[
  {
    "path": ".editorconfig",
    "content": "[*.{cpp,h,hpp,sh,md,cfg,sample}]\nindent_style = tab\nindent_size = 4\nbrace_style = same_line\n\n[*.{yml,yaml}]\nindent_style = space\nindent_size = 2\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: aristocratos\npatreon: # Replace with a single Patreon username\nopen_collective: # Replace with a single Open Collective username\nko_fi: aristocratos\ntidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel\ncommunity_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry\nliberapay: # Replace with a single Liberapay username\nissuehunt: # Replace with a single IssueHunt username\notechie: # Replace with a single Otechie username\ncustom: https://paypal.me/aristocratos\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\nlabels: bug\n\n---\n\n**Read the README.md and search for similar issues before posting a bug report!**\n\n<!-- Any bug that can be solved by just reading the [prerequisites](https://github.com/aristocratos/btop#prerequisites) section of the README will likely be ignored. -->\n\n**Describe the bug**\n\n<!-- A clear and concise description of what the bug is. -->\n\n**To Reproduce**\n\n<!-- Steps to reproduce the behavior. ->\n\n**Expected behavior**\n\n<!-- A clear and concise description of what you expected to happen. -->\n\n**Screenshots**\n\n<!-- If applicable, add screenshots to help explain your problem. -->\n\n**Info (please complete the following information):**\n - btop++ version: `btop --version`\n   - If using snap: `snap info btop`\n - Binary: [self compiled or static binary from release]\n - Architecture: [x86_64, aarch64, etc.] `uname -m`\n - Platform: [Linux, FreeBSD, OsX]\n - (Linux) Kernel: `uname -r`\n - (OSX/FreeBSD) Os release version:\n - Terminal used:\n - Font used:\n\n**Additional context**\n\n<!-- Contents of `~/.local/state/btop.log` -->\n\n<!-- Note: The snap uses: `~/snap/btop/current/.local/state/btop.log` -->\n\n<!-- (try running btop with `--debug` flag if btop.log is empty) -->\n\n**GDB Backtrace**\n\n<!-- If btop++ is crashing at start the following steps could be helpful: -->\n\n<!-- (Extra helpful if compiled with `make OPTFLAGS=\"-O0 -g\"`) -->\n\n<!-- 1. run (linux): `gdb btop` (macos): `lldb btop` -->\n\n<!-- 2. `r` to run, wait for crash and press enter if prompted, CTRL+L to clear screen if needed. -->\n\n<!-- 3. (gdb): `thread apply all bt` (lldb): `bt all` to get backtrace for all threads -->\n\n<!-- 4. Copy and paste the backtrace here: -->\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\nlabels: feature\n\n---\n\n**Is your feature request related to a problem? Please describe.**\n\n<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->\n\n**Describe the solution you'd like**\n\n<!-- A clear and concise description of what you want to happen. -->\n\n**Describe alternatives you've considered**\n\n<!-- A clear and concise description of any alternative solutions or features you've considered. -->\n\n**Additional context**\n\n<!-- Add any other context or screenshots about the feature request here. -->\n"
  },
  {
    "path": ".github/renovate.json5",
    "content": "{\n    $schema: \"https://docs.renovatebot.com/renovate-schema.json\",\n    extends: [\"config:recommended\"],\n}\n"
  },
  {
    "path": ".github/workflows/cmake-freebsd.yml",
    "content": "name: FreeBSD CMake\n\non:\n  workflow_dispatch:\n  push:\n    branches: main\n    tags-ignore: '*.*'\n    paths:\n      - '.github/workflows/cmake-freebsd.yml'\n      - 'CMakeLists.txt'\n      - 'cmake/**'\n      - 'include/**'\n      - 'src/*pp'\n      - 'src/freebsd/*pp'\n  pull_request:\n    branches: main\n    paths:\n      - '.github/workflows/cmake-freebsd.yml'\n      - 'CMakeLists.txt'\n      - 'cmake/**'\n      - 'include/**'\n      - 'src/*pp'\n      - 'src/freebsd/*pp'\n\njobs:\n  build:\n    name: freebsd-${{ matrix.version}}-${{ matrix.arch}}\n    runs-on: ubuntu-24.04\n    concurrency:\n      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ matrix.arch }}-${{ matrix.version }}\n      cancel-in-progress: true\n    strategy:\n      matrix:\n        arch: ['aarch64', 'x86_64']\n        version: ['14.3', '15.0']\n    steps:\n      - uses: actions/checkout@v6\n\n      - name: Compile\n        uses: vmactions/freebsd-vm@v1\n        with:\n          arch: ${{ matrix.arch }}\n          release: ${{ matrix.version }}\n          usesh: true\n          prepare: pkg install -y cmake git ninja\n          run: |\n            cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug\n            cmake --build build --verbose\n            ctest --test-dir build\n"
  },
  {
    "path": ".github/workflows/cmake-linux.yml",
    "content": "name: Linux CMake\n\non:\n  workflow_dispatch:\n  push:\n    branches: main\n    tags-ignore: '*.*'\n    paths:\n      - '.github/workflows/cmake-linux.yml'\n      - 'CMakeLists.txt'\n      - 'cmake/**'\n      - 'include/**'\n      - 'src/*pp'\n      - 'src/linux/*pp'\n  pull_request:\n    branches: main\n    paths:\n      - '.github/workflows/cmake-linux.yml'\n      - 'CMakeLists.txt'\n      - 'cmake/**'\n      - 'include/**'\n      - 'src/*pp'\n      - 'src/linux/*pp'\n\njobs:\n  build:\n    name: ${{ matrix.compiler }}-${{ matrix.version }}\n    runs-on: ubuntu-24.04\n    concurrency:\n      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ matrix.compiler }}-${{ matrix.version }}\n      cancel-in-progress: true\n    strategy:\n      matrix:\n        include:\n          - compiler: clang\n            version: 19\n          - compiler: clang\n            version: 20\n          - compiler: clang\n            version: 21\n          - compiler: gcc\n            version: 14\n    steps:\n      - uses: actions/checkout@v6\n\n      - name: Install clang ${{ matrix.version }}\n        if: ${{ matrix.compiler == 'clang' }}\n        run: wget -qO - https://apt.llvm.org/llvm.sh | sudo bash -s -- ${{ matrix.version }} all\n\n      - name: Configure\n        run: |\n          if [[ \"${{ matrix.compiler }}\" == \"clang\" ]]; then\n            export CC=clang-${{ matrix.version }}\n            export CXX=clang++-${{ matrix.version }}\n            export CXXFLAGS=\"-stdlib=libc++\"\n            export LDFLAGS=\"-fuse-ld=lld -rtlib=compiler-rt -unwindlib=libunwind\"\n          else\n            export CC=gcc-${{ matrix.version }}\n            export CXX=g++-${{ matrix.version }}\n          fi\n          cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug\n\n      - name: Compile\n        run: cmake --build build --verbose\n\n      - name: Test\n        run: ctest --test-dir build\n"
  },
  {
    "path": ".github/workflows/cmake-macos.yml",
    "content": "name: macOS CMake\n\non:\n  workflow_dispatch:\n  push:\n    branches: main\n    tags-ignore: '*.*'\n    paths:\n      - '.github/workflows/cmake-macos.yml'\n      - 'CMakeLists.txt'\n      - 'cmake/**'\n      - 'include/**'\n      - 'src/*pp'\n      - 'src/osx/*pp'\n  pull_request:\n    branches: main\n    paths:\n      - '.github/workflows/cmake-macos.yml'\n      - 'CMakeLists.txt'\n      - 'cmake/**'\n      - 'include/**'\n      - 'src/*pp'\n      - 'src/osx/*pp'\n\njobs:\n  cmake_build_on_macos:\n    runs-on: macos-15\n    concurrency:\n      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}\n      cancel-in-progress: true\n    steps:\n      - uses: actions/checkout@v6\n\n      - name: Install build tools\n        run: |\n          export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1\n          brew update --quiet\n          brew install --force --overwrite cmake llvm lld ninja\n\n      - name: Configure\n        run: |\n          export LLVM_PREFIX=\"$(brew --prefix llvm)\"\n          export LLD_PREFIX=\"$(brew --prefix lld)\"\n          export CXX=\"$LLVM_PREFIX/bin/clang++\"\n          export CPPFLAGS=\"-I$LLVM_PREFIX/include\"\n          export LDFLAGS=\"-L$LLVM_PREFIX/lib -L$LLVM_PREFIX/lib/c++ -Wl,-rpath,$LLVM_PREFIX/lib/c++ -fuse-ld=$LLD_PREFIX/bin/ld64.lld\"\n          cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug\n\n      - name: Compile\n        run: cmake --build build --verbose\n\n      - name: Test\n        run: ctest --test-dir build\n"
  },
  {
    "path": ".github/workflows/cmake-netbsd.yml",
    "content": "name: NetBSD CMake\n\non:\n  workflow_dispatch:\n  push:\n    branches: main\n    tags-ignore: '*.*'\n    paths:\n      - '.github/workflows/cmake-netbsd.yml'\n      - 'CMakeLists.txt'\n      - 'cmake/**'\n      - 'include/**'\n      - 'src/*pp'\n      - 'src/netbsd/*pp'\n  pull_request:\n    branches: main\n    paths:\n      - '.github/workflows/cmake-netbsd.yml'\n      - 'CMakeLists.txt'\n      - 'cmake/**'\n      - 'include/**'\n      - 'src/*pp'\n      - 'src/netbsd/*pp'\n\njobs:\n  build:\n    name: netbsd-${{ matrix.version }}-${{ matrix.arch }}\n    runs-on: ubuntu-24.04\n    concurrency:\n      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ matrix.arch }}-${{ matrix.version }}\n      cancel-in-progress: true\n    strategy:\n      matrix:\n        arch: ['aarch64', 'amd64']\n        version: ['10.1']\n    steps:\n      - uses: actions/checkout@v6\n\n      - name: Compile\n        uses: vmactions/netbsd-vm@v1\n        with:\n          arch: ${{ matrix.arch }}\n          release: ${{ matrix.version }}\n          usesh: true\n          prepare: |\n            export PATH=\"/usr/pkg/sbin:/usr/pkg/bin:$PATH\"\n            export PKG_PATH=\"https://ftp.netbsd.org/pub/pkgsrc/packages/NetBSD/${{ matrix.arch }}/${{ matrix.version }}/All/\"\n            /usr/sbin/pkg_add pkgin\n            pkgin -y install cmake gcc14 git ninja-build\n          run: |\n            export CXX=\"/usr/pkg/gcc14/bin/g++\"\n            cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug\n            cmake --build build --verbose\n            ctest --test-dir build\n"
  },
  {
    "path": ".github/workflows/cmake-openbsd.yml",
    "content": "name: OpenBSD CMake\n\non:\n  workflow_dispatch:\n  push:\n    branches: main\n    tags-ignore: '*.*'\n    paths:\n      - '.github/workflows/cmake-openbsd.yml'\n      - 'CMakeLists.txt'\n      - 'cmake/**'\n      - 'include/**'\n      - 'src/*pp'\n      - 'src/openbsd/*pp'\n  pull_request:\n    branches: main\n    paths:\n      - '.github/workflows/cmake-openbsd.yml'\n      - 'CMakeLists.txt'\n      - 'cmake/**'\n      - 'include/**'\n      - 'src/*pp'\n      - 'src/openbsd/*pp'\n\njobs:\n  build:\n    name: openbsd-${{ matrix.version}}-${{ matrix.arch}}\n    runs-on: ubuntu-24.04\n    concurrency:\n      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ matrix.arch }}-${{ matrix.version }}\n      cancel-in-progress: true\n    strategy:\n      matrix:\n        arch: ['aarch64', 'x86_64']\n        version: ['7.8']\n    steps:\n      - uses: actions/checkout@v6\n\n      - name: Compile\n        uses: vmactions/openbsd-vm@v1\n        with:\n          arch: ${{ matrix.arch }}\n          release: ${{ matrix.version }}\n          usesh: true\n          prepare: pkg_add cmake git ninja\n          run: |\n            cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug\n            cmake --build build --verbose\n            ctest --test-dir build\n"
  },
  {
    "path": ".github/workflows/continuous-build-freebsd.yml",
    "content": "name: Continuous Build FreeBSD\n\non:\n  workflow_dispatch:\n  push:\n    branches:\n      - main\n    tags-ignore:\n      - '*.*'\n    paths:\n      - 'src/**'\n      - '!src/linux/**'\n      - '!src/osx/**'\n      - '!src/netbsd/**'\n      - '!src/openbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/continuous-build-freebsd.yml'\n  pull_request:\n    branches:\n      - main\n    paths:\n      - 'src/**'\n      - '!src/linux/**'\n      - '!src/osx/**'\n      - '!src/netbsd/**'\n      - '!src/openbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/continuous-build-freebsd.yml'\n\njobs:\n  build-freebsd:\n    runs-on: ubuntu-24.04\n    timeout-minutes: 20\n    strategy:\n      matrix:\n        compiler: [\"clang++\", \"g++\"]\n    steps:\n      - uses: actions/checkout@v6\n\n      - name: Compile\n        uses: vmactions/freebsd-vm@v1\n        with:\n          release: '14.3'\n          usesh: true\n          prepare: |\n            pkg install -y gmake gcc15 coreutils git lowdown\n            git config --global --add safe.directory /home/runner/work/btop/btop\n          run: |\n            if [ \"${{ matrix.compiler }}\" == \"g++\" ]; then\n              CXX=g++15\n              COMPILER=gcc\n            else\n              CXX=clang++\n              COMPILER=llvm\n            fi\n            gmake STATIC=true STRIP=true\n            GIT_HASH=$(git rev-parse --short \"$GITHUB_SHA\")\n            mv bin/btop bin/btop-\"$COMPILER\"-\"$GIT_HASH\"\n            ls -alh bin\n\n      - uses: actions/upload-artifact@v7\n        with:\n          name: btop-x86_64-freebsd-14-${{ matrix.compiler }}\n          path: 'bin/*'\n          if-no-files-found: error\n"
  },
  {
    "path": ".github/workflows/continuous-build-gpu.yml",
    "content": "name: Continuous Build Gpu\n\non:\n  workflow_dispatch:\n  push:\n    branches:\n      - main\n    tags-ignore:\n      - '*.*'\n    paths:\n      - 'src/**'\n      - '!src/osx/**'\n      - '!src/freebsd/**'\n      - '!src/netbsd/**'\n      - '!src/openbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/continuous-build-gpu.yml'\n  pull_request:\n    branches:\n      - main\n    paths:\n      - 'src/**'\n      - '!src/osx/**'\n      - '!src/freebsd/**'\n      - '!src/netbsd/**'\n      - '!src/openbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/continuous-build-gpu.yml'\n\njobs:\n  gpu_build_linux:\n    runs-on: ubuntu-24.04\n    container: alpine:edge\n    concurrency:\n      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}\n      cancel-in-progress: true\n    steps:\n      - uses: actions/checkout@v6\n\n      - name: Install build tools\n        run: apk add --no-cache --update gcc g++ make linux-headers\n\n      - name: Compile\n        run: make CXX=g++ GPU_SUPPORT=true\n\n"
  },
  {
    "path": ".github/workflows/continuous-build-linux.yml",
    "content": "name: Continuous Build Linux\n\non:\n  workflow_dispatch:\n  push:\n    branches: main\n    tags-ignore: '*.*'\n    paths:\n      - 'src/**'\n      - '!src/osx/**'\n      - '!src/freebsd/**'\n      - '!src/netbsd/**'\n      - '!src/openbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/continuous-build-linux.yml'\n  pull_request:\n    branches: main\n    paths:\n      - 'src/**'\n      - '!src/osx/**'\n      - '!src/freebsd/**'\n      - '!src/netbsd/**'\n      - '!src/openbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/continuous-build-linux.yml'\n\njobs:\n  build:\n    runs-on: ubuntu-24.04\n    concurrency:\n      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ matrix.toolchain }}\n      cancel-in-progress: true\n    continue-on-error: true\n    strategy:\n      matrix:\n        toolchain:\n          - aarch64-unknown-linux-musl\n          - arm-unknown-linux-musleabi\n          - arm-unknown-linux-musleabihf\n          - armv7-unknown-linux-musleabi\n          - armv7-unknown-linux-musleabihf\n          - i586-unknown-linux-musl\n          - i686-unknown-linux-musl\n          - m68k-unknown-linux-musl\n          - mips-unknown-linux-musl\n          - mips-unknown-linux-muslsf\n          - mips64-unknown-linux-musl\n          - mips64el-unknown-linux-musl\n          - mipsel-unknown-linux-musl\n          - mipsel-unknown-linux-muslsf\n          - powerpc-unknown-linux-musl\n          - powerpc64-unknown-linux-musl\n          - powerpc64le-unknown-linux-musl\n          - powerpcle-unknown-linux-musl\n          - riscv32-unknown-linux-musl\n          - riscv64-unknown-linux-musl\n          - s390x-ibm-linux-musl\n          - x86_64-unknown-linux-musl\n\n    steps:\n      - uses: actions/checkout@v6\n\n      - name: Install cross toolchain\n        run: |\n          wget -q -P /tmp https://github.com/cross-tools/musl-cross/releases/download/20250929/${{ matrix.toolchain }}.tar.xz\n          wget -q -P /tmp https://github.com/cross-tools/musl-cross/releases/download/20250929/${{ matrix.toolchain }}.tar.xz.sha256\n          echo \"$(cat /tmp/${{ matrix.toolchain }}.tar.xz.sha256) /tmp/${{ matrix.toolchain }}.tar.xz\" | sha256sum --check --status\n          mkdir -p /opt/x-tools/\n          tar -xf /tmp/${{ matrix.toolchain }}.tar.xz -C /opt/x-tools\n\n      - name: Compile\n        run: CXX=/opt/x-tools/${{ matrix.toolchain }}/bin/${{ matrix.toolchain }}-g++ make STATIC=true STRIP=true\n\n      - name: Create binary artifacts\n        run: |\n          TOOLCHAIN=${{ matrix.toolchain }}\n          GIT_HASH=$(git rev-parse --short \"${{ github.sha }}\")\n          FILENAME=btop-${TOOLCHAIN/linux-musl/}-$GIT_HASH\n          mv bin/btop bin/$FILENAME\n\n      - name: Upload artifacts\n        uses: actions/upload-artifact@v7\n        with:\n          name: btop-${{ matrix.toolchain }}\n          path: '${{ github.workspace }}/bin/*'\n"
  },
  {
    "path": ".github/workflows/continuous-build-macos.yml",
    "content": "name: Continuous Build MacOS\n\non:\n  workflow_dispatch:\n  push:\n    branches:\n      - main\n    tags-ignore:\n      - '*.*'\n    paths:\n      - 'src/**'\n      - '!src/linux/**'\n      - '!src/freebsd/**'\n      - '!src/netbsd/**'\n      - '!src/openbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/continuous-build-macos.yml'\n  pull_request:\n    branches:\n      - main\n    paths:\n      - 'src/**'\n      - '!src/linux/**'\n      - '!src/freebsd/**'\n      - '!src/netbsd/**'\n      - '!src/openbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/continuous-build-macos.yml'\n\njobs:\n  build-macos:\n    strategy:\n      matrix:\n        os:\n         # - {runner: 'macos-13', version: 'Ventura'}\n          - {runner: 'macos-14', version: 'Sonoma'}\n          - {runner: 'macos-15', version: 'Sequoia'}\n    runs-on: ${{ matrix.os.runner }}\n    steps:\n      - uses: maxim-lobanov/setup-xcode@v1\n        with:\n          xcode-version: latest-stable\n\n      - uses: actions/checkout@v6\n\n      - name: Install build tools\n        run: |\n          export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1\n          brew update --quiet\n          brew install --force --overwrite gcc@15 lowdown\n\n      - name: Compile\n        run: |\n          make CXX=$(brew --prefix)/bin/g++-15\n          GIT_HASH=$(git rev-parse --short \"$GITHUB_SHA\")\n          mv bin/btop bin/btop-arm64-${{ matrix.os.runner }}-${{ matrix.os.version }}-$GIT_HASH\n          ls -alh bin\n\n      - uses: actions/upload-artifact@v7\n        with:\n          name: btop-arm64-${{ matrix.os.runner }}-${{ matrix.os.version }}\n          path: 'bin/*'\n"
  },
  {
    "path": ".github/workflows/continuous-build-netbsd.yml",
    "content": "name: Continuous Build NetBSD\n\non:\n  workflow_dispatch:\n  push:\n    branches:\n      - main\n    tags-ignore:\n      - '*.*'\n    paths:\n      - 'src/**'\n      - '!src/linux/**'\n      - '!src/osx/**'\n      - '!src/freebsd/**'\n      - '!src/openbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/continuous-build-netbsd.yml'\n  pull_request:\n    branches:\n      - main\n    paths:\n      - 'src/**'\n      - '!src/linux/**'\n      - '!src/osx/**'\n      - '!src/freebsd/**'\n      - '!src/openbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/continuous-build-netbsd.yml'\n\njobs:\n  build-netbsd:\n    runs-on: ubuntu-24.04\n    timeout-minutes: 20\n    steps:\n      - uses: actions/checkout@v6\n\n      - name: Compile\n        uses: vmactions/netbsd-vm@v1\n\n        with:\n          release: '10.1'\n          usesh: true\n          prepare: |\n            PATH=\"/usr/pkg/sbin:/usr/pkg/bin:$PATH\"\n            PKG_PATH=\"https://ftp.netbsd.org/pub/pkgsrc/packages/NetBSD/amd64/10.1/All/\"\n            export PATH PKG_PATH\n            /usr/sbin/pkg_add pkgin\n            pkgin -y install gmake gcc14 coreutils git\n            git config --global --add safe.directory /home/runner/work/btop/btop\n          run: |\n            gmake CXX=/usr/pkg/gcc14/bin/g++ CXXFLAGS='-DNDEBUG -I/usr/pkg/gcc10/include -I/usr/include -I/usr/pkg/include' STATIC=true STRIP=true\n            GIT_HASH=$(git rev-parse --short \"$GITHUB_SHA\")\n            mv bin/btop bin/btop-GCC10-\"$GIT_HASH\"\n            ls -alh bin\n\n      - uses: actions/upload-artifact@v7\n        with:\n          name: btop-x86_64-netbsd-9.3\n          path: 'bin/*'\n          if-no-files-found: error\n\n"
  },
  {
    "path": ".github/workflows/continuous-build-openbsd.yml",
    "content": "name: Continuous Build OpenBSD\n\non:\n  workflow_dispatch:\n  push:\n    branches:\n      - main\n    tags-ignore:\n      - '*.*'\n    paths:\n      - 'src/**'\n      - '!src/linux/**'\n      - '!src/osx/**'\n      - '!src/freebsd/**'\n      - '!src/netbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/continuous-build-openbsd.yml'\n  pull_request:\n    branches:\n      - main\n    paths:\n      - 'src/**'\n      - '!src/linux/**'\n      - '!src/osx/**'\n      - '!src/freebsd/**'\n      - '!src/netbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/continuous-build-openbsd.yml'\n\njobs:\n  build-openbsd:\n    runs-on: ubuntu-24.04\n    timeout-minutes: 20\n    steps:\n      - uses: actions/checkout@v6\n\n      - name: Compile\n        uses: vmactions/openbsd-vm@v1\n        with:\n          release: '7.8'\n          usesh: true\n          prepare: |\n            pkg_add gmake coreutils git lowdown\n            git config --global --add safe.directory /home/runner/work/btop/btop\n          run: |\n            gmake STATIC=true STRIP=true\n            GIT_HASH=$(git rev-parse --short \"$GITHUB_SHA\")\n            mv bin/btop bin/btop-\"$GIT_HASH\"\n\n      - uses: actions/upload-artifact@v7\n        with:\n          name: btop-x86_64-openbsd-7.8\n          path: 'bin/*'\n          if-no-files-found: error\n"
  },
  {
    "path": ".github/workflows/test-snap-can-build.yml",
    "content": "name: 🧪 Test snap can be built on x86_64\non:\n  workflow_dispatch:\n  push:\n   branches: [ main ]\n   tags-ignore:\n      - '*.*'\n   paths:\n      - 'src/**'\n      - '!src/osx/**'\n      - '!src/freebsd/**'\n      - '!src/netbsd/**'\n      - '!src/openbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/test-snap-can-build.yml'\n      - 'snap/snapcraft.yaml'\n  pull_request:\n   branches: [ main ]\n   paths:\n      - 'src/**'\n      - '!src/osx/**'\n      - '!src/freebsd/**'\n      - '!src/netbsd/**'\n      - '!src/openbsd/**'\n      - 'include/**'\n      - 'Makefile'\n      - '.github/workflows/test-snap-can-build.yml'\n      - 'snap/snapcraft.yaml'\n\njobs:\n  build:\n    runs-on: ubuntu-24.04\n    strategy:\n      matrix:\n        node-version: [20.x]\n\n    steps:\n      - uses: actions/checkout@v6\n\n      - uses: snapcore/action-build@v1\n        id: build\n\n      - uses: diddlesnaps/snapcraft-review-action@v1\n        with:\n          snap: ${{ steps.build.outputs.snap }}\n          isClassic: 'false'\n"
  },
  {
    "path": ".gitignore",
    "content": "# gitginore template for creating Snap packages\n# website: https://snapcraft.io/\n\nparts/\nprime/\nstage/\n*.snap\n\n# Snapcraft global state tracking data(automatically generated)\n# https://forum.snapcraft.io/t/location-to-save-global-state/768\n/snap/.snapcraft/\n\n# Source archive packed by `snapcraft cleanbuild` before pushing to the LXD container\n/*_source.tar.bz2\n\n# Prerequisites\n*.d\n\n# Compiled Object files\n*.slo\n*.lo\n*.o\n*.obj\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Compiled Dynamic libraries\n*.so\n*.dylib\n*.dll\n\n# Fortran module files\n*.mod\n*.smod\n\n# Compiled Static libraries\n*.lai\n*.la\n*.a\n*.lib\n\n# Executables\n*.exe\n*.out\n*.app\n\n# Compiled man page\nbtop.1\n\nbuild\nbin\nbtop\n/obj/\nconfig.h\n.*/\n\n# Optional libraries\nlib/rocm_smi_lib\n\n# Don't ignore .github directory\n!.github/\n\n# Ignore files created by Qt Creator\n*.config\n*.creator\n*.creator.user\n*.creator.user.*\n*.cflags\n*.cxxflags\n*.files\n*.includes\n\n# CMake\nCMakeLists.txt.user\nCMakeCache.txt\nCMakeFiles\nCMakeScripts\nTesting\nMakefile\ncmake_install.cmake\ninstall_manifest.txt\ncompile_commands.json\nCTestTestfile.cmake\n_deps\nCMakeUserPresets.json\n\n# CLion\ncmake-build-*\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "## v1.4.6\n\nReferences | Description | Author(s)\n--- | --- | ---\n#1272 | Skip 'H' and 'HX' suffix in AMD cpu name trimming | @ramdomPTM\n#1268 | feature: add process renice functionality | @goddamnparticle\n#1285 | Revert \"Use /sys/dev/block/MAJOR:MINOR instead of /sys/block/NAME for disk I/O\" #1270 | @deckstose\n#1277 | feat: Introduce cpu frequency display modes | @emiliopedrollo\n#1282 | Fix CPU frequency detection for LoongArch CPUs | @Twopic2\n#1275 | fix arrow keys that send 'O' instead of '[' | @vandabbin\n#1251 | OpenBSD: battery: add support for watthour and watts sensors | @shtrophic\n#1208 | Add Gotham theme | @jrebs\n#1291 | Fix macOS deadlocks and race conditions in collector threads #1292 | @kuzmeech\n#1296 | fix: btop crash on arm cpu | @emiliopedrollo @zenofile\n#984 | Added ability to set which gpu vendors to enable | @thedustinmiller\n#1274 | added tree toggle of expand/collapse for children of process | @irabrine\n#1300 | Use right key codes to match f1 and f2 keys | @vandabbin\n#1305 | Handle missing SMC gracefully on macOS | @achille\n#1309 | Fix redraw in proc list when changing sort order | @vandabbin\n#1304 | Fix load average and GPU watts leaking past box border | @vandabbin\n#1220 | feat: respect effective cpus from cgroup | @deckstose\n#1218 | feat: display container engine | @deckstose\n#1315 | feat: raise cpp standard to c++23 | @deckstose\nd0cbaf7 | Add configuration toggle for terminal synchronization | @aristocratos\n#1306 | Implement feat Process list pausing | @vandabbin\n#1322 | flip name, command, and user sorting | @vandabbin\n#1334 | fix tty theme for pause banner | @vandabbin\n#1325 | test: add test harness with ctest | @deckstose\n#1339 | fix: skip first argument of argv | @AlvaroParker\n#1357 | feat: add --themes-dir flag | @adeci\n#1359 | fix: don't over-/underflow when parsing --update argument | @yinghao-w\n#1362 | fix segfault on musl systems | @v1cont\n#1363 | Pass only static duration strings to Config::set in Config::apply_preset | @yinghao-w\n#1366 | fix: cpu per-thread totals not reaching 100% | @Tom94\n#1367 | Fix: Align boxes when Cpu bottom and Gpu on | @yinghao-w\n#1372 | Minor fixes and improvements for NetBSD | @fraggerfox\n#1377 | Fixed GPU rendering | @TheSovietPancakes\n#1379 | Fix: Always collect GPU data when cpu_graph_lower = \"Auto\" | @yinghao-w\n#1393 | Fix: humanized units shortening | @yinghao-w\n#1401 | Feat: add mouse dragging of scrollbar | @yinghao-w\n#1399 | feat: add cli option to dump default config | @deckstose\ne969f43 | Added \"save_config_on_exit\" option to configuration | @aristocratos\n\n## v1.4.5\n\nReferences | Description | Author(s)\n--- | --- | ---\n#1254 | Bump bundled fmt to 12.0.0 | @deckstose\n#1242 | Enable vim movement in help menu | @botantony\n#948 | Remove reduntant symbols in tree view | @Denizantip\n#1249 | Use /sys/dev/block/MAJOR:MINOR instead of /sys/block/NAME for disk I/O | @CountBleck\n#1227 | feat: display CPU power draw & fix GPU+load avg overwriting core info | @Tom94 and @YuriiShkrobut\n4f5abbb | Fix locale issues | @aristocratos\n#1165 | Add encode and decode meters on Nvidia GPUs | @sam-kirby\n#1197 | linux: Battery Time-to-full | @RadsammyT\n#1203 | Convert ascii escape codes in mountpoint names before reading statvfs | @deckstose\n#1198 | Fix presets erroring with gpu* usage | @entropylost\n#1191 | Fix --tty/--no-tty flag having no effect | @deckstose\n\n## v1.4.4\n\nReferences | Description | Author(s)\n--- | --- | ---\n#1185 | Fix auto-detection of CPU temp on Ampere boards | @bexcran\n589c133 | Fixed floating_humanizer() to work correctly when numeric delimiter isn't a dot. | @aristocratos\n#1157 | Add command line option to set an inital filter | @imwints\n#1172 | Make 100ms the minimal refresh rate. Exit gracefully if integer conversion in CLI parser fails. | @imwints\n#1031 | Lock/unlock config to avoid infinite recursion | @Jacajack\n#1156 | Fix incorrect positioning and start symbol of second title introduced in 2538d89 | @xDMPx\nffcd064 | Fix dangling reference warnings for GCC 13 and later | aristocratos\n\n## v1.4.3\n\nReferences | Description | Author(s)\n--- | --- | ---\nc3b225f | Revert e266ccd which broke str_to_upper() and str_to_lower() | @aristocratos\n#1137 | Enable additional checks in libc++ with the new hardening mode | @imwints\n#1135 | Remove redundant optimization flag | @imwints\n#1139 | Ignore incomplete filter regex, issue #1133 | @imwints\n\n## v1.4.2\n\nReferences | Description | Author(s)\n--- | --- | ---\nf1482fe | Fix process arguments appearing outside proc box by replacing ASCII control codes with blankspace, issue #1080 | @aristocratos\n#1130 | Fix problems shown by clang-tidy's performance checks | @imwints\n#1120 | Fix wrong error message and documentation of renamed option --utf-force | @t-webber @imwints\n#1128 | Flatten cmake module path | @imwints\n#1129 | CMake: Remove option to use mold  | @imwints\n#1047 | Update Terminus font link, fix typo, spelling, and grammar | @QinCai-rui\n#929 | Please clang with sanitizers | @bad-co-de\n#1126 | Fix MacOS tree-mode + aggregate memory/thread scaling issue | @xaskii\n#993 | Fix typo: Mhz -> MHz | @NyCodeGHG\n\n## v1.4.1\n\nReferences | Description | Author(s)\n--- | --- | ---\n#1111 #1112 | Various code fixes | @imwints\n#930 #931 | Various code fixes | @bad-co-de\n#1061 | Fixed typo | @polluks\n#1110 | Move the config parser in it's own module  | @imwints\n#1101 | Adding a menu option to show bitrates in base 10 separate from the setting to show bytes/bits in base 10 | @georgev93\n#1079 | Allow MidnightBSD to build btop using the existing freebsd support. | @laffer1\n#1098 | Use XDG_STATE_HOME to save logs | @imwints\n#1092 | Bump CMake version to 3.25 required for LINUX variable | @imwints\n#1058 | Replace brackets with arrows in net and proc box | @taha-yassine\n#1091 | Bump bundled fmt to 11.1.4 | @imwints\n#725 | cmake:  link to CMAKE_DL_LIBS | @alalazo\n#990 | Fix phoenix-night.theme marked as executable | @sertonix\n#1034 | Add Kanagawa-lotus and Kanagawa-wave themes | @philikarus\n#973 | Bump NetBSD version to 10.1 and FreeBSD version to 14.2. | @fraggerfox\n#1072 | Add dark version of adwaita theme: adwaita-dark | @k0tran\n#1036 | Resetting last selection on page navigation in optionsMenu to avoid unordered_map error | @seth-wood\n#1029 | Share the CPU name trimming code between platforms | @yarrick\n#1033 | Update Ryzen name trimming | @yarrick\n#1030 | Drop macos 12 build, add v14 and v15 | @yarrick\n#1028 | Fix cmake-macos workflow | @yarrick\n#1027 | Bump version of deprecated upload-artifact step | @yarrick\n#1025 | Update obsolete egrep call | @tywkeene\nb52069c | Fix menu crash when GPU_SUPPORT=false, issue #989 | @aristocratos\n#961 | Add 'Everforest Ligth Medium' theme | @mstuttgart\n#960 | Support intel GPUs before Gen-6 (patch from upstream) | @w8jcik\n#958 | intel_name_lookup_shim.c (get_intel_device_name): Fix SEGFAULT | @artyom-poptsov\n2e7208d | Fix rsmi_measure_pcie_speeds not saving, issue #934 | @aristocratos\nf3446ed | Show GPU Watt fractions when below 100W | @aristocratos\n\n| + more from @imwints @aristocratos\n\nBig thanks to @imwints for helping out with project maintenance, PR reviews and merging!\n\n## v1.4.0\n\nReferences | Description | Author(s)\n--- | --- | ---\n#703 | NetBSD Support | @fraggerfox\n#903 | Intel GPU support | @bjia56\n161e8f4 | Added warnings when toggling boxes and terminal size is to small | @aristocratos\n4210f5f | Fix missing core percentages, issue #792 | @aristocratos\n35857f8 | Various fixes for drawing GPU related information | @aristocratos\n#879 | fix divide 0 error when caculating disk usage percentage (#791) | @flylai\n#884 | fix io_graph_speeds parsing | @feihtthief\n#863 | V1 of Phoenix Night theme | @Firehawke\n3f384c0 | Fixed missing CPU core temps when too small to show core temp graphs, issues #792 #867 | @aristocratos\n97d2fb5 | Fixed missing IO graphs in IO mode, issue #867 | @aristocratos\n#840 | fix zero temp (#467) | @joske\n#850 | Fix comments (parsing) in theme files | @acidghost\n#806 | Add regex filtering | @imwints\n#836 | Fix typo in file existences check for voltage_now | @vsey\n#835 | Show time in days when remaining battery exceeds an estimation of 24h | @imwints\n#819 | (AMD Gpu) fix pwr_usage not being defined correctly during rsmi collection | @kalkafox\n#831 | macOS: fix crash if there exists a uid not associated with any user | @thecoder-001\n#796 | Fix rsmi device name buffer size | @davc0n\n#807 | Add gruvbox_light theme | @kk9uk\n#724 | Create man page for btop in Markdown | @ottok\n#734 | Include metadata in binary version output `btop --version` | @imwints\n#771 | collect: Fix reading of battery power draw on Linux | @Derppening\n\n## v1.3.2\n\nDescription | Author(s) | References\n--- | --- | ---\nfix: Can't detect librocm 6.0.x | @imwints, @aristocratos | #761\n\n## v1.3.1\n\nDescription | Author(s) | References\n--- | --- | ---\nGPU: Added support for dynamic loading of ROCm v6 libraries | @aristocratos, @fxzjshm | 5511131, #737\nIncrease max network interface name to 15 | @tessus | #714\nFix OpenBSD UTF-8 locale detection | @lcheylus, @imwints | #753, #717\nAdd hot-reloading of config file with CTRL+R or SIGUSR2 signal | @MartinPit | #722\nAdd battery power draw for linux and freebsd | @vsey | #689\nFix crash caused by string exception when cpu clock is exactly between 999.5 and 999.9 Mhz | @rkmcode | #735\nWrite newline at end of config file | @planet36 | #743\nAdd theme based on Everforest Dark Medium palette | @M-Sviridov | #746\nfix: don't mangle memory for zombie processes | @joske | #747\nShare common code from collect | @imwints | #756\nFixed incorrect used and available memory for OSX | | 4461a43\n\n## v1.3.0\n\n* Added Gpu Support Linux | @romner-set | PR #529\n\n* Added platform support for OpenBSD | @joske | PR #607\n\n* Enable macos clang | @muneebmahmed | PR #666\n\n* Fix Apple Silicon CPUs misprinted | @masiboss | PR #679\n\n* Cmake support for MacOS | @imwints | PR #675\n\n* Elementarish theme: color update according to Elementary palette | @stradicat | PR #660\n\n* Add alternative key codes for Delete, Insert, Home, End | @ivanp7 | PR #659\n\n* Fix scrollbar not clearing sometimes. | @DecklynKern | PR #643\n\n* Add keybind for toggling memory display mode in PROC box | @rahulaggarwal965 | PR #623\n\n* Minor string initialization improvement | @imwints | PR #636\n\n* Made disks statvfs logic asynchronous. | @crestfallnatwork | PR #633\n\n* Fix signal list on non-linux/weird linux platforms | @lvxnull | PR #630\n\n* Add option to accumulate a child's resources in parent in tree-view | @imwints | PR #618\n\n* Add CMake support for Linux | @imwints | PR #589\n\n* Horizon theme | @SidVeld | PR #610\n\n* Fix short conversion of 1000-1023 *iB | @scorpion-26 | #609\n\n* Fix integer overflows in btop_collect.cpp | @dorrellmw | #546\n\n* Support compiling with LLVM | @imwints | #510\n\n* Fix getting zfs pool name with '.' char in freebsd | @jfouquart | #602\n\n* [macos/freebsd] support gcc13 | @joske | #600\n\n* FreeBSD swap info | @rrveex | #560\n\n* Create adwaita.theme | @flipflop133 | #485\n\n* Try get terminal size of \"/dev/tty\" if stdout fails | @imwints | PR #627\n\n* Refresh rate program argument | @imwints | PR #640\n\n* Improved error handling when determining the config directory | @imwints | #652\n\n* Use native POSIX polling syscalls to read input | @lvxnull | #624\n\n* Conditional compile on Big Sur and up | @joske | PR #690\n\n+ Various fixes by @imwints, @simplepad, @joske, @gwena, @cpalv, @iambeingtracked, @mattico, @NexAdn\n\n## v1.2.13\n\n* Makefile: VERBOSE=true flag for Makefile to display all compiler commands and fixed so already set CXXFLAGS and LDFLAGS are displayed.\n\n* Makefile: Added autodetection for gcc12 to make compiling on macos Ventura easier.\n\n* Changed: Reverted back to sysconf(_SC_NPROCESSORS_ONLN) for Cpu core count ant let the new dynamic update fix if cores are turned on later\n\n* Fixed: Ignore disks that fails in statvfs64() to avoid slowdowns and possible crashes.\n\n* Fixed: Moved up get_cpuHz() in the execution order to get better cpu clock reading.\n\n* Added: proc tree view: if there's more than 40 width left, try to print full cmd, by @Superty\n\n* Fixed: Show the first IP of the interface in NET box instead of the last, by @correabuscar\n\n* Changed: Replace getnameinfo with inet_ntop [on Linux], by @correabuscar\n\n* Fixed: Not picking up last username from /etc/passwd\n\n* Fixed: Process nice value underflowing, issue #461\n\n* Changed: Replace getnameinfo with inet_ntop [on FreeBSD], by @correabuscar\n\n* Changed: Replace getnameinfo with inet_ntop [on macos], by @correabuscar\n\n## v1.2.12\n\n* Added: Dynamic updating of max number of CPU cores.\n\n## v1.2.11\n\n* Fixed: Number of cores wrongly detected for Ryzen in rare cases.\n\n## v1.2.10\n\n* Fixed: Process tree filtering not case insensitive\n\n* Added: Paper theme, by @s6muel\n\n* Fixed: Extra checks to avoid crash on trying to replace empty strings in tree mode\n\n* Fixed: Crashing when cores are offline\n\n* Fixed: Cpu::collect() core count counter...\n\n* Changed: Using sysconf(_SC_NPROCESSORS_CONF) for number of cores instead of sysconf(_SC_NPROCESSORS_ONLN)\n\n* Maintenance: Code cleanup, by @stefanos82\n\n## v1.2.9\n\n* Fixed: Memory values not clearing properly when not in graph mode in mem box\n\n* Changed: kyli0x theme color update, by @kyli0x\n\n* Added: Elementarish theme, by @dennismayr\n\n* Added: key \"?\" to see help, by @mohi001\n\n* Added: solarized_light theme, by @Fingerzam\n\n* Changed: Made ZFS stats collection compatible with zfs_pools_only option, by @simplepad\n\n* Changed: Rewrite of process sorting and tree generation including fixes for tree sorting and mouse support\n\n* Added: Option to hide the small cpu graphs for processes\n\n* Changed: Small graphs now show colors for each character\n\n* Fixed: Getting selfpath on macos (fix for finding theme folder)\n\n## v1.2.8\n\n* Added: Support for ZFS pool io stats monitoring, by @simplepad\n\n* Added: Filtering of kernel processes, by @0xJoeMama\n\n* Added: New theme everforest-dark-hard, by @iambeingtracked\n\n* Added: New theme tomorrow-night, by @appuchias\n\n* Changed: Disable battery monitoring if it fails instead of exiting\n\n## v1.2.7\n\n* Fixed: Disk IO stats for individual partitions instead of whole disk (Linux)\n\n* Added: Case insensitive process filtering, by @abrasumente233\n\n* Added: Include ZFS ARC in cached/available memory on Linux, by @mattico\n\n* Added: Desktop entry and icons, by @yonatan8070\n\n* Fixed: Net sync scale bug\n\n* Added: tokyo-night & tokyo-storm themes, by @Schievel1\n\n## v1.2.6\n\n* Fixed: Wrong memory unit when shorten and size is less than 10, by @mohi001\n\n* Fixed: Use cpu cores average temp if missing cpu package temp for FreeBSD\n\n* Changed: Enter symbol to a more common variant\n\n## v1.2.5\n\n* Fixed: Fallback to less accurate UTF8 char count if conversion to wstring fails\n\n* Fixed: Small ui fixes for mem and disks\n\n* Added: New theme HotPurpleTrafficLight, by @pallebone\n\n* Fixed: title_left symbol between auto and zero in the net box is not displayed, by @mrdotx\n\n* Fixed: Mouse mappings for net box\n\n## v1.2.4\n\n* Optimization: Proc::draw()\n\n* Fixed: Ignore duplicate disks with same mountpoint\n\n* Changed: Restrict command line for processes to 1000 characters to fix utf8 conversion errors\n\n* Added: add \"g\" and \"G\" to vim keys, by @mohi001\n\n## v1.2.3\n\n* Changed: floating_humanizer() now show fractions when shortened and value is < 10\n\n* Fixed: Process tree not redrawing properly\n\n* Fixed: string to wstring conversion crash when string is too big\n\n## v1.2.2\n\n* Changed: Reverted uncolor() back to using regex to fix delay in opening menu when compiled with musl\n\n* Added: Toggle for showing free disk space for privileged or normal users\n\n* Added: Clarification on signal screen that number can be manually entered\n\n## v1.2.1\n\n* Added: Arrow only after use of \"f\" when filtering processes, by @NavigationHazard\n\n* Fixed: Fx::uncolor not removing all escapes\n\n* Fixed: Text alignment for popup boxes\n\n* Fixed: Terminal resize warning getting stuck\n\n* Removed: Unnecessary counter for atomic_lock\n\n* Added: Percentage progress to Makefile\n\n* Fixed: Alignment of columns in proc box when wide UTF8 characters are used\n\n* Fixed: Battery meter draw fix\n\n## v1.2.0\n\n* Added: Support for FreeBSD, by @joske and @aristocratos\n\n* Fixed (again): Account for system rolling over net speeds in Net::collect()\n\n* Added: Theme gruvbox_material_dark, by @marcoradocchia\n\n* Added: Option for base 10 bytes/bits\n\n## v1.1.5\n\n* Fixed: Account for system rolling over net speeds in Net::collect()\n\n## v1.1.4\n\n* Fixed: Create dependency files in build directory when compiling, by @stwnt\n\n* Fixed: fix CPU temp fallback on macOS, by @joske\n\n* Changed: From rng::sort() to rng::stable_sort() for more stability\n\n* Fixed: in_avail() can always be zero, by @pg83\n\n## v1.1.3\n\n* Added: New theme ayu, by @AlphaNecron\n\n* Added: New theme gruvbox_dark_v2, by @pietryszak\n\n* Fixed: Macos cpu coretemp for Intel, by @joske\n\n* Added: New theme OneDark, by @vtmx\n\n* Fixed: Fixed network graph scale int rollover\n\n* Fixed: Suspected possibility of very rare stall in Input::clear()\n\n## v1.1.2\n\n* Fixed: SISEGV on macos Mojave, by @mgradowski\n\n* Fixed: Small optimizations and fixes to Mem::collect() and Input::get()\n\n* Fixed: Wrong unit for net_upload and net_download in config menu\n\n* Fixed: UTF-8 detection on macos\n\n* Fixed: coretemp iteration due to missing tempX_input, by @KFilipek\n\n* Fixed: coretemp ordering\n\n## v1.1.1\n\n* Added: Partial static build (libgcc, libstdc++) for macos\n\n* Changed: Continuous build macos switched to OSX 11.6 (Big Sur) and partial static build\n\n* Changed: Release binaries for macos switched to OSX 12 (Monterey) and partial static build\n\n## v1.1.0\n\n* Added: Support for OSX, by @joske and @aristocratos\n\n## v1.0.24\n\n* Changed: Collection ordering\n\n* Fixed: Restore all escape seq mouse modes on exit\n\n* Fixed: SIGINT not cleaning up on exit\n\n## v1.0.23\n\n* Fixed: Config parser missing first value when not including version header\n\n* Fixed: Vim keys menu lists selection\n\n* Fixed: Stall when clearing input queue on exit and queue is >1\n\n* Fixed: Inconsistent behaviour of \"q\" key in the menus\n\n## v1.0.22\n\n* Fixed: Bad values for disks and network on 32-bit\n\n## v1.0.21\n\n* Fixed: Removed extra spaces in cpu name\n\n* Added: / as alternative bind for filter\n\n* Fixed: Security issue when running with SUID bit set\n\n## v1.0.20\n\n* Added: Improved cpu sensor detection for Ryzen Mobile, by @adnanpri\n\n* Changed: Updated makefile\n\n* Changed: Regex for Fx::uncolor() changed to string search and replace\n\n* Changed: Removed all use of regex with dedicated string functions\n\n## v1.0.19\n\n* Fixed: Makefile now tests compiler flag compatibility\n\n## v1.0.18\n\n* Fixed: Makefile g++ -dumpmachine failure to get platform on some distros\n\n## v1.0.17\n\n* Changed: Reverted mutexes back to custom atomic bool based locks\n\n* Added: Static binaries switched to building with musl + more platforms, by @jan-guenter\n\n* Fixed: Improved battery detection, by @jan-guenter\n\n* Added: Displayed battery selectable in options menu\n\n* Fixed: Battery error if non existent battery named is entered\n\n## v1.0.16\n\n* Fixed: atomic_wait() and atomic_lock{} use cpu pause instructions instead of thread sleep\n\n* Fixed: Swapped from atomic bool spinlocks to mutexes to fix rare deadlock\n\n* Added: Continuous Build workflow for OSX branch, by @ShrirajHegde\n\n* Changed: Reverted thread mutex lock to atomic bool with wait and timeout\n\n* Changed: Removed unnecessary async threads in Runner thread\n\n* Added: Try to restart secondary thread in case of stall and additional error checks for ifstream in Proc::collect()\n\n* Fixed: change [k]ill to [K]ill when enabling vim keys, by @jlopezcur\n\n## v1.0.15\n\n* Fixed: Extra \"root\" partition when running in snap\n\n* Changed: Limit atomic_wait() to 1000ms to fix rare stall\n\n* Fixed: Removed unneeded lock in Runner::run()\n\n* Added: Toggle in options for enabling directional vim keys \"h,j,k,l\"\n\n## v1.0.14\n\n* Changed: Total system memory is checked at every update instead of once at start\n\n* Added: Continuous Build workflow, by @ShrirajHegde\n\n* Fixed: Uid -> User fallback to getpwuid() if failure for non static builds\n\n* Fixed: snap root disk and changed to compiler flags instead of env variables for detection\n\n* Added: Development branch for OSX, by @joske\n\n## v1.0.13\n\n* Changed: Graph empty symbol is now regular whitespace\n\n## v1.0.12\n\n* Fixed: Exception handling for faulty net download/upload speed\n\n* Fixed: Cpu percent formatting if over 10'000\n\n## v1.0.11\n\n* Changed: atomic_wait to use while loop instead of wait() because of rare stall when a signal handler is triggered while waiting\n\n* Fixed: Get real / mountpoint when running inside snap\n\n* Fixed: UTF8 set LANG and LC_ALL to empty before UTF8 search and fixed empty error msg on exit before signal handler init\n\n* Changed: Init will continue with a warning if UTF-8 locale are detected and it fails to set the locale\n\n## v1.0.10\n\n* Added: Wait for terminal size properties to be available at start\n\n* Changed: Stop second thread before updating terminal size variables\n\n* Changed: Moved check for valid terminal dimensions to before platform init\n\n* Added: Check for empty percentage deques\n\n* Changed: Cpu temp values check for existing values\n\n* Fixed: Cpu percent cutting off above 1000 percent and added scaling with \"k\" prefix above 10'000\n\n* Fixed: Crash when rapidly resizing terminal at start\n\n## v1.0.9\n\n* Added: ifstream check and try-catch for stod() in Tools::system_uptime()\n\n* Fixed: Freeze on cin.ignore()\n\n## v1.0.8\n\n* Fixed: Additional NULL checks in UTF-8 detection\n\n* Changed: Makefile: Only look for g++-11 if CXX=g++\n\n* Fixed: Missing NULL check for ttyname\n\n* Changed: Only log tty name if known\n\n## v1.0.7\n\n* Fixed: Crash when opening menu at too small size\n\n* Fixed: Cores not constrained to cpu box and core numbers above 100 cut off\n\n* Fixed: Scrollbar position incorrect in small lists and selection not working when filtering\n\n## v1.0.6\n\n* Fixed: Check that getenv(\"LANG\") is not NULL in UTF-8 check\n\n* Fixed: Processes not completely hidden when collapsed in tree mode\n\n* Fixed: Changed wrong filename error.log to btop.log\n\n## v1.0.5\n\n* Fixed: Load AVG sizing when hiding temperatures\n\n* Fixed: Sizing constraints bug on start and boxes can be toggled from size error screen\n\n* Fixed: UTF-8 check crashing if LANG was set to non existent locale\n\n## v1.0.4\n\n* Fixed: Use /proc/pid/statm if RSS memory from /proc/pid/stat is faulty\n\n## v1.0.3\n\n* Fixed: stoi 0 literal pointer to nullptr and added more clamping for gradient array access\n\n## v1.0.2\n\n* Fixed: ARCH detection in Makefile\n\n* Fixed: Color gradient array out of bounds, added clamp 0-100 for cpu percent values\n\n* Fixed: Menu size and preset size issues and added warnings for small terminal size\n\n* Fixed: Options menu page selection alignment\n\n## v1.0.1\n\n* Fixed: UTF-8 check to include UTF8\n\n* Fixed: Added thread started check before joining in clean_quit()\n\n* Fix documentation of --utf-force in README and --help. by @purinchu\n\n## v1.0.0\n\n* First release for Linux\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "# SPDX-License-Identifier: Apache-2.0\n#\n# CMake configuration for btop\n#\n\ncmake_minimum_required(VERSION 3.25)\n\n# Disable in-source builds since they would override the Makefile\nif(\"${CMAKE_CURRENT_SOURCE_DIR}\" STREQUAL \"${CMAKE_CURRENT_BINARY_DIR}\")\n  message(FATAL_ERROR \"In-source builds are not allowed\")\nendif()\n\nproject(\"btop\"\n  DESCRIPTION \"A monitor of resources\"\n  HOMEPAGE_URL \"https://github.com/aristocratos/btop\"\n  LANGUAGES CXX\n)\n\ninclude(CheckIPOSupported)\ninclude(CMakeDependentOption)\n\n# Make our Find<Package>.cmake files available\nlist(APPEND CMAKE_MODULE_PATH \"${CMAKE_CURRENT_SOURCE_DIR}/cmake/\")\n\nset(CMAKE_CXX_STANDARD 23)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\nset(CMAKE_COLOR_DIAGNOSTICS ON)\nset(CMAKE_EXPORT_COMPILE_COMMANDS ON)\n\noption(BTOP_STATIC \"Link btop statically\" OFF)\noption(BTOP_GPU \"Enable GPU support\" ON)\ncmake_dependent_option(BTOP_RSMI_STATIC \"Link statically to ROCm SMI\" OFF \"BTOP_GPU\" OFF)\n\n# Enable LTO in release builds by default\nif(CMAKE_BUILD_TYPE MATCHES \"Rel(ease|WithDebInfo)\")\n  option(BTOP_LTO \"Enable LTO\" ON)\nelse()\n  option(BTOP_LTO \"Enable LTO\" OFF)\nendif()\n\nif(BTOP_STATIC AND NOT APPLE)\n  # Set this before calling find_package\n  set(CMAKE_FIND_LIBRARY_SUFFIXES \".a\")\nendif()\n\nadd_executable(btop src/main.cpp)\nadd_library(libbtop OBJECT\n  src/btop.cpp\n  src/btop_cli.cpp\n  src/btop_config.cpp\n  src/btop_draw.cpp\n  src/btop_input.cpp\n  src/btop_log.cpp\n  src/btop_menu.cpp\n  src/btop_shared.cpp\n  src/btop_theme.cpp\n  src/btop_tools.cpp\n)\n\ntarget_link_libraries(btop libbtop)\n\nif(BTOP_LTO)\n  check_ipo_supported()\n  set_target_properties(btop PROPERTIES INTERPROCEDURAL_OPTIMIZATION ON)\n  set_target_properties(libbtop PROPERTIES INTERPROCEDURAL_OPTIMIZATION ON)\nendif()\n\nif(APPLE)\n  target_sources(libbtop PRIVATE src/osx/btop_collect.cpp src/osx/sensors.cpp src/osx/smc.cpp)\nelseif(CMAKE_SYSTEM_NAME STREQUAL \"FreeBSD\" OR CMAKE_SYSTEM_NAME STREQUAL \"MidnightBSD\")\n  target_sources(libbtop PRIVATE src/freebsd/btop_collect.cpp)\nelseif(CMAKE_SYSTEM_NAME STREQUAL \"OpenBSD\")\n  target_sources(libbtop PRIVATE src/openbsd/btop_collect.cpp src/openbsd/sysctlbyname.cpp)\nelseif(CMAKE_SYSTEM_NAME STREQUAL \"NetBSD\")\n  target_sources(libbtop PRIVATE src/netbsd/btop_collect.cpp)\nelseif(LINUX)\n  target_sources(libbtop PRIVATE src/linux/btop_collect.cpp)\n  if(BTOP_GPU)\n    add_subdirectory(src/linux/intel_gpu_top)\n  endif()\nelse()\n  message(FATAL_ERROR \"${CMAKE_SYSTEM_NAME} is not supported\")\nendif()\n\n# Generate build info\nexecute_process(\n  COMMAND \"git\" \"rev-parse\" \"--short\" \"HEAD\"\n  WORKING_DIRECTORY \"${CMAKE_SOURCE_DIR}\"\n  OUTPUT_VARIABLE GIT_COMMIT\n  OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)\nset(CONFIGURE_COMMAND\n    \"cmake -DBTOP_STATIC=${BTOP_STATIC} -DBTOP_GPU=${BTOP_GPU}\"\n)\nget_filename_component(CXX_COMPILER_BASENAME \"${CMAKE_CXX_COMPILER}\" NAME)\nset(COMPILER \"${CXX_COMPILER_BASENAME}\")\nset(COMPILER_VERSION \"${CMAKE_CXX_COMPILER_VERSION}\")\nconfigure_file(${CMAKE_CURRENT_SOURCE_DIR}/src/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h @ONLY IMMEDIATE)\nset(CMAKE_INCLUDE_CURRENT_DIR ON)\n\ninclude(CheckCXXSourceCompiles)\ninclude(CheckCXXSymbolExists)\n\ncheck_cxx_source_compiles(\n  \"\n  #include <version>\n  #if __cpp_lib_optional < 202110L\n  #error \\\"Missing __cpp_lib_optional < 202110L\\\"\n  #endif\n  int main() { return 0; }\n  \"\n  HAS_CXX_OPTIONAL_MONADS\n)\nif(NOT HAS_CXX_OPTIONAL_MONADS)\n  message(FATAL_ERROR \"The compiler doesn't support std::optional::and_then\")\nendif()\ncheck_cxx_symbol_exists(\"__cpp_lib_expected\" \"version\" HAS_CXX_EXPECTED)\nif(NOT HAS_CXX_EXPECTED)\n  message(FATAL_ERROR \"The compiler doesn't support std::expected\")\nendif()\ncheck_cxx_symbol_exists(\"__cpp_lib_ranges\" \"version\" HAS_CXX_RANGES)\nif(NOT HAS_CXX_RANGES)\n  message(FATAL_ERROR \"The compiler doesn't support std::ranges\")\nendif()\ncheck_cxx_symbol_exists(\"__cpp_lib_ranges_to_container\" \"version\" HAS_CXX_RANGES_TO_CONTAINER)\nif(NOT HAS_CXX_RANGES_TO_CONTAINER)\n  message(FATAL_ERROR \"The compiler doesn't support std::ranges::to\")\nendif()\ncheck_cxx_symbol_exists(\"__cpp_lib_string_contains\" \"version\" HAS_CXX_STRING_CONTAINS)\nif(NOT HAS_CXX_STRING_CONTAINS)\n  message(FATAL_ERROR \"The compiler doesn't support std::string::contains\")\nendif()\n\ntarget_compile_options(libbtop PUBLIC -Wall -Wextra -Wpedantic)\n\ninclude(CheckCXXCompilerFlag)\n\nif(NOT APPLE)\n  target_compile_options(libbtop PUBLIC -fstack-clash-protection)\nendif()\ncheck_cxx_compiler_flag(-fstack-protector HAS_FSTACK_PROTECTOR)\nif(HAS_FSTACK_PROTECTOR)\n  target_compile_options(libbtop PUBLIC -fstack-protector)\nendif()\ncheck_cxx_compiler_flag(-fcf-protection HAS_FCF_PROTECTION)\nif(HAS_FCF_PROTECTION)\n  target_compile_options(libbtop PUBLIC -fcf-protection)\nendif()\n\ntarget_compile_definitions(libbtop PUBLIC\n  FMT_HEADER_ONLY\n  _FILE_OFFSET_BITS=64\n  $<$<CONFIG:Debug>:_GLIBCXX_ASSERTIONS _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG>\n)\n\ntarget_include_directories(libbtop SYSTEM PUBLIC include)\n\n# Enable pthreads\nset(THREADS_PREFER_PTHREAD_FLAG ON)\nfind_package(Threads REQUIRED)\ntarget_link_libraries(libbtop Threads::Threads)\n\n# Enable GPU support\nif(LINUX AND BTOP_GPU)\n  target_compile_definitions(libbtop PUBLIC GPU_SUPPORT)\n\n  if(BTOP_RSMI_STATIC)\n    # ROCm doesn't properly add it's folders to the module path if `CMAKE_MODULE_PATH` is already\n    # set\n    # We could also manually append ROCm's path here\n    set(_CMAKE_MODULE_PATH CMAKE_MODULE_PATH)\n    unset(CMAKE_MODULE_PATH)\n\n    # NOTE: This might be problematic in the future if other sub projects depend on this or if\n    # btop starts producing libraries\n    # Build a static ROCm library\n    set(BUILD_SHARED_LIBS OFF CACHE BOOL \"\" FORCE)\n\n    add_subdirectory(lib/rocm_smi_lib EXCLUDE_FROM_ALL)\n\n    add_library(ROCm INTERFACE)\n    # Export ROCm's properties to a target\n    target_compile_definitions(ROCm INTERFACE RSMI_STATIC)\n    target_include_directories(ROCm INTERFACE lib/rocm_smi_lib/include)\n    target_link_libraries(ROCm INTERFACE rocm_smi64)\n\n    set(CMAKE_MODULE_PATH _CMAKE_MODULE_PATH)\n\n    target_link_libraries(libbtop ROCm)\n  endif()\n  if(NOT BTOP_STATIC)\n    target_link_libraries(libbtop ${CMAKE_DL_LIBS})\n  endif()\nendif()\n\nif(BTOP_STATIC)\n  target_compile_definitions(libbtop PUBLIC STATIC_BUILD)\n  target_link_options(libbtop PUBLIC -static LINKER:--fatal-warnings)\nendif()\n\n# Enable GPU support on Apple Silicon\nif(APPLE AND BTOP_GPU)\n  target_compile_definitions(libbtop PUBLIC GPU_SUPPORT)\nendif()\n\n# Other platform dependent flags\nif(APPLE)\n  target_link_libraries(libbtop\n    $<LINK_LIBRARY:FRAMEWORK,CoreFoundation> $<LINK_LIBRARY:FRAMEWORK,IOKit>\n  )\n  if(BTOP_GPU)\n    find_library(IOREPORT_LIB IOReport)\n    if(IOREPORT_LIB)\n      target_link_libraries(libbtop ${IOREPORT_LIB})\n    endif()\n  endif()\nelseif(CMAKE_SYSTEM_NAME STREQUAL \"FreeBSD\" OR CMAKE_SYSTEM_NAME STREQUAL \"MidnightBSD\")\n  # Avoid version mismatch for libstdc++ when a specific version of GCC is installed and not the\n  # default one since all use the default ones RPATH\n  if (CMAKE_CXX_COMPILER_ID STREQUAL \"GNU\")\n    string(REGEX MATCH \"^[0-9]+\" GCC_VERSION_MAJOR \"${CMAKE_CXX_COMPILER_VERSION}\")\n    set_target_properties(btop PROPERTIES\n      INSTALL_RPATH \"/usr/local/lib/gcc${GCC_VERSION_MAJOR}\"\n      BUILD_WITH_INSTALL_RPATH TRUE\n    )\n\n    # The gcc compiler wrapper doesn't add '--eh-frame-hdr' on FreeBSD with static builds\n    # https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=278551\n    if(BTOP_STATIC)\n      target_link_options(libbtop PUBLIC LINKER:--eh-frame-hdr)\n    endif()\n  endif()\n\n  find_package(devstat REQUIRED)\n  find_package(kvm REQUIRED)\n  target_link_libraries(libbtop devstat::devstat kvm::kvm)\n  if(BTOP_STATIC)\n    find_package(elf REQUIRED)\n    target_link_libraries(libbtop elf::elf)\n  endif()\nelseif(CMAKE_SYSTEM_NAME STREQUAL \"OpenBSD\")\n  if(CMAKE_CXX_COMPILER_ID STREQUAL \"GNU\")\n    target_compile_options(libbtop PUBLIC -static-libstdc++)\n  endif()\n  find_package(kvm REQUIRED)\n  target_link_libraries(libbtop kvm::kvm)\nelseif(CMAKE_SYSTEM_NAME STREQUAL \"NetBSD\")\n  if(CMAKE_CXX_COMPILER_ID STREQUAL \"GNU\")\n    target_compile_options(libbtop PUBLIC -static-libstdc++)\n  endif()\n  find_package(kvm REQUIRED)\n  find_package(proplib REQUIRED)\n  target_link_libraries(libbtop kvm::kvm proplib::proplib)\nendif()\n\n# Check if lowdown is installed\nfind_program(LOWDOWN_EXECUTABLE lowdown)\n\nif(LOWDOWN_EXECUTABLE)\n  # Custom target to compile Markdown to man page using lowdown\n  add_custom_command(\n    OUTPUT btop.1\n    COMMAND lowdown -s -T man -o btop.1 ${CMAKE_CURRENT_SOURCE_DIR}/manpage.md\n    DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/manpage.md\n    VERBATIM\n  )\n  add_custom_target(generate_manpage ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/btop.1)\n  # Install the man page\n  install(FILES \"${CMAKE_CURRENT_BINARY_DIR}/btop.1\" DESTINATION \"share/man/man1\")\nelse()\n  message(STATUS \"Command 'lowdown' not found: skipping generating man page btop.1\")\nendif()\n\ninstall(TARGETS btop RUNTIME)\ninstall(FILES \"btop.desktop\" DESTINATION \"share/applications\")\ninstall(FILES \"Img/icon.png\" DESTINATION \"share/icons/hicolor/48x48/apps\" RENAME \"btop.png\")\ninstall(FILES \"Img/icon.svg\" DESTINATION \"share/icons/hicolor/scalable/apps\" RENAME \"btop.svg\")\ninstall(DIRECTORY \"themes\" DESTINATION \"share/btop\")\n\ninclude(CTest)\nif(BUILD_TESTING)\n  add_subdirectory(tests)\nendif()\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "\n# Contributor Covenant 3.0\n\n## Our Pledge\n\nWe pledge to make our community welcoming, safe, and equitable for all.\n\nWe are committed to fostering an environment that respects and promotes the dignity, rights, and contributions of all individuals, regardless of characteristics including race, ethnicity, caste, color, age, physical characteristics, neurodiversity, disability, sex or gender, gender identity or expression, sexual orientation, language, philosophy or religion, national or social origin, socio-economic position, level of education, or other status. The same privileges of participation are extended to everyone who participates in good faith and in accordance with this Covenant.\n\n\n## Encouraged Behaviors\n\nWhile acknowledging differences in social norms, we all strive to meet our community's expectations for positive behavior. We also understand that our words and actions may be interpreted differently than we intend based on culture, background, or native language.\n\nWith these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including:\n\n1. Respecting the **purpose of our community**, our activities, and our ways of gathering.\n2. Engaging **kindly and honestly** with others.\n3. Respecting **different viewpoints** and experiences.\n4. **Taking responsibility** for our actions and contributions.\n5. Gracefully giving and accepting **constructive feedback**.\n6. Committing to **repairing harm** when it occurs.\n7. Behaving in other ways that promote and sustain the **well-being of our community**.\n\n\n## Restricted Behaviors\n\nWe agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct.\n\n1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop.\n2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people.\n3. **Stereotyping or discrimination.** Characterizing anyone’s personality or behavior on the basis of immutable identities or traits.\n4. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community.\n5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission.\n6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group.\n7. Behaving in other ways that **threaten the well-being** of our community.\n\n### Other Restrictions\n\n1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions.\n2. **Failing to credit sources.** Not properly crediting the sources of content you contribute.\n3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community.\n4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviors.\n\n\n## Reporting an Issue\n\nTensions can occur between community members even when they are trying their best to collaborate. Not every conflict represents a code of conduct violation, and this Code of Conduct reinforces encouraged behaviors and norms that can help avoid conflicts and minimize harm.\n\nWhen an incident does occur, it is important to report it promptly. To report a possible violation, **[NOTE: describe your means of reporting here.]**\n\nCommunity Moderators take reports of violations seriously and will make every effort to respond in a timely manner. They will investigate all reports of code of conduct violations, reviewing messages, logs, and recordings, or interviewing witnesses and other participants. Community Moderators will keep investigation and enforcement actions as transparent as possible while prioritizing safety and confidentiality. In order to honor these values, enforcement actions are carried out in private with the involved parties, but communicating to the whole community may be part of a mutually agreed upon resolution.\n\n\n## Addressing and Repairing Harm\n\n**[NOTE: The remedies and repairs outlined below are suggestions based on best practices in code of conduct enforcement. If your community has its own established enforcement process, be sure to edit this section to describe your own policies.]**\n\nIf an investigation by the Community Moderators finds that this Code of Conduct has been violated, the following enforcement ladder may be used to determine how best to repair harm, based on the incident's impact on the individuals involved and the community as a whole. Depending on the severity of a violation, lower rungs on the ladder may be skipped.\n\n1) Warning\n   1) Event: A violation involving a single incident or series of incidents.\n   2) Consequence: A private, written warning from the Community Moderators.\n   3) Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations.\n2) Temporarily Limited Activities\n   1) Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation.\n   2) Consequence: A private, written warning with a time-limited cooldown period designed to underscore the seriousness of the situation and give the community members involved time to process the incident. The cooldown period may be limited to particular communication channels or interactions with particular community members.\n   3) Repair: Examples of repair may include making an apology, using the cooldown period to reflect on actions and impact, and being thoughtful about re-entering community spaces after the period is over.\n3) Temporary Suspension\n   1) Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation.\n   2) Consequence: A private written warning with conditions for return from suspension. In general, temporary suspensions give the person being suspended time to reflect upon their behavior and possible corrective actions.\n   3) Repair: Examples of repair include respecting the spirit of the suspension, meeting the specified conditions for return, and being thoughtful about how to reintegrate with the community when the suspension is lifted.\n4) Permanent Ban\n   1) Event: A pattern of repeated code of conduct violations that other steps on the ladder have failed to resolve, or a violation so serious that the Community Moderators determine there is no way to keep the community safe with this person as a member.\n   2) Consequence: Access to all community spaces, tools, and communication channels is removed. In general, permanent bans should be rarely used, should have strong reasoning behind them, and should only be resorted to if working through other remedies has failed to change the behavior.\n   3) Repair: There is no possible repair in cases of this severity.\n\nThis enforcement ladder is intended as a guideline. It does not limit the ability of Community Managers to use their discretion and judgment, in keeping with the best interests of our community.\n\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public or other spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.\n\n\n## Attribution\n\nThis Code of Conduct is adapted from the Contributor Covenant, version 3.0, permanently available at [https://www.contributor-covenant.org/version/3/0/](https://www.contributor-covenant.org/version/3/0/).\n\nContributor Covenant is stewarded by the Organization for Ethical Source and licensed under CC BY-SA 4.0. To view a copy of this license, visit [https://creativecommons.org/licenses/by-sa/4.0/](https://creativecommons.org/licenses/by-sa/4.0/)\n\nFor answers to common questions about Contributor Covenant, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are provided at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations). Additional enforcement and community guideline resources can be found at [https://www.contributor-covenant.org/resources](https://www.contributor-covenant.org/resources). The enforcement ladder was inspired by the work of [Mozilla’s code of conduct team](https://github.com/mozilla/inclusion).\n\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing guidelines\n\n## When submitting pull requests\n\n* Explain your thinking in why a change or addition is needed.\n  * Is it a requested change or feature?\n  * If not, open a feature request to get feedback before making a pull request.\n\n* Split up multiple unrelated changes in multiple pull requests.\n\n* If it's a fix for a unreported bug, make a bug report and link the pull request.\n\n* Purely cosmetic changes won't be accepted without a very good explanation of its value.\n\n* Submissions where the majority of the code is AI generated must be marked with [AI generated].\n\n* \"Vibe coded\" PR's where it seems like the author doesn't understand the generated code will be dismissed.\n\n## Formatting\n\n### Follow the current syntax design\n\n* Indent type: Tabs\n\n* Tab size: 4\n\n* Alternative operators `and`, `or` and `not`.\n\n* Opening curly braces `{` at the end of the same line as the statement/condition.\n\n## General guidelines\n\n* Don't force a programming style. Use object oriented, functional, data oriented, etc., where it's suitable.\n\n* Use [RAII](https://en.cppreference.com/w/cpp/language/raii).\n\n* Make use of the standard algorithms library, watch [C++ Seasoning](https://www.youtube.com/watch?v=W2tWOdzgXHA) and [105 STL Algorithms](https://www.youtube.com/watch?v=bFSnXNIsK4A) for inspiration.\n\n* Use the included `fmt` library for string formatting, see issue [#535](https://github.com/aristocratos/btop/issues/535) for more info and examples.\n\n  * All new code should prefer `fmt::format` or `fmt::format_to` instead of\n    manually concatenating strings for better performance.\n\n* Do not add includes if the same functionality can be achieved using the already included libraries.\n\n* Use descriptive names for variables.\n\n* Use comments if not very obvious what your code is doing.\n\n* Add comments as labels for what's currently happening in bigger sections of code for better readability.\n\n* Avoid writing to disk.\n\n* If using the logger functions, be sensible, only call it if something of importance has changed.\n\n* Benchmark your code and look for alternatives if they cause a noticeable negative impact.\n\nFor questions open a new discussion thread or send a mail to jakob@qvantnet.com\n\nFor proposing changes to this document create a [new issue](https://github.com/aristocratos/btop/issues/new/choose).\n"
  },
  {
    "path": "LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# ![btop++](Img/logo.png)\n\n<a href=\"https://repology.org/project/btop/versions\">\n    <img src=\"https://repology.org/badge/vertical-allrepos/btop.svg\" alt=\"Packaging status\" align=\"right\">\n</a>\n\n![Linux](https://img.shields.io/badge/-Linux-grey?logo=linux)\n![macOS](https://img.shields.io/badge/-OSX-black?logo=apple)\n![FreeBSD](https://img.shields.io/badge/-FreeBSD-red?logo=freebsd)\n![NetBSD](https://img.shields.io/badge/-NetBSD-black?logo=netbsd)\n![OpenBSD](https://img.shields.io/badge/-OpenBSD-black?logo=openbsd)\n![Usage](https://img.shields.io/badge/Usage-System%20resource%20monitor-yellow)\n![c++23](https://img.shields.io/badge/cpp-c%2B%2B23-green)\n![latest_release](https://img.shields.io/github/v/tag/aristocratos/btop?label=release)\n[![Donate](https://img.shields.io/badge/-Donate-yellow?logo=paypal)](https://paypal.me/aristocratos)\n[![Sponsor](https://img.shields.io/badge/-Sponsor-red?logo=github)](https://github.com/sponsors/aristocratos)\n[![Coffee](https://img.shields.io/badge/-Buy%20me%20a%20Coffee-grey?logo=Ko-fi)](https://ko-fi.com/aristocratos)\n[![btop](https://snapcraft.io/btop/badge.svg)](https://snapcraft.io/btop)\n[![Continuous Build Linux](https://github.com/aristocratos/btop/actions/workflows/continuous-build-linux.yml/badge.svg)](https://github.com/aristocratos/btop/actions/workflows/continuous-build-linux.yml)\n[![Continuous Build macOS](https://github.com/aristocratos/btop/actions/workflows/continuous-build-macos.yml/badge.svg)](https://github.com/aristocratos/btop/actions/workflows/continuous-build-macos.yml)\n[![Continuous Build FreeBSD](https://github.com/aristocratos/btop/actions/workflows/continuous-build-freebsd.yml/badge.svg)](https://github.com/aristocratos/btop/actions/workflows/continuous-build-freebsd.yml)\n[![Continuous Build NetBSD](https://github.com/aristocratos/btop/actions/workflows/continuous-build-netbsd.yml/badge.svg)](https://github.com/aristocratos/btop/actions/workflows/continuous-build-netbsd.yml)\n[![Continuous Build OpenBSD](https://github.com/aristocratos/btop/actions/workflows/continuous-build-openbsd.yml/badge.svg)](https://github.com/aristocratos/btop/actions/workflows/continuous-build-openbsd.yml)\n\n## Index\n\n* [News](#news)\n* [Documents](#documents)\n* [Description](#description)\n* [Features](#features)\n* [Themes](#themes)\n* [Support and funding](#support-and-funding)\n* [Prerequisites](#prerequisites) (Read this if you are having issues!)\n* [Screenshots](#screenshots)\n* [Keybindings](#help-menu)\n* [Installation Linux/macOS](#installation)\n* [Compilation Linux](#compilation-linux)\n* [Compilation macOS](#compilation-macos-osx)\n* [Compilation FreeBSD](#compilation-freebsd)\n* [Compilation NetBSD](#compilation-netbsd)\n* [Compilation OpenBSD](#compilation-openbsd)\n* [Testing](#testing)\n* [GPU compatibility](#gpu-compatibility)\n* [Installing the snap](#installing-the-snap)\n* [Configurability](#configurability)\n* [License](#license)\n\nIf you are considering donating, please first consider donating to:\n\n[<img src=\"https://images.squarespace-cdn.com/content/v1/66fd17c779966209da4359da/9dcb67db-433e-41cb-94d7-cecba280dc0b/Picture+1.png\" height=\"100px\">](https://www.qm4ua.org/)\n[<img src=\"https://secure2.convio.net/stccad/images/content/pagebuilder/stc-logo2022.png\" width=\"400px\">](https://donate.savethechildren.org)\n\n\n\n## News\n\n##### 4 December 2025\n\nSince there is a increasing amount of AI generated/assisted PR's, the following guidlines have been added to CONTRIBUTING.md:\n\n* Submissions where the majority of the code is AI generated must be marked with [AI generated].\n\n* \"Vibe coded\" PR's where it seems like the author doesn't understand the generated code will be dismissed.\n\n##### 22 September 2024\n\nBtop release v1.4.0\n\nIntel GPU support added, note that only GPU utilization, power usage and clock speed available to monitor. Thanks to [@bjia56](https://github.com/bjia56) for contributions.\n\nNetBSD support added. Thanks to [@fraggerfox](https://github.com/fraggerfox) for contributions.\n\nSee [CHANGELOG.md](CHANGELOG.md) and latest [release](https://github.com/aristocratos/btop/releases/latest) for detailed list of new features, bug fixes and new themes.\n\n##### 7 January 2024\n\nBtop release v1.3.0\n\nBig release with GPU support added for Linux and platform support for OpenBSD. Big thanks to [@romner-set](https://github.com/romner-set) (GPU support) and [@joske](https://github.com/joske) (OpenBSD support) for contributions.\nAnd a multitude of bugfixes and small changes, see [CHANGELOG.md](CHANGELOG.md) and latest [release](https://github.com/aristocratos/btop/releases/latest) for detailed list and attributions.\n\nSee news entry below for more information regarding GPU support.\n\n##### 25 November 2023\n\nGPU monitoring added for Linux!\n\nCompile from git main to try it out.\n\nUse keys `5`, `6`, `7` and `0` to show/hide the gpu monitoring boxes. `5` = Gpu 1, `6` = Gpu 2, etc.\n\nGpu stats/graphs can also be displayed in the \"Cpu box\" (not as verbose), see the cpu options menu for info and configuration.\n\nNote that the binaries provided on the release page (when released) and the continuous builds will not have gpu support enabled.\n\nBecause the GPU support relies on loading of dynamic gpu libraries, gpu support will not work when also static linking.\n\nSee [Compilation Linux](#compilation-linux) for more info on how to compile with gpu monitoring support.\n\nMany thanks to [@romner-set](https://github.com/romner-set) who wrote the vast majority of the implementation for GPU support.\n\nBig update with version bump to 1.3 coming soon.\n\n##### 28 August 2022\n\n[![btop4win](https://github.com/aristocratos/btop4win/raw/master/Img/logo.png)](https://github.com/aristocratos/btop4win)\n\nFirst release of btop4win available at https://github.com/aristocratos/btop4win\n\n<details>\n<summary>More...</summary>\n\n##### 16 January 2022\n\nRelease v1.2.0 with FreeBSD support. No release binaries for FreeBSD provided as of yet.\n\nAgain a big thanks to [@joske](https://github.com/joske) for his porting efforts!\n\nSince compatibility with Linux, macOS and FreeBSD are done, the focus going forward will be on new features like GPU monitoring.\n\n##### 13 November 2021\n\nRelease v1.1.0 with macOS support. Binaries in [continuous-build-macos](https://github.com/aristocratos/btop/actions/workflows/continuous-build-macos.yml) are only x86 for now.\nmacOS binaries + installer are included for both x86 and ARM64 (Apple Silicon) in the releases.\n\nBig thank you to [@joske](https://github.com/joske) who wrote the vast majority of the implementation!\n\n##### 30 October 2021\n\nWork on the OSX [macOS] and FreeBSD branches, both initiated and mostly worked on by [@joske](https://github.com/joske), will likely be completed in the coming weeks.\nThe OSX [macOS] branch has some memory leaks that needs to be sorted out and both have some issues with the processes cpu usage calculation and other smaller issues that needs fixing.\n\nIf you want to help out, test for bugs/fix bugs or just try out the branches:\n\n**macOS / OSX**\n```bash\n# Install and use Homebrew or MacPorts package managers for easy dependency installation\nbrew install coreutils make gcc@11 lowdown\ngit clone https://github.com/aristocratos/btop.git\ncd btop\ngit checkout OSX\ngmake\n```\n\n**FreeBSD**\n```bash\nsudo pkg install gmake gcc11 coreutils git lowdown\ngit clone https://github.com/aristocratos/btop.git\ncd btop\ngit checkout freebsd\ngmake\n```\n\nNote that GNU make (`gmake`) is recommended but not required for macOS/OSX but it is required on FreeBSD.\n\n\n##### 6 October 2021\n\nmacOS development have been started by [@joske](https://github.com/joske), big thanks :)\nSee branch [OSX](https://github.com/aristocratos/btop/tree/OSX) for current progress.\n\n##### 18 September 2021\n\nThe Linux version of btop++ is complete. Released as version 1.0.0\n\nI will be providing statically compiled binaries for a range of architectures in every release for those having problems compiling.\n\nFor compilation GCC 11 is required.\n\nPlease report any bugs to the [Issues](https://github.com/aristocratos/btop/issues/new?assignees=aristocratos&labels=bug&template=bug_report.md&title=%5BBUG%5D) page.\n\nThe development plan right now:\n\n* 1.1.0 macOS [OSX] support\n* 1.2.0 FreeBSD support\n* 1.3.0 Support for GPU monitoring\n* 1.X.0 Other platforms and features...\n\nWindows support is not in the plans as of now, but if anyone else wants to take it on, I will try to help.\n\n##### 5 May 2021\n\nThis project is gonna take some time until it has complete feature parity with bpytop, since all system information gathering will have to be written from scratch without any external libraries.\nAnd will need some help in the form of code contributions to get complete support for BSD and macOS/OSX.\n\n</details>\n\n## Documents\n\n**[CHANGELOG.md](CHANGELOG.md)**\n\n**[CONTRIBUTING.md](CONTRIBUTING.md)**\n\n**[CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)**\n\n## Description\n\nResource monitor that shows usage and stats for processor, memory, disks, network and processes.\n\nC++ version and continuation of [bashtop](https://github.com/aristocratos/bashtop) and [bpytop](https://github.com/aristocratos/bpytop).\n\n## Features\n\n* Easy to use, with a game inspired menu system.\n* Full mouse support: all buttons with a highlighted key are clickable and mouse scrolling works in process list and menu boxes.\n* Fast and responsive UI with UP, DOWN key process selection.\n* Function for showing detailed stats for selected process.\n* Ability to filter processes.\n* Easy switching between sorting options.\n* Tree view of processes.\n* Send any signal to selected process.\n* Pause the process list.\n* UI menu for changing all config file options.\n* Auto scaling graph for network usage.\n* Shows IO activity and speeds for disks.\n* Battery meter\n* Selectable symbols for the graphs.\n* Custom presets\n* And more...\n\n## Themes\n\nBtop++ uses the same theme files as bpytop and bashtop (some color values missing in bashtop themes).\n\nSee [themes](https://github.com/aristocratos/btop/tree/main/themes) folder for available themes.\n\nBtop searches the following directories for system themes:\n\n* `../share/btop/themes` (this path is relative to the btop executable)\n* `/usr/local/share/btop/themes`\n* `/usr/share/btop/themes`\n\nThe first directory that exists and isn't empty is used as the system themes directory.\n\nThe user themes directory depends on which environment variables are set:\n\n* If `$XDG_CONFIG_HOME` is set, the user themes directory is `$XDG_CONFIG_HOME/btop/themes`\n* Otherwise, if `$HOME` is set, the user themes directory is `$HOME/.config/btop/themes`\n* Otherwise, the user themes directory is `~/.config/btop/themes`\n\nThe `make install` command places the default themes in `[$PREFIX or /usr/local]/share/btop/themes`.\nUser created themes should be placed in the user themes directory.\n\nUse the `--themes-dir` command-line option to specify a custom themes directory.\nWhen specified, this directory takes priority over the default search paths.\n\nLet me know if you want to contribute with new themes.\n\nThe new Process list pausing and Process following features introduce a few new theme attributes.\nThese attributes still need to be added to all of the existing themes (except the default one).\n\nProcess list banner attributes:\n* proc_pause_bg: background color of the banner when the list is paused.\n* proc_follow_bg: background color of the banner when the process following feature is active.\n* proc_banner_bg: background color of the banner when the process following feature is active AND the list is paused.\n* proc_banner_fg: foreground (text) color of the banner\n\nProcess following attributes:\n* followed_bg: background color of the followed process in the list.\n* followed_fg: foreground color of the followed process in the list.\n\n## Support and funding\n\nYou can sponsor this project through GitHub. See [my sponsors page](https://github.com/sponsors/aristocratos) for options.\n\nOr donate through [PayPal](https://paypal.me/aristocratos) or [ko-fi](https://ko-fi.com/aristocratos).\n\nAny support is greatly appreciated!\n\n## Prerequisites\n\nFor the best experience run within a terminal with support for:\n\n* 24-bit truecolor ([See list of terminals with truecolor support](https://github.com/termstandard/colors))\n* 256-color terminals are supported through 24-bit to 256-color conversion when setting \"truecolor\" to False in the options or with \"-lc/--low-color\" arguments.\n* 16 color TTY mode will be activated if a real tty device is detected. Can be forced with \"-t/--tty\" arguments.\n* Wide characters (Are sometimes problematic in web-based terminals)\n\nAlso necessary is a UTF8 locale and a font that includes:\n\n* Unicode Block “Braille Patterns” U+2800 - U+28FF (Not needed in TTY mode or with graphs set to type: block or tty.)\n* Unicode Block “Geometric Shapes” U+25A0 - U+25FF\n* Unicode Block \"Box Drawing\" and \"Block Elements\" U+2500 - U+259F\n\n### **Optional Dependencies (Needed for GPU monitoring) (Only Linux)**\n\nGPU monitoring also requires a btop binary built with GPU support (`GPU_SUPPORT=true` flag).\n\nSee [GPU compatibility](#gpu-compatibility) section for more about compiling with GPU support.\n\n * **NVIDIA**\n\n   If you have an NVIDIA GPU you must use an official NVIDIA driver, both the closed-source and open-source ones have been verified to work.\n\n   In addition to that you must also have the nvidia-ml dynamic library installed, which should be included with the driver package of your distribution.\n\n * **AMD**\n\n   If you have an AMD GPU `rocm_smi_lib` is required, which may or may not be packaged for your distribution.\n\n * **INTEL**\n\n   Requires a working C compiler if compiling from source.\n\n   Also requires the user to have permission to read from SYSFS.\n\n   Can be set with `make setcap` (preferred) or `make setuid` or by running btop with `sudo` or equivalent.\n\n### **Notice (Text rendering issues)**\n\n* If you are having problems with the characters in the graphs not looking like they do in the screenshots, it's likely a problem with your systems configured fallback font not having support for braille characters.\n\n* See [Terminess Powerline](https://github.com/ryanoasis/nerd-fonts/blob/master/patched-fonts/Terminus/TerminessNerdFontMono-Regular.ttf) for an example of a font that includes the braille symbols.\n\n* See comments by @sgleizes [link](https://github.com/aristocratos/bpytop/issues/100#issuecomment-684036827) and @XenHat [link](https://github.com/aristocratos/bpytop/issues/100#issuecomment-691585587) in issue #100 for possible solutions.\n\n* If text is misaligned and you use Konsole or Yakuake, turning off \"Bi-Directional text rendering\" is a possible fix.\n\n* Characters clipping into each other or text/border misalignments are not bugs caused by btop, but most likely a fontconfig or terminal problem where the braille characters making up the graphs aren't rendered correctly.\n\n* Look to the creators of the terminal emulator you use to fix these issues if the previously mentioned fixes don't work for you.\n\n## Screenshots\n\n#### Main UI showing details for a selected process\n\n![Screenshot 1](Img/normal.png)\n\n#### Main UI in TTY mode\n\n![Screenshot 2](Img/tty.png)\n\n#### Main UI with custom options\n\n![Screenshot 3](Img/alt.png)\n\n#### Main-menu\n\n![Screenshot 3](Img/main-menu.png)\n\n#### Options-menu\n\n![Screenshot 4](Img/options-menu.png)\n\n#### Help-menu\n\n![Screenshot 5](Img/help-menu.png)\n\n## Installation\n\n**Binaries for Linux are statically compiled with musl and work on kernel releases 2.6.39 and newer**\n\n1. **Download btop-(VERSION)-(ARCH)-(PLATFORM).tbz from [latest release](https://github.com/aristocratos/btop/releases/latest) and unpack to a new folder**\n\n   **Notice! Use x86_64 for 64-bit x86 systems, i486 and i686 are 32-bit!**\n\n2. **Install (from created folder)**\n\n   * **Run:**\n\n   ```bash\n   # use \"make install PREFIX=/target/dir\" to set target, default: /usr/local\n   # only use \"sudo\" when installing to a NON user owned directory\n   sudo make install\n   ```\n\n3. **(Optional/Required for Intel GPU and CPU wattage) Set extended capabilities or suid bit to btop**\n\n   Enables signal sending to any process without starting with `sudo` and can prevent /proc read permissions problems on some systems.\n\n   Is required for Intel GPU support and CPU wattage monitoring.\n\n   * **Run:**\n\n   ```bash\n   # run after make install and use same PREFIX if any was used at install\n   sudo make setcap\n   ```\n   * **or**\n\n   ```bash\n   # run after make install and use same PREFIX if any was used at install\n   # set SU_USER and SU_GROUP to select user and group, default is root:root\n   sudo make setuid\n   ```\n\n* **Uninstall**\n\n  * **Run:**\n\n   ```bash\n   sudo make uninstall\n   ```\n\n* **Show help**\n\n   ```bash\n   make help\n   ```\n\n**Binary release (from native os repo)**\n\n* **openSUSE**\n  * **Tumbleweed:**\n    ```bash\n    sudo zypper in btop\n    ```\n  * For all other versions, see [openSUSE Software: btop](https://software.opensuse.org/package/btop)\n* **Fedora**\n    ```bash\n    sudo dnf install btop\n\t```\n* **RHEL/Rocky/AlmaLinux 8+**\n    ```bash\n    sudo dnf install epel-release\n\tsudo dnf install btop\n\t```\n* **FreeBSD**\n\t```sh\n\tpkg install btop\n\t```\n* **NetBSD**\n\t```sh\n\tpkg_add btop\n\t```\n\n\n**Binary release on Homebrew (macOS (x86_64 & ARM64) / Linux (x86_64))**\n\n* **[Homebrew](https://formulae.brew.sh/formula/btop)**\n  ```bash\n  brew install btop\n  ```\n\n## Compilation Linux\n\n   Requires at least GCC 14 or Clang 19.\n\n   The Makefile also needs GNU `coreutils` and `sed` (should already be installed on any modern distribution).\n\n   ### GPU compatibility\n\n   Btop++ supports Nvidia and AMD GPUs and Intel IGPUs out of the box on Linux x86_64, provided you have the correct drivers and libraries.\n\n   Gpu support for Nvidia or AMD will not work when static linking glibc (or musl, etc.)!\n\n   For x86_64 Linux the flag `GPU_SUPPORT` is automatically set to `true`, to manually disable gpu support set the flag to false, like:\n\n   `make GPU_SUPPORT=false` (or `cmake -DBTOP_GPU=false` with CMake)\n\n * **NVIDIA**\n\n    You must use an official NVIDIA driver, both the closed-source and [open-source](https://github.com/NVIDIA/open-gpu-kernel-modules) ones have been verified to work.\n\n    In addition to that you must also have the `nvidia-ml` dynamic library installed, which should be included with the driver package of your distribution.\n\n * **AMD**\n\n    AMDGPU data is queried using the [ROCm SMI](https://github.com/rocm/rocm_smi_lib) library, which may or may not be packaged for your distribution. If your distribution doesn't provide a package, btop++ is statically linked to ROCm SMI with the `RSMI_STATIC=true` make flag.\n\n    This flag expects the ROCm SMI source code in `lib/rocm_smi_lib`, and compilation will fail if it's not there. The latest tested version is 5.6.x, which can be obtained with the following command:\n\n   ```bash\n   git clone https://github.com/rocm/rocm_smi_lib.git --depth 1 -b rocm-5.6.x lib/rocm_smi_lib\n   ```\n\n<details>\n<summary>\n\n### With Make\n</summary>\n\n1. **Install dependencies (example for Ubuntu 24.04 Noble)**\n\n   ```bash\n   sudo apt install coreutils sed git build-essential lowdown\n   ```\n\n2. **Clone repository**\n\n   ```bash\n   git clone https://github.com/aristocratos/btop.git\n   cd btop\n   ```\n\n3. **Compile**\n\n   ```bash\n   make\n   ```\n\n   Options for make:\n\n   | Flag                            | Description                                                             |\n   |---------------------------------|-------------------------------------------------------------------------|\n   | `VERBOSE=true`                  | To display full compiler/linker commands                                |\n   | `STATIC=true`                   | For static compilation                                                  |\n   | `QUIET=true`                    | For less verbose output                                                 |\n   | `STRIP=true`                    | To force stripping of debug symbols (adds `-s` linker flag)             |\n   | `DEBUG=true`                    | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging        |\n   | `ARCH=<architecture>`           | To manually set the target architecture                                 |\n   | `GPU_SUPPORT=<true\\|false>`     | Enable/disable GPU support (Enabled by default on X86_64 Linux)         |\n   | `RSMI_STATIC=true`              | To statically link the ROCm SMI library used for querying AMDGPU        |\n   | `ADDFLAGS=<flags>`              | For appending flags to both compiler and linker                         |\n   | `CXX=<compiler>`                | Manually set which compiler to use                                       |\n\n   Example: `make ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system.\n\n   Notice! If using LDAP Authentication, usernames will show as UID number for LDAP users if compiling statically with glibc.\n\n4. **Install**\n\n   ```bash\n   sudo make install\n   ```\n\n   Append `PREFIX=/target/dir` to set target, default: `/usr/local`\n\n   Notice! Only use \"sudo\" when installing to a NON user owned directory.\n\n5. **(Optional/Required for Intel GPU support and CPU wattage) Set extended capabilities or suid bit to btop**\n\n   No need for `sudo` to enable signal sending to any process and to prevent /proc read permissions problems on some systems.\n\n   Also required for Intel GPU monitoring and CPU wattage monitoring.\n\n   Run after make install and use same PREFIX if any was used at install.\n\n   ```bash\n   sudo make setcap\n   ```\n\n   or\n\n   Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `root`\n\n   ```bash\n   sudo make setuid\n   ```\n\n* **Uninstall**\n\n   ```bash\n   sudo make uninstall\n   ```\n\n* **Remove any object files from source dir**\n\n   ```bash\n   make clean\n   ```\n\n* **Remove all object files, binaries and created directories in source dir**\n\n   ```bash\n   make distclean\n   ```\n\n* **Show help**\n\n   ```bash\n   make help\n   ```\n\n</details>\n<details>\n<summary>\n\n### With CMake (Community maintained)\n</summary>\n\n1. **Install build dependencies**\n\n   Requires Clang / GCC, CMake, Ninja, Lowdown and Git\n\n   For example, with Debian Bookworm:\n\n   ```bash\n   sudo apt install cmake git g++ ninja-build lowdown\n   ```\n\n2. **Clone the repository**\n\n   ```bash\n   git clone https://github.com/aristocratos/btop.git && cd btop\n   ``````\n\n3. **Compile**\n\n   ```bash\n   # Configure\n   cmake -B build -G Ninja\n   # Build\n   cmake --build build\n   ```\n\n   This will automatically build a release version of btop.\n\n   Some useful options to pass to the configure step:\n\n   | Configure flag                  | Description                                                             |\n   |---------------------------------|-------------------------------------------------------------------------|\n   | `-DBTOP_STATIC=<ON\\|OFF>`       | Enables static linking (OFF by default)                                 |\n   | `-DBTOP_LTO=<ON\\|OFF>`          | Enables link time optimization (ON by default)                          |\n\n\n   | `-DBTOP_GPU=<ON\\|OFF>`          | Enable GPU support (ON by default)                                      |\n   | `-DBTOP_RSMI_STATIC=<ON\\|OFF>`  | Build and link the ROCm SMI library statically (OFF by default)         |\n   | `-DCMAKE_INSTALL_PREFIX=<path>` | The installation prefix ('/usr/local' by default)                       |\n\n   To force any other compiler, run `CXX=<compiler> cmake -B build -G Ninja`\n\n4. **Install**\n\n   ```bash\n   cmake --install build\n   ```\n\n   May require root privileges\n\n5. **Uninstall**\n\n   CMake doesn't generate an uninstall target by default. To remove installed files, run\n   ```\n   cat build/install_manifest.txt | xargs rm -irv\n   ```\n\n6. **Cleanup build directory**\n\n   ```bash\n   cmake --build build -t clean\n   ```\n\n</details>\n\n## Compilation macOS OSX\n\n   Requires at least GCC 14 or Clang 19.\n\n   The Makefile also needs GNU coreutils and `sed`.\n\n   Install and use Homebrew or MacPorts package managers for easy dependency installation\n\n<details>\n<summary>\n\n### With Make\n</summary>\n\n1. **Install dependencies (example for Homebrew)**\n\n   ```bash\n   brew install coreutils make gcc@15 lowdown\n   ```\n\n2. **Clone repository**\n\n   ```bash\n   git clone https://github.com/aristocratos/btop.git\n   cd btop\n   ```\n3. **Compile**\n\n   ```bash\n   gmake\n   ```\n\n   Options for make:\n\n   | Flag                            | Description                                                             |\n   |---------------------------------|-------------------------------------------------------------------------|\n   | `VERBOSE=true`                  | To display full compiler/linker commands                                |\n   | `STATIC=true`                   | For static compilation (only libgcc and libstdc++)                      |\n   | `QUIET=true`                    | For less verbose output                                                 |\n   | `STRIP=true`                    | To force stripping of debug symbols (adds `-s` linker flag)             |\n   | `DEBUG=true`                    | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging        |\n   | `ARCH=<architecture>`           | To manually set the target architecture                                 |\n   | `ADDFLAGS=<flags>`              | For appending flags to both compiler and linker                         |\n   | `CXX=<compiler>`                | Manually set which compiler to use                                       |\n\n   Example: `gmake ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system.\n\n4. **Install**\n\n   ```bash\n   sudo gmake install\n   ```\n\n   Append `PREFIX=/target/dir` to set target, default: `/usr/local`\n\n   Notice! Only use \"sudo\" when installing to a NON user owned directory.\n\n5. **(Recommended) Set suid bit to make btop always run as root (or other user)**\n\n   ```bash\n   sudo gmake setuid\n   ```\n\n   No need for `sudo` to see information for non user owned processes and to enable signal sending to any process.\n\n   Run after make install and use same PREFIX if any was used at install.\n\n   Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `wheel`\n\n* **Uninstall**\n\n   ```bash\n   sudo gmake uninstall\n   ```\n\n* **Remove any object files from source dir**\n\n   ```bash\n   gmake clean\n   ```\n\n* **Remove all object files, binaries and created directories in source dir**\n\n   ```bash\n   gmake distclean\n   ```\n\n* **Show help**\n\n   ```bash\n   gmake help\n   ```\n\n</details>\n<details>\n<summary>\n\n### With CMake (Community maintained)\n</summary>\n\n1. **Install build dependencies**\n\n   Requires Clang, CMake, Ninja, Lowdown and Git\n\n   ```bash\n   brew update --quiet\n   brew install cmake git llvm ninja lowdown\n   ```\n\n2. **Clone the repository**\n\n   ```bash\n   git clone https://github.com/aristocratos/btop.git && cd btop\n   ```\n\n3. **Compile**\n\n   ```bash\n   # Configure\n   export LLVM_PREFIX=\"$(brew --prefix llvm)\"\n   export CXX=\"$LLVM_PREFIX/bin/clang++\"\n   export CPPFLAGS=\"-I$LLVM_PREFIX/include\"\n   export LDFLAGS=\"-L$LLVM_PREFIX/lib -L$LLVM_PREFIX/lib/c++ -Wl,-rpath,$LLVM_PREFIX/lib/c++ -fuse-ld=$LLVM_PREFIX/bin/ld64.lld\"\n   cmake -B build -G Ninja\n   # Build\n   cmake --build build\n   ```\n\n   This will automatically build a release version of btop.\n\n   Some useful options to pass to the configure step:\n\n   | Configure flag                  | Description                                                             |\n   |---------------------------------|-------------------------------------------------------------------------|\n   | `-DBTOP_LTO=<ON\\|OFF>`          | Enables link time optimization (ON by default)                          |\n\n\n   | `-DCMAKE_INSTALL_PREFIX=<path>` | The installation prefix ('/usr/local' by default)                       |\n\n   To force any specific compiler, run `CXX=<compiler> cmake -B build -G Ninja`\n\n4. **Install**\n\n   ```bash\n   cmake --install build\n   ```\n\n   May require root privileges\n\n5. **Uninstall**\n\n   CMake doesn't generate an uninstall target by default. To remove installed files, run\n   ```\n   cat build/install_manifest.txt | xargs rm -irv\n   ```\n\n6. **Cleanup build directory**\n\n   ```bash\n   cmake --build build -t clean\n   ```\n\n</details>\n\n## Compilation FreeBSD\n\n   Requires at least Clang 19 (default) or GCC 14.\n\n   Note that GNU make (`gmake`) is required to compile on FreeBSD.\n\n<details>\n<summary>\n\n### With gmake\n</summary>\n\n1. **Install dependencies**\n\n   ```bash\n   sudo pkg install gmake coreutils git lowdown\n   ```\n\n2. **Clone repository**\n\n   ```bash\n   git clone https://github.com/aristocratos/btop.git\n   cd btop\n   ```\n\n3. **Compile**\n\n   ```bash\n   gmake\n   ```\n\n   Options for make:\n\n   | Flag                            | Description                                                             |\n   |---------------------------------|-------------------------------------------------------------------------|\n   | `VERBOSE=true`                  | To display full compiler/linker commands                                |\n   | `STATIC=true`                   | For static compilation (only libgcc and libstdc++)                      |\n   | `QUIET=true`                    | For less verbose output                                                 |\n   | `STRIP=true`                    | To force stripping of debug symbols (adds `-s` linker flag)             |\n   | `DEBUG=true`                    | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging        |\n   | `ARCH=<architecture>`           | To manually set the target architecture                                 |\n   | `ADDFLAGS=<flags>`              | For appending flags to both compiler and linker                         |\n   | `CXX=<compiler>`                | Manually set which compiler to use                                       |\n\n   Example: `gmake ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system.\n\n4. **Install**\n\n   ```bash\n   sudo gmake install\n   ```\n\n   Append `PREFIX=/target/dir` to set target, default: `/usr/local`\n\n   Notice! Only use \"sudo\" when installing to a NON user owned directory.\n\n5. **(Recommended) Set suid bit to make btop always run as root (or other user)**\n\n   ```bash\n   sudo gmake setuid\n   ```\n\n   No need for `sudo` to see information for non user owned processes and to enable signal sending to any process.\n\n   Run after make install and use same PREFIX if any was used at install.\n\n   Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `wheel`\n\n* **Uninstall**\n\n   ```bash\n   sudo gmake uninstall\n   ```\n\n* **Remove any object files from source dir**\n\n   ```bash\n   gmake clean\n   ```\n\n* **Remove all object files, binaries and created directories in source dir**\n\n   ```bash\n   gmake distclean\n   ```\n\n* **Show help**\n\n   ```bash\n   gmake help\n   ```\n\n</details>\n<details>\n<summary>\n\n### With CMake (Community maintained)\n</summary>\n\n1. **Install build dependencies**\n\n   Requires Clang / GCC, CMake, Ninja, Lowdown and Git\n\n   ```bash\n   pkg install cmake ninja lowdown\n   ```\n\n2. **Clone the repository**\n\n   ```bash\n   git clone https://github.com/aristocratos/btop.git && cd btop\n   ```\n\n3. **Compile**\n\n   ```bash\n   # Configure\n   cmake -B build -G Ninja\n   # Build\n   cmake --build build\n   ```\n\n   This will automatically build a release version of btop.\n\n   Some useful options to pass to the configure step:\n\n   | Configure flag                  | Description                                                             |\n   |---------------------------------|-------------------------------------------------------------------------|\n   | `-DBTOP_STATIC=<ON\\|OFF>`       | Enables static linking (OFF by default)                                 |\n   | `-DBTOP_LTO=<ON\\|OFF>`          | Enables link time optimization (ON by default)                          |\n\n\n   | `-DCMAKE_INSTALL_PREFIX=<path>` | The installation prefix ('/usr/local' by default)                       |\n\n   _**Note:** Static linking does not work with GCC._\n\n   To force any other compiler, run `CXX=<compiler> cmake -B build -G Ninja`\n\n4. **Install**\n\n   ```bash\n   cmake --install build\n   ```\n\n   May require root privileges\n\n5. **Uninstall**\n\n   CMake doesn't generate an uninstall target by default. To remove installed files, run\n   ```\n   cat build/install_manifest.txt | xargs rm -irv\n   ```\n\n6. **Cleanup build directory**\n\n   ```bash\n   cmake --build build -t clean\n   ```\n\n</details>\n\n## Compilation NetBSD\n\n   Requires at least GCC 14.\n\n   Note that GNU make (`gmake`) is required to compile on NetBSD.\n\n<details>\n<summary>\n\n### With gmake\n</summary>\n\n1. **Install dependencies**\n\n   ```bash\n   /usr/sbin/pkg_add pkgin\n   pkgin install -y coregutils gcc14 git gmake\n   ```\n\n2. **Clone repository**\n\n   ```bash\n   git clone https://github.com/aristocratos/btop.git\n   cd btop\n   ```\n\n3. **Compile**\n\n   ```bash\n   CXX=/usr/pkg/gcc14/bin/g++ gmake CXXFLAGS=\"-DNDEBUG\"\n   ```\n\n   Options for make:\n\n   | Flag                            | Description                                                             |\n   |---------------------------------|-------------------------------------------------------------------------|\n   | `VERBOSE=true`                  | To display full compiler/linker commands                                |\n   | `STATIC=true`                   | For static compilation (only libgcc and libstdc++)                      |\n   | `QUIET=true`                    | For less verbose output                                                 |\n   | `STRIP=true`                    | To force stripping of debug symbols (adds `-s` linker flag)             |\n   | `DEBUG=true`                    | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging        |\n   | `ARCH=<architecture>`           | To manually set the target architecture                                 |\n   | `ADDFLAGS=<flags>`              | For appending flags to both compiler and linker                         |\n   | `CXX=<compiler>`                | Manually set which compiler to use                                      |\n\n   Example: `gmake ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system.\n\n4. **Install**\n\n   ```bash\n   sudo gmake install\n   ```\n\n   Append `PREFIX=/target/dir` to set target, default: `/usr/local`\n\n   Notice! Only use \"sudo\" when installing to a NON user owned directory.\n\n5. **(Recommended) Set suid bit to make btop always run as root (or other user)**\n\n   ```bash\n   sudo gmake setuid\n   ```\n\n   No need for `sudo` to see information for non user owned processes and to enable signal sending to any process.\n\n   Run after make install and use same PREFIX if any was used at install.\n\n   Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `wheel`\n\n* **Uninstall**\n\n   ```bash\n   sudo gmake uninstall\n   ```\n\n* **Remove any object files from source dir**\n\n   ```bash\n   gmake clean\n   ```\n\n* **Remove all object files, binaries and created directories in source dir**\n\n   ```bash\n   gmake distclean\n   ```\n\n* **Show help**\n\n   ```bash\n   gmake help\n   ```\n\n</details>\n<details>\n<summary>\n\n### With CMake (Community maintained)\n</summary>\n\n1. **Install build dependencies**\n\n   Requires GCC, CMake, Ninja and Git\n\n   ```bash\n   /usr/sbin/pkg_add pkgin\n   pkgin install cmake ninja-build gcc14 git\n   ```\n\n2. **Clone the repository**\n\n   ```bash\n   git clone https://github.com/aristocratos/btop.git && cd btop\n   ```\n\n3. **Compile**\n\n   ```bash\n   # Configure\n   CXX=\"/usr/pkg/gcc14/bin/g++\" cmake -B build -G Ninja\n   # Build\n   cmake --build build\n   ```\n\n   This will automatically build a release version of btop.\n\n   Some useful options to pass to the configure step:\n\n   | Configure flag                  | Description                                                             |\n   |---------------------------------|-------------------------------------------------------------------------|\n   | `-DBTOP_LTO=<ON\\|OFF>`          | Enables link time optimization (ON by default)                          |\n\n\n   | `-DCMAKE_INSTALL_PREFIX=<path>` | The installation prefix ('/usr/local' by default)                       |\n\n   To force any other compiler, run `CXX=<compiler> cmake -B build -G Ninja`\n\n4. **Install**\n\n   ```bash\n   cmake --install build\n   ```\n\n   May require root privileges\n\n5. **Uninstall**\n\n   CMake doesn't generate an uninstall target by default. To remove installed files, run\n   ```\n   cat build/install_manifest.txt | xargs rm -irv\n   ```\n\n6. **Cleanup build directory**\n\n   ```bash\n   cmake --build build -t clean\n   ```\n\n</details>\n\n## Compilation OpenBSD\n\n   Note that GNU make (`gmake`) is required to compile on OpenBSD.\n\n<details>\n<summary>\n\n### With gmake\n</summary>\n\n1. **Install dependencies**\n\n   ```bash\n   pkg_add coreutils git gmake lowdown\n   ```\n\n2. **Clone repository**\n\n   ```bash\n   git clone https://github.com/aristocratos/btop.git\n   cd btop\n   ```\n\n3. **Compile**\n\n   ```bash\n   gmake\n   ```\n\n   Options for make:\n\n   | Flag                            | Description                                                             |\n   |---------------------------------|-------------------------------------------------------------------------|\n   | `VERBOSE=true`                  | To display full compiler/linker commands                                |\n   | `STATIC=true`                   | For static compilation (only libgcc and libstdc++)                      |\n   | `QUIET=true`                    | For less verbose output                                                 |\n   | `STRIP=true`                    | To force stripping of debug symbols (adds `-s` linker flag)             |\n   | `DEBUG=true`                    | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging        |\n   | `ARCH=<architecture>`           | To manually set the target architecture                                 |\n   | `ADDFLAGS=<flags>`              | For appending flags to both compiler and linker                         |\n   | `CXX=<compiler>`                | Manually set which compiler to use                                       |\n\n   Example: `gmake ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system.\n\n4. **Install**\n\n   ```bash\n   sudo gmake install\n   ```\n\n   Append `PREFIX=/target/dir` to set target, default: `/usr/local`\n\n   Notice! Only use \"sudo\" when installing to a NON user owned directory.\n\n5. **(Recommended) Set suid bit to make btop always run as root (or other user)**\n\n   ```bash\n   sudo gmake setuid\n   ```\n\n   No need for `sudo` to see information for non user owned processes and to enable signal sending to any process.\n\n   Run after make install and use same PREFIX if any was used at install.\n\n   Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `wheel`\n\n* **Uninstall**\n\n   ```bash\n   sudo gmake uninstall\n   ```\n\n* **Remove any object files from source dir**\n\n   ```bash\n   gmake clean\n   ```\n\n* **Remove all object files, binaries and created directories in source dir**\n\n   ```bash\n   gmake distclean\n   ```\n\n* **Show help**\n\n   ```bash\n   gmake help\n   ```\n\n</details>\n<details>\n<summary>\n\n### With CMake (Community maintained)\n</summary>\n\n1. **Install build dependencies**\n\n   Requires GCC, CMake, Ninja, Lowdown and Git\n\n   _**Note:** LLVM's libc++ shipped with OpenBSD 7.4 is too old and cannot compile btop._\n\n   ```bash\n   pkg_add cmake git ninja lowdown\n   ```\n\n2. **Clone the repository**\n\n   ```bash\n   git clone https://github.com/aristocratos/btop.git && cd btop\n   ```\n\n3. **Compile**\n\n   ```bash\n   # Configure\n   cmake -B build -G Ninja\n   # Build\n   cmake --build build\n   ```\n\n   This will automatically build a release version of btop.\n\n   Some useful options to pass to the configure step:\n\n   | Configure flag                  | Description                                                             |\n   |---------------------------------|-------------------------------------------------------------------------|\n   | `-DBTOP_LTO=<ON\\|OFF>`          | Enables link time optimization (ON by default)                          |\n   | `-DCMAKE_INSTALL_PREFIX=<path>` | The installation prefix ('/usr/local' by default)                       |\n\n   To force any other compiler, run `CXX=<compiler> cmake -B build -G Ninja`\n\n4. **Install**\n\n   ```bash\n   cmake --install build\n   ```\n\n   May require root privileges\n\n5. **Uninstall**\n\n   CMake doesn't generate an uninstall target by default. To remove installed files, run\n   ```\n   cat build/install_manifest.txt | xargs rm -irv\n   ```\n\n6. **Cleanup build directory**\n\n   ```bash\n   cmake --build build -t clean\n   ```\n\n</details>\n\n## Testing\n\nTesting requires [CMake](cmake.org). Tests are build by default and can be run with `ctest --test-dir <build>`.\n\nIf you want to disable building tests, pass `-DBUILD_TESTING=OFF` to the configure step.\n\n## Installing the snap\n[![btop](https://snapcraft.io/btop/badge.svg)](https://snapcraft.io/btop)\n\n### Note: there are now two snaps available: `btop` and `btop-desktop`. The desktop version is much larger and includes the desktop entries needed to allow for launching `btop` with a click.\n\n * **Install the snap**\n\n    ```bash\n    sudo snap install btop\n    or\n    sudo snap install btop-desktop\n    ```\n * **Install the latest snap from the edge channel**\n   ```\n   sudo snap install btop --edge\n   or\n   sudo snap install btop-desktop --edge\n   ```\n\n * **Connect the interface**\n\n    ```bash\n\tsudo snap connect btop:removable-media\n\tor\n\tsudo snap connect btop-desktop:removable-media\n\t```\n\n## Configurability\n\nAll options changeable from within UI.\nConfig and log files stored in `$XDG_CONFIG_HOME/btop` or `$HOME/.config/btop` folder\n\n#### btop.conf: (auto generated if not found)\n\n```toml\n#? Config file for btop v.1.4.5\n\n#* Name of a btop++/bpytop/bashtop formatted \".theme\" file, \"Default\" and \"TTY\" for builtin themes.\n#* Themes should be placed in \"../share/btop/themes\" relative to binary or \"$HOME/.config/btop/themes\"\ncolor_theme = \"Default\"\n\n#* If the theme set background should be shown, set to False if you want terminal background transparency.\ntheme_background = true\n\n#* Sets if 24-bit truecolor should be used, will convert 24-bit colors to 256 color (6x6x6 color cube) if false.\ntruecolor = true\n\n#* Set to true to force tty mode regardless if a real tty has been detected or not.\n#* Will force 16-color mode and TTY theme, set all graph symbols to \"tty\" and swap out other non tty friendly symbols.\nforce_tty = false\n\n#* Define presets for the layout of the boxes. Preset 0 is always all boxes shown with default settings. Max 9 presets.\n#* Format: \"box_name:P:G,box_name:P:G\" P=(0 or 1) for alternate positions, G=graph symbol to use for box.\n#* Use whitespace \" \" as separator between different presets.\n#* Example: \"cpu:0:default,mem:0:tty,proc:1:default cpu:0:braille,proc:0:tty\"\npresets = \"cpu:1:default,proc:0:default cpu:0:default,mem:0:default,net:0:default cpu:0:block,net:0:tty\"\n\n#* Set to True to enable \"h,j,k,l,g,G\" keys for directional control in lists.\n#* Conflicting keys for h:\"help\" and k:\"kill\" is accessible while holding shift.\nvim_keys = false\n\n#* Rounded corners on boxes, is ignored if TTY mode is ON.\nrounded_corners = true\n\n#* Use terminal synchronized output sequences to reduce flickering on supported terminals.\nterminal_sync = true\n\n#* Default symbols to use for graph creation, \"braille\", \"block\" or \"tty\".\n#* \"braille\" offers the highest resolution but might not be included in all fonts.\n#* \"block\" has half the resolution of braille but uses more common characters.\n#* \"tty\" uses only 3 different symbols but will work with most fonts and should work in a real TTY.\n#* Note that \"tty\" only has half the horizontal resolution of the other two, so will show a shorter historical view.\ngraph_symbol = \"braille\"\n\n# Graph symbol to use for graphs in cpu box, \"default\", \"braille\", \"block\" or \"tty\".\ngraph_symbol_cpu = \"default\"\n\n# Graph symbol to use for graphs in cpu box, \"default\", \"braille\", \"block\" or \"tty\".\ngraph_symbol_mem = \"default\"\n\n# Graph symbol to use for graphs in cpu box, \"default\", \"braille\", \"block\" or \"tty\".\ngraph_symbol_net = \"default\"\n\n# Graph symbol to use for graphs in cpu box, \"default\", \"braille\", \"block\" or \"tty\".\ngraph_symbol_proc = \"default\"\n\n#* Manually set which boxes to show. Available values are \"cpu mem net proc\" and \"gpu0\" through \"gpu5\", separate values with whitespace.\nshown_boxes = \"cpu mem net proc\"\n\n#* Update time in milliseconds, recommended 2000 ms or above for better sample times for graphs.\nupdate_ms = 2000\n\n#* Processes sorting, \"pid\" \"program\" \"arguments\" \"threads\" \"user\" \"memory\" \"cpu lazy\" \"cpu direct\",\n#* \"cpu lazy\" sorts top process over time (easier to follow), \"cpu direct\" updates top process directly.\nproc_sorting = \"cpu lazy\"\n\n#* Reverse sorting order, True or False.\nproc_reversed = false\n\n#* Show processes as a tree.\nproc_tree = false\n\n#* Use the cpu graph colors in the process list.\nproc_colors = true\n\n#* Use a darkening gradient in the process list.\nproc_gradient = true\n\n#* If process cpu usage should be of the core it's running on or usage of the total available cpu power.\nproc_per_core = false\n\n#* Show process memory as bytes instead of percent.\nproc_mem_bytes = true\n\n#* Show cpu graph for each process.\nproc_cpu_graphs = true\n\n#* Use /proc/[pid]/smaps for memory information in the process info box (very slow but more accurate)\nproc_info_smaps = false\n\n#* Show proc box on left side of screen instead of right.\nproc_left = false\n\n#* (Linux) Filter processes tied to the Linux kernel(similar behavior to htop).\nproc_filter_kernel = false\n\n#* Should the process list follow the selected process when detailed view is open.\nproc_follow_detailed = true\n\n#* In tree-view, always accumulate child process resources in the parent process.\nproc_aggregate = false\n\n#* Should cpu and memory usage display be preserved for dead processes when paused.\nkeep_dead_proc_usage = false\n\n#* Sets the CPU stat shown in upper half of the CPU graph, \"total\" is always available.\n#* Select from a list of detected attributes from the options menu.\ncpu_graph_upper = \"Auto\"\n\n#* Sets the CPU stat shown in lower half of the CPU graph, \"total\" is always available.\n#* Select from a list of detected attributes from the options menu.\ncpu_graph_lower = \"Auto\"\n\n#* Toggles if the lower CPU graph should be inverted.\ncpu_invert_lower = true\n\n#* Set to True to completely disable the lower CPU graph.\ncpu_single_graph = false\n\n#* Show cpu box at bottom of screen instead of top.\ncpu_bottom = false\n\n#* Shows the system uptime in the CPU box.\nshow_uptime = true\n\n#* Shows the CPU package current power consumption in watts. Requires running `make setcap` or `make setuid` or running with sudo.\nshow_cpu_watts = true\n\n#* Show cpu temperature.\ncheck_temp = true\n\n#* Which sensor to use for cpu temperature, use options menu to select from list of available sensors.\ncpu_sensor = \"Auto\"\n\n#* Show temperatures for cpu cores also if check_temp is True and sensors has been found.\nshow_coretemp = true\n\n#* Set a custom mapping between core and coretemp, can be needed on certain cpus to get correct temperature for correct core.\n#* Use lm-sensors or similar to see which cores are reporting temperatures on your machine.\n#* Format \"x:y\" x=core with wrong temp, y=core with correct temp, use space as separator between multiple entries.\n#* Example: \"4:0 5:1 6:3\"\ncpu_core_map = \"\"\n\n#* Which temperature scale to use, available values: \"celsius\", \"fahrenheit\", \"kelvin\" and \"rankine\".\ntemp_scale = \"celsius\"\n\n#* Use base 10 for bits/bytes sizes, KB = 1000 instead of KiB = 1024.\nbase_10_sizes = false\n\n#* Show CPU frequency.\nshow_cpu_freq = true\n\n#* How to calculate CPU frequency, available values: \"first\", \"range\", \"lowest\", \"highest\" and \"average\".\nfreq_mode = \"first\"\n\n#* Draw a clock at top of screen, formatting according to strftime, empty string to disable.\n#* Special formatting: /host = hostname | /user = username | /uptime = system uptime\nclock_format = \"%X\"\n\n#* Update main ui in background when menus are showing, set this to false if the menus is flickering too much for comfort.\nbackground_update = true\n\n#* Custom cpu model name, empty string to disable.\ncustom_cpu_name = \"\"\n\n#* Optional filter for shown disks, should be full path of a mountpoint, separate multiple values with whitespace \" \".\n#* Only disks matching the filter will be shown. Prepend exclude= to only show disks not matching the filter. Examples: disk_filter=\"/boot /home/user\", disks_filter=\"exclude=/boot /home/user\"\ndisks_filter = \"\"\n\n#* Show graphs instead of meters for memory values.\nmem_graphs = true\n\n#* Show mem box below net box instead of above.\nmem_below_net = false\n\n#* Count ZFS ARC in cached and available memory.\nzfs_arc_cached = true\n\n#* If swap memory should be shown in memory box.\nshow_swap = true\n\n#* Show swap as a disk, ignores show_swap value above, inserts itself after first disk.\nswap_disk = true\n\n#* If mem box should be split to also show disks info.\nshow_disks = true\n\n#* Filter out non physical disks. Set this to False to include network disks, RAM disks and similar.\nonly_physical = true\n\n#* Read disks list from /etc/fstab. This also disables only_physical.\nuse_fstab = true\n\n#* Setting this to True will hide all datasets, and only show ZFS pools. (IO stats will be calculated per-pool)\nzfs_hide_datasets = false\n\n#* Set to true to show available disk space for privileged users.\ndisk_free_priv = false\n\n#* Toggles if io activity % (disk busy time) should be shown in regular disk usage view.\nshow_io_stat = true\n\n#* Toggles io mode for disks, showing big graphs for disk read/write speeds.\nio_mode = false\n\n#* Set to True to show combined read/write io graphs in io mode.\nio_graph_combined = false\n\n#* Set the top speed for the io graphs in MiB/s (100 by default), use format \"mountpoint:speed\" separate disks with whitespace \" \".\n#* Example: \"/mnt/media:100 /:20 /boot:1\".\nio_graph_speeds = \"\"\n\n#* Set fixed values for network graphs in Mebibits. Is only used if net_auto is also set to False.\nnet_download = 100\n\nnet_upload = 100\n\n#* Use network graphs auto rescaling mode, ignores any values set above and rescales down to 10 Kibibytes at the lowest.\nnet_auto = true\n\n#* Sync the auto scaling for download and upload to whichever currently has the highest scale.\nnet_sync = true\n\n#* Starts with the Network Interface specified here.\nnet_iface = \"\"\n\n#* \"True\" shows bitrates in base 10 (Kbps, Mbps). \"False\" shows bitrates in binary sizes (Kibps, Mibps, etc.). \"Auto\" uses base_10_sizes.\nbase_10_bitrate = \"Auto\"\n\n#* Show battery stats in top right if battery is present.\nshow_battery = true\n\n#* Which battery to use if multiple are present. \"Auto\" for auto detection.\nselected_battery = \"Auto\"\n\n#* Show power stats of battery next to charge indicator.\nshow_battery_watts = true\n\n#* Set loglevel for \"~/.local/state/btop.log\" levels are: \"ERROR\" \"WARNING\" \"INFO\" \"DEBUG\".\n#* The level set includes all lower levels, i.e. \"DEBUG\" will show all logging info.\nlog_level = \"WARNING\"\n```\n\n#### Command line options\n\n```text\nUsage: btop [OPTIONS]\n\nOptions:\n  -c, --config <file>     Path to a config file\n  -d, --debug             Start in debug mode with additional logs and metrics\n  -f, --filter <filter>   Set an initial process filter\n      --force-utf         Override automatic UTF locale detection\n  -l, --low-color         Disable true color, 256 colors only\n  -p, --preset <id>       Start with a preset (0-9)\n  -t, --tty               Force tty mode with ANSI graph symbols and 16 colors only\n      --no-tty            Force disable tty mode\n  -u, --update <ms>       Set an initial update rate in milliseconds\n      --default-config    Print default config to standard output\n  -h, --help              Show this help message and exit\n  -V, --version           Show a version message and exit (more with --version)\n```\n\n## LICENSE\n\n[Apache License 2.0](LICENSE)\n"
  },
  {
    "path": "btop.desktop",
    "content": "[Desktop Entry]\nType=Application\nVersion=1.0\nName=btop++\nGenericName=System Monitor\nGenericName[it]=Monitor di sistema\nGenericName[zh_TW]=系統監視器\nGenericName[pt_BR]=Monitor de sistema\nComment=Resource monitor that shows usage and stats for processor, memory, disks, network and processes\nComment[it]=Monitoraggio delle risorse: mostra utilizzo e statistiche per CPU, dischi, rete e processi\nComment[zh_TW]=顯示處理器、主記憶體、磁碟、網路與進程的使用與統計數據的資源監視器應用程式\nComment[pt_BR]=Monitoramente de atividades com estatisticas e graficos por CPU, disco, rede e processos\nIcon=btop\nExec=btop\nTerminal=true\nCategories=System;Monitor;ConsoleOnly;\nKeywords=system;process;task\nKeywords[zh_TW]=系統;進程;處理程序;任務\nKeywords[pt_BR]=sistema;processos;tarefas\n"
  },
  {
    "path": "cmake/Finddevstat.cmake",
    "content": "# SPDX-License-Identifier: Apache-2.0\n#\n# Find devstat, the Device Statistics Library\n#\n\nif(CMAKE_SYSTEM_NAME STREQUAL \"FreeBSD\" OR CMAKE_SYSTEM_NAME STREQUAL \"MidnightBSD\")\n  find_path(devstat_INCLUDE_DIR NAMES devstat.h)\n  find_library(devstat_LIBRARY NAMES devstat)\n\n  include(FindPackageHandleStandardArgs)\n  find_package_handle_standard_args(devstat REQUIRED_VARS devstat_LIBRARY devstat_INCLUDE_DIR)\n\n  if(devstat_FOUND AND NOT TARGET devstat::devstat)\n    add_library(devstat::devstat UNKNOWN IMPORTED)\n    set_target_properties(devstat::devstat PROPERTIES\n      IMPORTED_LOCATION \"${devstat_LIBRARY}\"\n      INTERFACE_INCLUDE_DIRECTORIES \"${devstat_INCLUDE_DIR}\"\n    )\n  endif()\n\n  mark_as_advanced(devstat_INCLUDE_DIR devstat_LIBRARY)\nendif()\n\n"
  },
  {
    "path": "cmake/Findelf.cmake",
    "content": "# SPDX-License-Identifier: Apache-2.0\n#\n# Find libelf, the ELF Access Library\n#\n\nif(CMAKE_SYSTEM_NAME STREQUAL \"FreeBSD\" OR CMAKE_SYSTEM_NAME STREQUAL \"MidnightBSD\")\n  find_path(elf_INCLUDE_DIR NAMES libelf.h)\n  find_library(elf_LIBRARY NAMES elf)\n\n  include(FindPackageHandleStandardArgs)\n  find_package_handle_standard_args(elf REQUIRED_VARS elf_LIBRARY elf_INCLUDE_DIR)\n\n  if(elf_FOUND AND NOT TARGET elf::elf)\n    add_library(elf::elf UNKNOWN IMPORTED)\n    set_target_properties(elf::elf PROPERTIES\n      IMPORTED_LOCATION \"${elf_LIBRARY}\"\n      INTERFACE_INCLUDE_DIRECTORIES \"${elf_INCLUDE_DIR}\"\n    )\n  endif()\n\n  mark_as_advanced(elf_INCLUDE_DIR elf_LIBRARY)\nendif()\n\n"
  },
  {
    "path": "cmake/Findkvm.cmake",
    "content": "# SPDX-License-Identifier: Apache-2.0\n#\n# Find libkvm, the Kernel Data Access Library\n#\n\nif(BSD)\n  find_path(kvm_INCLUDE_DIR NAMES kvm.h)\n  find_library(kvm_LIBRARY NAMES kvm)\n\n  include(FindPackageHandleStandardArgs)\n  find_package_handle_standard_args(kvm REQUIRED_VARS kvm_LIBRARY kvm_INCLUDE_DIR)\n\n  if(kvm_FOUND AND NOT TARGET kvm::kvm)\n    add_library(kvm::kvm UNKNOWN IMPORTED)\n    set_target_properties(kvm::kvm PROPERTIES\n      IMPORTED_LOCATION \"${kvm_LIBRARY}\"\n      INTERFACE_INCLUDE_DIRECTORIES \"${kvm_INCLUDE_DIR}\"\n    )\n  endif()\n\n  mark_as_advanced(kvm_INCLUDE_DIR kvm_LIBRARY)\nendif()\n\n"
  },
  {
    "path": "cmake/Findproplib.cmake",
    "content": "# SPDX-License-Identifier: Apache-2.0\n#\n# Find proplib – property container object library\n#\n\nif(BSD)\n  find_path(proplib_INCLUDE_DIR NAMES prop/proplib.h)\n  find_library(proplib_LIBRARY NAMES libprop prop)\n\n  include(FindPackageHandleStandardArgs)\n  find_package_handle_standard_args(proplib REQUIRED_VARS proplib_LIBRARY proplib_INCLUDE_DIR)\n\n  if(proplib_FOUND AND NOT TARGET proplib::proplib)\n    add_library(proplib::proplib UNKNOWN IMPORTED)\n    set_target_properties(proplib::proplib PROPERTIES\n      IMPORTED_LOCATION \"${proplib_LIBRARY}\"\n      INTERFACE_INCLUDE_DIRECTORIES \"${proplib_INCLUDE_DIR}\"\n    )\n  endif()\n\n  mark_as_advanced(proplib_INCLUDE_DIR proplib_LIBRARY)\nendif()\n\n"
  },
  {
    "path": "include/fmt/LICENSE.rst",
    "content": "Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n--- Optional exception to the license ---\n\nAs an exception, if, as a result of your compiling your source code, portions\nof this Software are embedded into a machine-executable object form of such\nsource code, you may redistribute such embedded portions in such object form\nwithout including the above copyright and permission notices.\n"
  },
  {
    "path": "include/fmt/args.h",
    "content": "// Formatting library for C++ - dynamic argument lists\n//\n// Copyright (c) 2012 - present, Victor Zverovich\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_ARGS_H_\n#define FMT_ARGS_H_\n\n#ifndef FMT_MODULE\n#  include <functional>  // std::reference_wrapper\n#  include <memory>      // std::unique_ptr\n#  include <vector>\n#endif\n\n#include \"format.h\"  // std_string_view\n\nFMT_BEGIN_NAMESPACE\nnamespace detail {\n\ntemplate <typename T> struct is_reference_wrapper : std::false_type {};\ntemplate <typename T>\nstruct is_reference_wrapper<std::reference_wrapper<T>> : std::true_type {};\n\ntemplate <typename T> auto unwrap(const T& v) -> const T& { return v; }\ntemplate <typename T>\nauto unwrap(const std::reference_wrapper<T>& v) -> const T& {\n  return static_cast<const T&>(v);\n}\n\n// node is defined outside dynamic_arg_list to workaround a C2504 bug in MSVC\n// 2022 (v17.10.0).\n//\n// Workaround for clang's -Wweak-vtables. Unlike for regular classes, for\n// templates it doesn't complain about inability to deduce single translation\n// unit for placing vtable. So node is made a fake template.\ntemplate <typename = void> struct node {\n  virtual ~node() = default;\n  std::unique_ptr<node<>> next;\n};\n\nclass dynamic_arg_list {\n  template <typename T> struct typed_node : node<> {\n    T value;\n\n    template <typename Arg>\n    FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {}\n\n    template <typename Char>\n    FMT_CONSTEXPR typed_node(const basic_string_view<Char>& arg)\n        : value(arg.data(), arg.size()) {}\n  };\n\n  std::unique_ptr<node<>> head_;\n\n public:\n  template <typename T, typename Arg> auto push(const Arg& arg) -> const T& {\n    auto new_node = std::unique_ptr<typed_node<T>>(new typed_node<T>(arg));\n    auto& value = new_node->value;\n    new_node->next = std::move(head_);\n    head_ = std::move(new_node);\n    return value;\n  }\n};\n}  // namespace detail\n\n/**\n * A dynamic list of formatting arguments with storage.\n *\n * It can be implicitly converted into `fmt::basic_format_args` for passing\n * into type-erased formatting functions such as `fmt::vformat`.\n */\nFMT_EXPORT template <typename Context> class dynamic_format_arg_store {\n private:\n  using char_type = typename Context::char_type;\n\n  template <typename T> struct need_copy {\n    static constexpr detail::type mapped_type =\n        detail::mapped_type_constant<T, char_type>::value;\n\n    enum {\n      value = !(detail::is_reference_wrapper<T>::value ||\n                std::is_same<T, basic_string_view<char_type>>::value ||\n                std::is_same<T, detail::std_string_view<char_type>>::value ||\n                (mapped_type != detail::type::cstring_type &&\n                 mapped_type != detail::type::string_type &&\n                 mapped_type != detail::type::custom_type))\n    };\n  };\n\n  template <typename T>\n  using stored_t = conditional_t<\n      std::is_convertible<T, std::basic_string<char_type>>::value &&\n          !detail::is_reference_wrapper<T>::value,\n      std::basic_string<char_type>, T>;\n\n  // Storage of basic_format_arg must be contiguous.\n  std::vector<basic_format_arg<Context>> data_;\n  std::vector<detail::named_arg_info<char_type>> named_info_;\n\n  // Storage of arguments not fitting into basic_format_arg must grow\n  // without relocation because items in data_ refer to it.\n  detail::dynamic_arg_list dynamic_args_;\n\n  friend class basic_format_args<Context>;\n\n  auto data() const -> const basic_format_arg<Context>* {\n    return named_info_.empty() ? data_.data() : data_.data() + 1;\n  }\n\n  template <typename T> void emplace_arg(const T& arg) {\n    data_.emplace_back(arg);\n  }\n\n  template <typename T>\n  void emplace_arg(const detail::named_arg<char_type, T>& arg) {\n    if (named_info_.empty())\n      data_.insert(data_.begin(), basic_format_arg<Context>(nullptr, 0));\n    data_.emplace_back(detail::unwrap(arg.value));\n    auto pop_one = [](std::vector<basic_format_arg<Context>>* data) {\n      data->pop_back();\n    };\n    std::unique_ptr<std::vector<basic_format_arg<Context>>, decltype(pop_one)>\n        guard{&data_, pop_one};\n    named_info_.push_back({arg.name, static_cast<int>(data_.size() - 2u)});\n    data_[0] = {named_info_.data(), named_info_.size()};\n    guard.release();\n  }\n\n public:\n  constexpr dynamic_format_arg_store() = default;\n\n  operator basic_format_args<Context>() const {\n    return basic_format_args<Context>(data(), static_cast<int>(data_.size()),\n                                      !named_info_.empty());\n  }\n\n  /**\n   * Adds an argument into the dynamic store for later passing to a formatting\n   * function.\n   *\n   * Note that custom types and string types (but not string views) are copied\n   * into the store dynamically allocating memory if necessary.\n   *\n   * **Example**:\n   *\n   *     fmt::dynamic_format_arg_store<fmt::format_context> store;\n   *     store.push_back(42);\n   *     store.push_back(\"abc\");\n   *     store.push_back(1.5f);\n   *     std::string result = fmt::vformat(\"{} and {} and {}\", store);\n   */\n  template <typename T> void push_back(const T& arg) {\n    if (detail::const_check(need_copy<T>::value))\n      emplace_arg(dynamic_args_.push<stored_t<T>>(arg));\n    else\n      emplace_arg(detail::unwrap(arg));\n  }\n\n  /**\n   * Adds a reference to the argument into the dynamic store for later passing\n   * to a formatting function.\n   *\n   * **Example**:\n   *\n   *     fmt::dynamic_format_arg_store<fmt::format_context> store;\n   *     char band[] = \"Rolling Stones\";\n   *     store.push_back(std::cref(band));\n   *     band[9] = 'c'; // Changing str affects the output.\n   *     std::string result = fmt::vformat(\"{}\", store);\n   *     // result == \"Rolling Scones\"\n   */\n  template <typename T> void push_back(std::reference_wrapper<T> arg) {\n    static_assert(\n        need_copy<T>::value,\n        \"objects of built-in types and string views are always copied\");\n    emplace_arg(arg.get());\n  }\n\n  /**\n   * Adds named argument into the dynamic store for later passing to a\n   * formatting function. `std::reference_wrapper` is supported to avoid\n   * copying of the argument. The name is always copied into the store.\n   */\n  template <typename T>\n  void push_back(const detail::named_arg<char_type, T>& arg) {\n    const char_type* arg_name =\n        dynamic_args_.push<std::basic_string<char_type>>(arg.name).c_str();\n    if (detail::const_check(need_copy<T>::value)) {\n      emplace_arg(\n          fmt::arg(arg_name, dynamic_args_.push<stored_t<T>>(arg.value)));\n    } else {\n      emplace_arg(fmt::arg(arg_name, arg.value));\n    }\n  }\n\n  /// Erase all elements from the store.\n  void clear() {\n    data_.clear();\n    named_info_.clear();\n    dynamic_args_ = {};\n  }\n\n  /// Reserves space to store at least `new_cap` arguments including\n  /// `new_cap_named` named arguments.\n  void reserve(size_t new_cap, size_t new_cap_named) {\n    FMT_ASSERT(new_cap >= new_cap_named,\n               \"set of arguments includes set of named arguments\");\n    data_.reserve(new_cap);\n    named_info_.reserve(new_cap_named);\n  }\n\n  /// Returns the number of elements in the store.\n  auto size() const noexcept -> size_t { return data_.size(); }\n};\n\nFMT_END_NAMESPACE\n\n#endif  // FMT_ARGS_H_\n"
  },
  {
    "path": "include/fmt/base.h",
    "content": "// Formatting library for C++ - the base API for char/UTF-8\n//\n// Copyright (c) 2012 - present, Victor Zverovich\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_BASE_H_\n#define FMT_BASE_H_\n\n#if defined(FMT_IMPORT_STD) && !defined(FMT_MODULE)\n#  define FMT_MODULE\n#endif\n\n#ifndef FMT_MODULE\n#  include <limits.h>  // CHAR_BIT\n#  include <stdio.h>   // FILE\n#  include <string.h>  // memcmp\n\n#  include <type_traits>  // std::enable_if\n#endif\n\n// The fmt library version in the form major * 10000 + minor * 100 + patch.\n#define FMT_VERSION 120000\n\n// Detect compiler versions.\n#if defined(__clang__) && !defined(__ibmxl__)\n#  define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)\n#else\n#  define FMT_CLANG_VERSION 0\n#endif\n#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)\n#  define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)\n#else\n#  define FMT_GCC_VERSION 0\n#endif\n#if defined(__ICL)\n#  define FMT_ICC_VERSION __ICL\n#elif defined(__INTEL_COMPILER)\n#  define FMT_ICC_VERSION __INTEL_COMPILER\n#else\n#  define FMT_ICC_VERSION 0\n#endif\n#if defined(_MSC_VER)\n#  define FMT_MSC_VERSION _MSC_VER\n#else\n#  define FMT_MSC_VERSION 0\n#endif\n\n// Detect standard library versions.\n#ifdef _GLIBCXX_RELEASE\n#  define FMT_GLIBCXX_RELEASE _GLIBCXX_RELEASE\n#else\n#  define FMT_GLIBCXX_RELEASE 0\n#endif\n#ifdef _LIBCPP_VERSION\n#  define FMT_LIBCPP_VERSION _LIBCPP_VERSION\n#else\n#  define FMT_LIBCPP_VERSION 0\n#endif\n\n#ifdef _MSVC_LANG\n#  define FMT_CPLUSPLUS _MSVC_LANG\n#else\n#  define FMT_CPLUSPLUS __cplusplus\n#endif\n\n// Detect __has_*.\n#ifdef __has_feature\n#  define FMT_HAS_FEATURE(x) __has_feature(x)\n#else\n#  define FMT_HAS_FEATURE(x) 0\n#endif\n#ifdef __has_include\n#  define FMT_HAS_INCLUDE(x) __has_include(x)\n#else\n#  define FMT_HAS_INCLUDE(x) 0\n#endif\n#ifdef __has_builtin\n#  define FMT_HAS_BUILTIN(x) __has_builtin(x)\n#else\n#  define FMT_HAS_BUILTIN(x) 0\n#endif\n#ifdef __has_cpp_attribute\n#  define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)\n#else\n#  define FMT_HAS_CPP_ATTRIBUTE(x) 0\n#endif\n\n#define FMT_HAS_CPP14_ATTRIBUTE(attribute) \\\n  (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute))\n\n#define FMT_HAS_CPP17_ATTRIBUTE(attribute) \\\n  (FMT_CPLUSPLUS >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute))\n\n// Detect C++14 relaxed constexpr.\n#ifdef FMT_USE_CONSTEXPR\n// Use the provided definition.\n#elif FMT_GCC_VERSION >= 702 && FMT_CPLUSPLUS >= 201402L\n// GCC only allows constexpr member functions in non-literal types since 7.2:\n// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66297.\n#  define FMT_USE_CONSTEXPR 1\n#elif FMT_ICC_VERSION\n#  define FMT_USE_CONSTEXPR 0  // https://github.com/fmtlib/fmt/issues/1628\n#elif FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912\n#  define FMT_USE_CONSTEXPR 1\n#else\n#  define FMT_USE_CONSTEXPR 0\n#endif\n#if FMT_USE_CONSTEXPR\n#  define FMT_CONSTEXPR constexpr\n#else\n#  define FMT_CONSTEXPR\n#endif\n\n// Detect consteval, C++20 constexpr extensions and std::is_constant_evaluated.\n#if !defined(__cpp_lib_is_constant_evaluated)\n#  define FMT_USE_CONSTEVAL 0\n#elif FMT_CPLUSPLUS < 201709L\n#  define FMT_USE_CONSTEVAL 0\n#elif FMT_GLIBCXX_RELEASE && FMT_GLIBCXX_RELEASE < 10\n#  define FMT_USE_CONSTEVAL 0\n#elif FMT_LIBCPP_VERSION && FMT_LIBCPP_VERSION < 10000\n#  define FMT_USE_CONSTEVAL 0\n#elif defined(__apple_build_version__) && __apple_build_version__ < 14000029L\n#  define FMT_USE_CONSTEVAL 0  // consteval is broken in Apple clang < 14.\n#elif FMT_MSC_VERSION && FMT_MSC_VERSION < 1929\n#  define FMT_USE_CONSTEVAL 0  // consteval is broken in MSVC VS2019 < 16.10.\n#elif defined(__cpp_consteval)\n#  define FMT_USE_CONSTEVAL 1\n#elif FMT_GCC_VERSION >= 1002 || FMT_CLANG_VERSION >= 1101\n#  define FMT_USE_CONSTEVAL 1\n#else\n#  define FMT_USE_CONSTEVAL 0\n#endif\n#if FMT_USE_CONSTEVAL\n#  define FMT_CONSTEVAL consteval\n#  define FMT_CONSTEXPR20 constexpr\n#else\n#  define FMT_CONSTEVAL\n#  define FMT_CONSTEXPR20\n#endif\n\n// Check if exceptions are disabled.\n#ifdef FMT_USE_EXCEPTIONS\n// Use the provided definition.\n#elif defined(__GNUC__) && !defined(__EXCEPTIONS)\n#  define FMT_USE_EXCEPTIONS 0\n#elif defined(__clang__) && !defined(__cpp_exceptions)\n#  define FMT_USE_EXCEPTIONS 0\n#elif FMT_MSC_VERSION && !_HAS_EXCEPTIONS\n#  define FMT_USE_EXCEPTIONS 0\n#else\n#  define FMT_USE_EXCEPTIONS 1\n#endif\n#if FMT_USE_EXCEPTIONS\n#  define FMT_TRY try\n#  define FMT_CATCH(x) catch (x)\n#else\n#  define FMT_TRY if (true)\n#  define FMT_CATCH(x) if (false)\n#endif\n\n#ifdef FMT_NO_UNIQUE_ADDRESS\n// Use the provided definition.\n#elif FMT_CPLUSPLUS < 202002L\n// Not supported.\n#elif FMT_HAS_CPP_ATTRIBUTE(no_unique_address)\n#  define FMT_NO_UNIQUE_ADDRESS [[no_unique_address]]\n// VS2019 v16.10 and later except clang-cl (https://reviews.llvm.org/D110485).\n#elif FMT_MSC_VERSION >= 1929 && !FMT_CLANG_VERSION\n#  define FMT_NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]\n#endif\n#ifndef FMT_NO_UNIQUE_ADDRESS\n#  define FMT_NO_UNIQUE_ADDRESS\n#endif\n\n#if FMT_HAS_CPP17_ATTRIBUTE(fallthrough)\n#  define FMT_FALLTHROUGH [[fallthrough]]\n#elif defined(__clang__)\n#  define FMT_FALLTHROUGH [[clang::fallthrough]]\n#elif FMT_GCC_VERSION >= 700 && \\\n    (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520)\n#  define FMT_FALLTHROUGH [[gnu::fallthrough]]\n#else\n#  define FMT_FALLTHROUGH\n#endif\n\n// Disable [[noreturn]] on MSVC/NVCC because of bogus unreachable code warnings.\n#if FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && !defined(__NVCC__)\n#  define FMT_NORETURN [[noreturn]]\n#else\n#  define FMT_NORETURN\n#endif\n\n#ifdef FMT_NODISCARD\n// Use the provided definition.\n#elif FMT_HAS_CPP17_ATTRIBUTE(nodiscard)\n#  define FMT_NODISCARD [[nodiscard]]\n#else\n#  define FMT_NODISCARD\n#endif\n\n#if FMT_GCC_VERSION || FMT_CLANG_VERSION\n#  define FMT_VISIBILITY(value) __attribute__((visibility(value)))\n#else\n#  define FMT_VISIBILITY(value)\n#endif\n\n// Detect pragmas.\n#define FMT_PRAGMA_IMPL(x) _Pragma(#x)\n#if FMT_GCC_VERSION >= 504 && !defined(__NVCOMPILER)\n// Workaround a _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884\n// and an nvhpc warning: https://github.com/fmtlib/fmt/pull/2582.\n#  define FMT_PRAGMA_GCC(x) FMT_PRAGMA_IMPL(GCC x)\n#else\n#  define FMT_PRAGMA_GCC(x)\n#endif\n#if FMT_CLANG_VERSION\n#  define FMT_PRAGMA_CLANG(x) FMT_PRAGMA_IMPL(clang x)\n#else\n#  define FMT_PRAGMA_CLANG(x)\n#endif\n#if FMT_MSC_VERSION\n#  define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__))\n#else\n#  define FMT_MSC_WARNING(...)\n#endif\n\n// Enable minimal optimizations for more compact code in debug mode.\nFMT_PRAGMA_GCC(push_options)\n#if !defined(__OPTIMIZE__) && !defined(__CUDACC__) && !defined(FMT_MODULE)\nFMT_PRAGMA_GCC(optimize(\"Og\"))\n#  define FMT_GCC_OPTIMIZED\n#endif\nFMT_PRAGMA_CLANG(diagnostic push)\n\n#ifdef FMT_ALWAYS_INLINE\n// Use the provided definition.\n#elif FMT_GCC_VERSION || FMT_CLANG_VERSION\n#  define FMT_ALWAYS_INLINE inline __attribute__((always_inline))\n#else\n#  define FMT_ALWAYS_INLINE inline\n#endif\n// A version of FMT_ALWAYS_INLINE to prevent code bloat in debug mode.\n#if defined(NDEBUG) || defined(FMT_GCC_OPTIMIZED)\n#  define FMT_INLINE FMT_ALWAYS_INLINE\n#else\n#  define FMT_INLINE inline\n#endif\n\n#ifndef FMT_BEGIN_NAMESPACE\n#  define FMT_BEGIN_NAMESPACE \\\n    namespace fmt {           \\\n    inline namespace v12 {\n#  define FMT_END_NAMESPACE \\\n    }                       \\\n    }\n#endif\n\n#ifndef FMT_EXPORT\n#  define FMT_EXPORT\n#  define FMT_BEGIN_EXPORT\n#  define FMT_END_EXPORT\n#endif\n\n#ifdef _WIN32\n#  define FMT_WIN32 1\n#else\n#  define FMT_WIN32 0\n#endif\n\n#if !defined(FMT_HEADER_ONLY) && FMT_WIN32\n#  if defined(FMT_LIB_EXPORT)\n#    define FMT_API __declspec(dllexport)\n#  elif defined(FMT_SHARED)\n#    define FMT_API __declspec(dllimport)\n#  endif\n#elif defined(FMT_LIB_EXPORT) || defined(FMT_SHARED)\n#  define FMT_API FMT_VISIBILITY(\"default\")\n#endif\n#ifndef FMT_API\n#  define FMT_API\n#endif\n\n#ifndef FMT_OPTIMIZE_SIZE\n#  define FMT_OPTIMIZE_SIZE 0\n#endif\n\n// FMT_BUILTIN_TYPE=0 may result in smaller library size at the cost of higher\n// per-call binary size by passing built-in types through the extension API.\n#ifndef FMT_BUILTIN_TYPES\n#  define FMT_BUILTIN_TYPES 1\n#endif\n\n#define FMT_APPLY_VARIADIC(expr) \\\n  using unused = int[];          \\\n  (void)unused { 0, (expr, 0)... }\n\nFMT_BEGIN_NAMESPACE\n\n// Implementations of enable_if_t and other metafunctions for older systems.\ntemplate <bool B, typename T = void>\nusing enable_if_t = typename std::enable_if<B, T>::type;\ntemplate <bool B, typename T, typename F>\nusing conditional_t = typename std::conditional<B, T, F>::type;\ntemplate <bool B> using bool_constant = std::integral_constant<bool, B>;\ntemplate <typename T>\nusing remove_reference_t = typename std::remove_reference<T>::type;\ntemplate <typename T>\nusing remove_const_t = typename std::remove_const<T>::type;\ntemplate <typename T>\nusing remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;\ntemplate <typename T>\nusing make_unsigned_t = typename std::make_unsigned<T>::type;\ntemplate <typename T>\nusing underlying_t = typename std::underlying_type<T>::type;\ntemplate <typename T> using decay_t = typename std::decay<T>::type;\nusing nullptr_t = decltype(nullptr);\n\n#if (FMT_GCC_VERSION && FMT_GCC_VERSION < 500) || FMT_MSC_VERSION\n// A workaround for gcc 4.9 & MSVC v141 to make void_t work in a SFINAE context.\ntemplate <typename...> struct void_t_impl {\n  using type = void;\n};\ntemplate <typename... T> using void_t = typename void_t_impl<T...>::type;\n#else\ntemplate <typename...> using void_t = void;\n#endif\n\nstruct monostate {\n  constexpr monostate() {}\n};\n\n// An enable_if helper to be used in template parameters which results in much\n// shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed\n// to workaround a bug in MSVC 2019 (see #1140 and #1186).\n#ifdef FMT_DOC\n#  define FMT_ENABLE_IF(...)\n#else\n#  define FMT_ENABLE_IF(...) fmt::enable_if_t<(__VA_ARGS__), int> = 0\n#endif\n\ntemplate <typename T> constexpr auto min_of(T a, T b) -> T {\n  return a < b ? a : b;\n}\ntemplate <typename T> constexpr auto max_of(T a, T b) -> T {\n  return a > b ? a : b;\n}\n\nFMT_NORETURN FMT_API void assert_fail(const char* file, int line,\n                                      const char* message);\n\nnamespace detail {\n// Suppresses \"unused variable\" warnings with the method described in\n// https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/.\n// (void)var does not work on many Intel compilers.\ntemplate <typename... T> FMT_CONSTEXPR void ignore_unused(const T&...) {}\n\nconstexpr auto is_constant_evaluated(bool default_value = false) noexcept\n    -> bool {\n// Workaround for incompatibility between clang 14 and libstdc++ consteval-based\n// std::is_constant_evaluated: https://github.com/fmtlib/fmt/issues/3247.\n#if FMT_CPLUSPLUS >= 202002L && FMT_GLIBCXX_RELEASE >= 12 && \\\n    (FMT_CLANG_VERSION >= 1400 && FMT_CLANG_VERSION < 1500)\n  ignore_unused(default_value);\n  return __builtin_is_constant_evaluated();\n#elif defined(__cpp_lib_is_constant_evaluated)\n  ignore_unused(default_value);\n  return std::is_constant_evaluated();\n#else\n  return default_value;\n#endif\n}\n\n// Suppresses \"conditional expression is constant\" warnings.\ntemplate <typename T> FMT_ALWAYS_INLINE constexpr auto const_check(T val) -> T {\n  return val;\n}\n\nFMT_NORETURN FMT_API void assert_fail(const char* file, int line,\n                                      const char* message);\n\n#if defined(FMT_ASSERT)\n// Use the provided definition.\n#elif defined(NDEBUG)\n// FMT_ASSERT is not empty to avoid -Wempty-body.\n#  define FMT_ASSERT(condition, message) \\\n    fmt::detail::ignore_unused((condition), (message))\n#else\n#  define FMT_ASSERT(condition, message)                                    \\\n    ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \\\n         ? (void)0                                                          \\\n         : ::fmt::assert_fail(__FILE__, __LINE__, (message)))\n#endif\n\n#ifdef FMT_USE_INT128\n// Use the provided definition.\n#elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \\\n    !(FMT_CLANG_VERSION && FMT_MSC_VERSION)\n#  define FMT_USE_INT128 1\nusing int128_opt = __int128_t;  // An optional native 128-bit integer.\nusing uint128_opt = __uint128_t;\ninline auto map(int128_opt x) -> int128_opt { return x; }\ninline auto map(uint128_opt x) -> uint128_opt { return x; }\n#else\n#  define FMT_USE_INT128 0\n#endif\n#if !FMT_USE_INT128\nenum class int128_opt {};\nenum class uint128_opt {};\n// Reduce template instantiations.\ninline auto map(int128_opt) -> monostate { return {}; }\ninline auto map(uint128_opt) -> monostate { return {}; }\n#endif\n\n#ifndef FMT_USE_BITINT\n#  define FMT_USE_BITINT (FMT_CLANG_VERSION >= 1500)\n#endif\n\n#if FMT_USE_BITINT\nFMT_PRAGMA_CLANG(diagnostic ignored \"-Wbit-int-extension\")\ntemplate <int N> using bitint = _BitInt(N);\ntemplate <int N> using ubitint = unsigned _BitInt(N);\n#else\ntemplate <int N> struct bitint {};\ntemplate <int N> struct ubitint {};\n#endif  // FMT_USE_BITINT\n\n// Casts a nonnegative integer to unsigned.\ntemplate <typename Int>\nFMT_CONSTEXPR auto to_unsigned(Int value) -> make_unsigned_t<Int> {\n  FMT_ASSERT(std::is_unsigned<Int>::value || value >= 0, \"negative value\");\n  return static_cast<make_unsigned_t<Int>>(value);\n}\n\ntemplate <typename Char>\nusing unsigned_char = conditional_t<sizeof(Char) == 1, unsigned char, unsigned>;\n\n// A heuristic to detect std::string and std::[experimental::]string_view.\n// It is mainly used to avoid dependency on <[experimental/]string_view>.\ntemplate <typename T, typename Enable = void>\nstruct is_std_string_like : std::false_type {};\ntemplate <typename T>\nstruct is_std_string_like<T, void_t<decltype(std::declval<T>().find_first_of(\n                                 typename T::value_type(), 0))>>\n    : std::is_convertible<decltype(std::declval<T>().data()),\n                          const typename T::value_type*> {};\n\n// Check if the literal encoding is UTF-8.\nenum { is_utf8_enabled = \"\\u00A7\"[1] == '\\xA7' };\nenum { use_utf8 = !FMT_WIN32 || is_utf8_enabled };\n\n#ifndef FMT_UNICODE\n#  define FMT_UNICODE 1\n#endif\n\nstatic_assert(!FMT_UNICODE || use_utf8,\n              \"Unicode support requires compiling with /utf-8\");\n\ntemplate <typename T> constexpr auto narrow(T*) -> char* { return nullptr; }\nconstexpr FMT_ALWAYS_INLINE auto narrow(const char* s) -> const char* {\n  return s;\n}\n\ntemplate <typename Char>\nFMT_CONSTEXPR auto compare(const Char* s1, const Char* s2, size_t n) -> int {\n  if (!is_constant_evaluated() && sizeof(Char) == 1) return memcmp(s1, s2, n);\n  for (; n != 0; ++s1, ++s2, --n) {\n    if (*s1 < *s2) return -1;\n    if (*s1 > *s2) return 1;\n  }\n  return 0;\n}\n\nnamespace adl {\nusing namespace std;\n\ntemplate <typename Container>\nauto invoke_back_inserter()\n    -> decltype(back_inserter(std::declval<Container&>()));\n}  // namespace adl\n\ntemplate <typename It, typename Enable = std::true_type>\nstruct is_back_insert_iterator : std::false_type {};\n\ntemplate <typename It>\nstruct is_back_insert_iterator<\n    It, bool_constant<std::is_same<\n            decltype(adl::invoke_back_inserter<typename It::container_type>()),\n            It>::value>> : std::true_type {};\n\n// Extracts a reference to the container from *insert_iterator.\ntemplate <typename OutputIt>\ninline FMT_CONSTEXPR20 auto get_container(OutputIt it) ->\n    typename OutputIt::container_type& {\n  struct accessor : OutputIt {\n    FMT_CONSTEXPR20 accessor(OutputIt base) : OutputIt(base) {}\n    using OutputIt::container;\n  };\n  return *accessor(it).container;\n}\n}  // namespace detail\n\n// Parsing-related public API and forward declarations.\nFMT_BEGIN_EXPORT\n\n/**\n * An implementation of `std::basic_string_view` for pre-C++17. It provides a\n * subset of the API. `fmt::basic_string_view` is used for format strings even\n * if `std::basic_string_view` is available to prevent issues when a library is\n * compiled with a different `-std` option than the client code (which is not\n * recommended).\n */\ntemplate <typename Char> class basic_string_view {\n private:\n  const Char* data_;\n  size_t size_;\n\n public:\n  using value_type = Char;\n  using iterator = const Char*;\n\n  constexpr basic_string_view() noexcept : data_(nullptr), size_(0) {}\n\n  /// Constructs a string view object from a C string and a size.\n  constexpr basic_string_view(const Char* s, size_t count) noexcept\n      : data_(s), size_(count) {}\n\n  constexpr basic_string_view(nullptr_t) = delete;\n\n  /// Constructs a string view object from a C string.\n#if FMT_GCC_VERSION\n  FMT_ALWAYS_INLINE\n#endif\n  FMT_CONSTEXPR20 basic_string_view(const Char* s) : data_(s) {\n#if FMT_HAS_BUILTIN(__builtin_strlen) || FMT_GCC_VERSION || FMT_CLANG_VERSION\n    if (std::is_same<Char, char>::value && !detail::is_constant_evaluated()) {\n      size_ = __builtin_strlen(detail::narrow(s));  // strlen is not constexpr.\n      return;\n    }\n#endif\n    size_t len = 0;\n    while (*s++) ++len;\n    size_ = len;\n  }\n\n  /// Constructs a string view from a `std::basic_string` or a\n  /// `std::basic_string_view` object.\n  template <typename S,\n            FMT_ENABLE_IF(detail::is_std_string_like<S>::value&& std::is_same<\n                          typename S::value_type, Char>::value)>\n  FMT_CONSTEXPR basic_string_view(const S& s) noexcept\n      : data_(s.data()), size_(s.size()) {}\n\n  /// Returns a pointer to the string data.\n  constexpr auto data() const noexcept -> const Char* { return data_; }\n\n  /// Returns the string size.\n  constexpr auto size() const noexcept -> size_t { return size_; }\n\n  constexpr auto begin() const noexcept -> iterator { return data_; }\n  constexpr auto end() const noexcept -> iterator { return data_ + size_; }\n\n  constexpr auto operator[](size_t pos) const noexcept -> const Char& {\n    return data_[pos];\n  }\n\n  FMT_CONSTEXPR void remove_prefix(size_t n) noexcept {\n    data_ += n;\n    size_ -= n;\n  }\n\n  FMT_CONSTEXPR auto starts_with(basic_string_view<Char> sv) const noexcept\n      -> bool {\n    return size_ >= sv.size_ && detail::compare(data_, sv.data_, sv.size_) == 0;\n  }\n  FMT_CONSTEXPR auto starts_with(Char c) const noexcept -> bool {\n    return size_ >= 1 && *data_ == c;\n  }\n  FMT_CONSTEXPR auto starts_with(const Char* s) const -> bool {\n    return starts_with(basic_string_view<Char>(s));\n  }\n\n  FMT_CONSTEXPR auto compare(basic_string_view other) const -> int {\n    int result =\n        detail::compare(data_, other.data_, min_of(size_, other.size_));\n    if (result != 0) return result;\n    return size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);\n  }\n\n  FMT_CONSTEXPR friend auto operator==(basic_string_view lhs,\n                                       basic_string_view rhs) -> bool {\n    return lhs.compare(rhs) == 0;\n  }\n  friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool {\n    return lhs.compare(rhs) != 0;\n  }\n  friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool {\n    return lhs.compare(rhs) < 0;\n  }\n  friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool {\n    return lhs.compare(rhs) <= 0;\n  }\n  friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool {\n    return lhs.compare(rhs) > 0;\n  }\n  friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool {\n    return lhs.compare(rhs) >= 0;\n  }\n};\n\nusing string_view = basic_string_view<char>;\n\ntemplate <typename T> class basic_appender;\nusing appender = basic_appender<char>;\n\n// Checks whether T is a container with contiguous storage.\ntemplate <typename T> struct is_contiguous : std::false_type {};\n\nclass context;\ntemplate <typename OutputIt, typename Char> class generic_context;\ntemplate <typename Char> class parse_context;\n\n// Longer aliases for C++20 compatibility.\ntemplate <typename Char> using basic_format_parse_context = parse_context<Char>;\nusing format_parse_context = parse_context<char>;\ntemplate <typename OutputIt, typename Char>\nusing basic_format_context =\n    conditional_t<std::is_same<OutputIt, appender>::value, context,\n                  generic_context<OutputIt, Char>>;\nusing format_context = context;\n\ntemplate <typename Char>\nusing buffered_context =\n    conditional_t<std::is_same<Char, char>::value, context,\n                  generic_context<basic_appender<Char>, Char>>;\n\ntemplate <typename Context> class basic_format_arg;\ntemplate <typename Context> class basic_format_args;\n\n// A separate type would result in shorter symbols but break ABI compatibility\n// between clang and gcc on ARM (#1919).\nusing format_args = basic_format_args<context>;\n\n// A formatter for objects of type T.\ntemplate <typename T, typename Char = char, typename Enable = void>\nstruct formatter {\n  // A deleted default constructor indicates a disabled formatter.\n  formatter() = delete;\n};\n\n/// Reports a format error at compile time or, via a `format_error` exception,\n/// at runtime.\n// This function is intentionally not constexpr to give a compile-time error.\nFMT_NORETURN FMT_API void report_error(const char* message);\n\nenum class presentation_type : unsigned char {\n  // Common specifiers:\n  none = 0,\n  debug = 1,   // '?'\n  string = 2,  // 's' (string, bool)\n\n  // Integral, bool and character specifiers:\n  dec = 3,  // 'd'\n  hex,      // 'x' or 'X'\n  oct,      // 'o'\n  bin,      // 'b' or 'B'\n  chr,      // 'c'\n\n  // String and pointer specifiers:\n  pointer = 3,  // 'p'\n\n  // Floating-point specifiers:\n  exp = 1,  // 'e' or 'E' (1 since there is no FP debug presentation)\n  fixed,    // 'f' or 'F'\n  general,  // 'g' or 'G'\n  hexfloat  // 'a' or 'A'\n};\n\nenum class align { none, left, right, center, numeric };\nenum class sign { none, minus, plus, space };\nenum class arg_id_kind { none, index, name };\n\n// Basic format specifiers for built-in and string types.\nclass basic_specs {\n private:\n  // Data is arranged as follows:\n  //\n  //  0                   1                   2                   3\n  //  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n  // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n  // |type |align| w | p | s |u|#|L|  f  |          unused           |\n  // +-----+-----+---+---+---+-+-+-+-----+---------------------------+\n  //\n  //   w - dynamic width info\n  //   p - dynamic precision info\n  //   s - sign\n  //   u - uppercase (e.g. 'X' for 'x')\n  //   # - alternate form ('#')\n  //   L - localized\n  //   f - fill size\n  //\n  // Bitfields are not used because of compiler bugs such as gcc bug 61414.\n  enum : unsigned {\n    type_mask = 0x00007,\n    align_mask = 0x00038,\n    width_mask = 0x000C0,\n    precision_mask = 0x00300,\n    sign_mask = 0x00C00,\n    uppercase_mask = 0x01000,\n    alternate_mask = 0x02000,\n    localized_mask = 0x04000,\n    fill_size_mask = 0x38000,\n\n    align_shift = 3,\n    width_shift = 6,\n    precision_shift = 8,\n    sign_shift = 10,\n    fill_size_shift = 15,\n\n    max_fill_size = 4\n  };\n\n  unsigned data_ = 1 << fill_size_shift;\n  static_assert(sizeof(basic_specs::data_) * CHAR_BIT >= 18, \"\");\n\n  // Character (code unit) type is erased to prevent template bloat.\n  char fill_data_[max_fill_size] = {' '};\n\n  FMT_CONSTEXPR void set_fill_size(size_t size) {\n    data_ = (data_ & ~fill_size_mask) |\n            (static_cast<unsigned>(size) << fill_size_shift);\n  }\n\n public:\n  constexpr auto type() const -> presentation_type {\n    return static_cast<presentation_type>(data_ & type_mask);\n  }\n  FMT_CONSTEXPR void set_type(presentation_type t) {\n    data_ = (data_ & ~type_mask) | static_cast<unsigned>(t);\n  }\n\n  constexpr auto align() const -> align {\n    return static_cast<fmt::align>((data_ & align_mask) >> align_shift);\n  }\n  FMT_CONSTEXPR void set_align(fmt::align a) {\n    data_ = (data_ & ~align_mask) | (static_cast<unsigned>(a) << align_shift);\n  }\n\n  constexpr auto dynamic_width() const -> arg_id_kind {\n    return static_cast<arg_id_kind>((data_ & width_mask) >> width_shift);\n  }\n  FMT_CONSTEXPR void set_dynamic_width(arg_id_kind w) {\n    data_ = (data_ & ~width_mask) | (static_cast<unsigned>(w) << width_shift);\n  }\n\n  FMT_CONSTEXPR auto dynamic_precision() const -> arg_id_kind {\n    return static_cast<arg_id_kind>((data_ & precision_mask) >>\n                                    precision_shift);\n  }\n  FMT_CONSTEXPR void set_dynamic_precision(arg_id_kind p) {\n    data_ = (data_ & ~precision_mask) |\n            (static_cast<unsigned>(p) << precision_shift);\n  }\n\n  constexpr auto dynamic() const -> bool {\n    return (data_ & (width_mask | precision_mask)) != 0;\n  }\n\n  constexpr auto sign() const -> sign {\n    return static_cast<fmt::sign>((data_ & sign_mask) >> sign_shift);\n  }\n  FMT_CONSTEXPR void set_sign(fmt::sign s) {\n    data_ = (data_ & ~sign_mask) | (static_cast<unsigned>(s) << sign_shift);\n  }\n\n  constexpr auto upper() const -> bool { return (data_ & uppercase_mask) != 0; }\n  FMT_CONSTEXPR void set_upper() { data_ |= uppercase_mask; }\n\n  constexpr auto alt() const -> bool { return (data_ & alternate_mask) != 0; }\n  FMT_CONSTEXPR void set_alt() { data_ |= alternate_mask; }\n  FMT_CONSTEXPR void clear_alt() { data_ &= ~alternate_mask; }\n\n  constexpr auto localized() const -> bool {\n    return (data_ & localized_mask) != 0;\n  }\n  FMT_CONSTEXPR void set_localized() { data_ |= localized_mask; }\n\n  constexpr auto fill_size() const -> size_t {\n    return (data_ & fill_size_mask) >> fill_size_shift;\n  }\n\n  template <typename Char, FMT_ENABLE_IF(std::is_same<Char, char>::value)>\n  constexpr auto fill() const -> const Char* {\n    return fill_data_;\n  }\n  template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>\n  constexpr auto fill() const -> const Char* {\n    return nullptr;\n  }\n\n  template <typename Char> constexpr auto fill_unit() const -> Char {\n    using uchar = unsigned char;\n    return static_cast<Char>(static_cast<uchar>(fill_data_[0]) |\n                             (static_cast<uchar>(fill_data_[1]) << 8) |\n                             (static_cast<uchar>(fill_data_[2]) << 16));\n  }\n\n  FMT_CONSTEXPR void set_fill(char c) {\n    fill_data_[0] = c;\n    set_fill_size(1);\n  }\n\n  template <typename Char>\n  FMT_CONSTEXPR void set_fill(basic_string_view<Char> s) {\n    auto size = s.size();\n    set_fill_size(size);\n    if (size == 1) {\n      unsigned uchar = static_cast<detail::unsigned_char<Char>>(s[0]);\n      fill_data_[0] = static_cast<char>(uchar);\n      fill_data_[1] = static_cast<char>(uchar >> 8);\n      fill_data_[2] = static_cast<char>(uchar >> 16);\n      return;\n    }\n    FMT_ASSERT(size <= max_fill_size, \"invalid fill\");\n    for (size_t i = 0; i < size; ++i)\n      fill_data_[i & 3] = static_cast<char>(s[i]);\n  }\n\n  FMT_CONSTEXPR void copy_fill_from(const basic_specs& specs) {\n    set_fill_size(specs.fill_size());\n    for (size_t i = 0; i < max_fill_size; ++i)\n      fill_data_[i] = specs.fill_data_[i];\n  }\n};\n\n// Format specifiers for built-in and string types.\nstruct format_specs : basic_specs {\n  int width;\n  int precision;\n\n  constexpr format_specs() : width(0), precision(-1) {}\n};\n\n/**\n * Parsing context consisting of a format string range being parsed and an\n * argument counter for automatic indexing.\n */\ntemplate <typename Char = char> class parse_context {\n private:\n  basic_string_view<Char> fmt_;\n  int next_arg_id_;\n\n  enum { use_constexpr_cast = !FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200 };\n\n  FMT_CONSTEXPR void do_check_arg_id(int arg_id);\n\n public:\n  using char_type = Char;\n  using iterator = const Char*;\n\n  constexpr explicit parse_context(basic_string_view<Char> fmt,\n                                   int next_arg_id = 0)\n      : fmt_(fmt), next_arg_id_(next_arg_id) {}\n\n  /// Returns an iterator to the beginning of the format string range being\n  /// parsed.\n  constexpr auto begin() const noexcept -> iterator { return fmt_.begin(); }\n\n  /// Returns an iterator past the end of the format string range being parsed.\n  constexpr auto end() const noexcept -> iterator { return fmt_.end(); }\n\n  /// Advances the begin iterator to `it`.\n  FMT_CONSTEXPR void advance_to(iterator it) {\n    fmt_.remove_prefix(detail::to_unsigned(it - begin()));\n  }\n\n  /// Reports an error if using the manual argument indexing; otherwise returns\n  /// the next argument index and switches to the automatic indexing.\n  FMT_CONSTEXPR auto next_arg_id() -> int {\n    if (next_arg_id_ < 0) {\n      report_error(\"cannot switch from manual to automatic argument indexing\");\n      return 0;\n    }\n    int id = next_arg_id_++;\n    do_check_arg_id(id);\n    return id;\n  }\n\n  /// Reports an error if using the automatic argument indexing; otherwise\n  /// switches to the manual indexing.\n  FMT_CONSTEXPR void check_arg_id(int id) {\n    if (next_arg_id_ > 0) {\n      report_error(\"cannot switch from automatic to manual argument indexing\");\n      return;\n    }\n    next_arg_id_ = -1;\n    do_check_arg_id(id);\n  }\n  FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {\n    next_arg_id_ = -1;\n  }\n  FMT_CONSTEXPR void check_dynamic_spec(int arg_id);\n};\n\n#ifndef FMT_USE_LOCALE\n#  define FMT_USE_LOCALE (FMT_OPTIMIZE_SIZE <= 1)\n#endif\n\n// A type-erased reference to std::locale to avoid the heavy <locale> include.\nclass locale_ref {\n#if FMT_USE_LOCALE\n private:\n  const void* locale_;  // A type-erased pointer to std::locale.\n\n public:\n  constexpr locale_ref() : locale_(nullptr) {}\n\n  template <typename Locale, FMT_ENABLE_IF(sizeof(Locale::collate) != 0)>\n  locale_ref(const Locale& loc);\n\n  inline explicit operator bool() const noexcept { return locale_ != nullptr; }\n#endif  // FMT_USE_LOCALE\n\n public:\n  template <typename Locale> auto get() const -> Locale;\n};\n\nFMT_END_EXPORT\n\nnamespace detail {\n\n// Specifies if `T` is a code unit type.\ntemplate <typename T> struct is_code_unit : std::false_type {};\ntemplate <> struct is_code_unit<char> : std::true_type {};\ntemplate <> struct is_code_unit<wchar_t> : std::true_type {};\ntemplate <> struct is_code_unit<char16_t> : std::true_type {};\ntemplate <> struct is_code_unit<char32_t> : std::true_type {};\n#ifdef __cpp_char8_t\ntemplate <> struct is_code_unit<char8_t> : bool_constant<is_utf8_enabled> {};\n#endif\n\n// Constructs fmt::basic_string_view<Char> from types implicitly convertible\n// to it, deducing Char. Explicitly convertible types such as the ones returned\n// from FMT_STRING are intentionally excluded.\ntemplate <typename Char, FMT_ENABLE_IF(is_code_unit<Char>::value)>\nconstexpr auto to_string_view(const Char* s) -> basic_string_view<Char> {\n  return s;\n}\ntemplate <typename T, FMT_ENABLE_IF(is_std_string_like<T>::value)>\nconstexpr auto to_string_view(const T& s)\n    -> basic_string_view<typename T::value_type> {\n  return s;\n}\ntemplate <typename Char>\nconstexpr auto to_string_view(basic_string_view<Char> s)\n    -> basic_string_view<Char> {\n  return s;\n}\n\ntemplate <typename T, typename Enable = void>\nstruct has_to_string_view : std::false_type {};\n// detail:: is intentional since to_string_view is not an extension point.\ntemplate <typename T>\nstruct has_to_string_view<\n    T, void_t<decltype(detail::to_string_view(std::declval<T>()))>>\n    : std::true_type {};\n\n/// String's character (code unit) type. detail:: is intentional to prevent ADL.\ntemplate <typename S,\n          typename V = decltype(detail::to_string_view(std::declval<S>()))>\nusing char_t = typename V::value_type;\n\nenum class type {\n  none_type,\n  // Integer types should go first,\n  int_type,\n  uint_type,\n  long_long_type,\n  ulong_long_type,\n  int128_type,\n  uint128_type,\n  bool_type,\n  char_type,\n  last_integer_type = char_type,\n  // followed by floating-point types.\n  float_type,\n  double_type,\n  long_double_type,\n  last_numeric_type = long_double_type,\n  cstring_type,\n  string_type,\n  pointer_type,\n  custom_type\n};\n\n// Maps core type T to the corresponding type enum constant.\ntemplate <typename T, typename Char>\nstruct type_constant : std::integral_constant<type, type::custom_type> {};\n\n#define FMT_TYPE_CONSTANT(Type, constant) \\\n  template <typename Char>                \\\n  struct type_constant<Type, Char>        \\\n      : std::integral_constant<type, type::constant> {}\n\nFMT_TYPE_CONSTANT(int, int_type);\nFMT_TYPE_CONSTANT(unsigned, uint_type);\nFMT_TYPE_CONSTANT(long long, long_long_type);\nFMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);\nFMT_TYPE_CONSTANT(int128_opt, int128_type);\nFMT_TYPE_CONSTANT(uint128_opt, uint128_type);\nFMT_TYPE_CONSTANT(bool, bool_type);\nFMT_TYPE_CONSTANT(Char, char_type);\nFMT_TYPE_CONSTANT(float, float_type);\nFMT_TYPE_CONSTANT(double, double_type);\nFMT_TYPE_CONSTANT(long double, long_double_type);\nFMT_TYPE_CONSTANT(const Char*, cstring_type);\nFMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);\nFMT_TYPE_CONSTANT(const void*, pointer_type);\n\nconstexpr auto is_integral_type(type t) -> bool {\n  return t > type::none_type && t <= type::last_integer_type;\n}\nconstexpr auto is_arithmetic_type(type t) -> bool {\n  return t > type::none_type && t <= type::last_numeric_type;\n}\n\nconstexpr auto set(type rhs) -> int { return 1 << static_cast<int>(rhs); }\nconstexpr auto in(type t, int set) -> bool {\n  return ((set >> static_cast<int>(t)) & 1) != 0;\n}\n\n// Bitsets of types.\nenum {\n  sint_set =\n      set(type::int_type) | set(type::long_long_type) | set(type::int128_type),\n  uint_set = set(type::uint_type) | set(type::ulong_long_type) |\n             set(type::uint128_type),\n  bool_set = set(type::bool_type),\n  char_set = set(type::char_type),\n  float_set = set(type::float_type) | set(type::double_type) |\n              set(type::long_double_type),\n  string_set = set(type::string_type),\n  cstring_set = set(type::cstring_type),\n  pointer_set = set(type::pointer_type)\n};\n\nstruct view {};\n\ntemplate <typename T, typename Enable = std::true_type>\nstruct is_view : std::false_type {};\ntemplate <typename T>\nstruct is_view<T, bool_constant<sizeof(T) != 0>> : std::is_base_of<view, T> {};\n\ntemplate <typename Char, typename T> struct named_arg;\ntemplate <typename T> struct is_named_arg : std::false_type {};\ntemplate <typename T> struct is_static_named_arg : std::false_type {};\n\ntemplate <typename Char, typename T>\nstruct is_named_arg<named_arg<Char, T>> : std::true_type {};\n\ntemplate <typename Char, typename T> struct named_arg : view {\n  const Char* name;\n  const T& value;\n\n  named_arg(const Char* n, const T& v) : name(n), value(v) {}\n  static_assert(!is_named_arg<T>::value, \"nested named arguments\");\n};\n\ntemplate <bool B = false> constexpr auto count() -> int { return B ? 1 : 0; }\ntemplate <bool B1, bool B2, bool... Tail> constexpr auto count() -> int {\n  return (B1 ? 1 : 0) + count<B2, Tail...>();\n}\n\ntemplate <typename... T> constexpr auto count_named_args() -> int {\n  return count<is_named_arg<T>::value...>();\n}\ntemplate <typename... T> constexpr auto count_static_named_args() -> int {\n  return count<is_static_named_arg<T>::value...>();\n}\n\ntemplate <typename Char> struct named_arg_info {\n  const Char* name;\n  int id;\n};\n\n// named_args is non-const to suppress a bogus -Wmaybe-uninitialized in gcc 13.\ntemplate <typename Char>\nFMT_CONSTEXPR void check_for_duplicate(named_arg_info<Char>* named_args,\n                                       int named_arg_index,\n                                       basic_string_view<Char> arg_name) {\n  for (int i = 0; i < named_arg_index; ++i) {\n    if (named_args[i].name == arg_name) report_error(\"duplicate named arg\");\n  }\n}\n\ntemplate <typename Char, typename T, FMT_ENABLE_IF(!is_named_arg<T>::value)>\nvoid init_named_arg(named_arg_info<Char>*, int& arg_index, int&, const T&) {\n  ++arg_index;\n}\ntemplate <typename Char, typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>\nvoid init_named_arg(named_arg_info<Char>* named_args, int& arg_index,\n                    int& named_arg_index, const T& arg) {\n  check_for_duplicate<Char>(named_args, named_arg_index, arg.name);\n  named_args[named_arg_index++] = {arg.name, arg_index++};\n}\n\ntemplate <typename T, typename Char,\n          FMT_ENABLE_IF(!is_static_named_arg<T>::value)>\nFMT_CONSTEXPR void init_static_named_arg(named_arg_info<Char>*, int& arg_index,\n                                         int&) {\n  ++arg_index;\n}\ntemplate <typename T, typename Char,\n          FMT_ENABLE_IF(is_static_named_arg<T>::value)>\nFMT_CONSTEXPR void init_static_named_arg(named_arg_info<Char>* named_args,\n                                         int& arg_index, int& named_arg_index) {\n  check_for_duplicate<Char>(named_args, named_arg_index, T::name);\n  named_args[named_arg_index++] = {T::name, arg_index++};\n}\n\n// To minimize the number of types we need to deal with, long is translated\n// either to int or to long long depending on its size.\nenum { long_short = sizeof(long) == sizeof(int) && FMT_BUILTIN_TYPES };\nusing long_type = conditional_t<long_short, int, long long>;\nusing ulong_type = conditional_t<long_short, unsigned, unsigned long long>;\n\ntemplate <typename T>\nusing format_as_result =\n    remove_cvref_t<decltype(format_as(std::declval<const T&>()))>;\ntemplate <typename T>\nusing format_as_member_result =\n    remove_cvref_t<decltype(formatter<T>::format_as(std::declval<const T&>()))>;\n\ntemplate <typename T, typename Enable = std::true_type>\nstruct use_format_as : std::false_type {};\n// format_as member is only used to avoid injection into the std namespace.\ntemplate <typename T, typename Enable = std::true_type>\nstruct use_format_as_member : std::false_type {};\n\n// Only map owning types because mapping views can be unsafe.\ntemplate <typename T>\nstruct use_format_as<\n    T, bool_constant<std::is_arithmetic<format_as_result<T>>::value>>\n    : std::true_type {};\ntemplate <typename T>\nstruct use_format_as_member<\n    T, bool_constant<std::is_arithmetic<format_as_member_result<T>>::value>>\n    : std::true_type {};\n\ntemplate <typename T, typename U = remove_const_t<T>>\nusing use_formatter =\n    bool_constant<(std::is_class<T>::value || std::is_enum<T>::value ||\n                   std::is_union<T>::value || std::is_array<T>::value) &&\n                  !has_to_string_view<T>::value && !is_named_arg<T>::value &&\n                  !use_format_as<T>::value && !use_format_as_member<U>::value>;\n\ntemplate <typename Char, typename T, typename U = remove_const_t<T>>\nauto has_formatter_impl(T* p, buffered_context<Char>* ctx = nullptr)\n    -> decltype(formatter<U, Char>().format(*p, *ctx), std::true_type());\ntemplate <typename Char> auto has_formatter_impl(...) -> std::false_type;\n\n// T can be const-qualified to check if it is const-formattable.\ntemplate <typename T, typename Char> constexpr auto has_formatter() -> bool {\n  return decltype(has_formatter_impl<Char>(static_cast<T*>(nullptr)))::value;\n}\n\n// Maps formatting argument types to natively supported types or user-defined\n// types with formatters. Returns void on errors to be SFINAE-friendly.\ntemplate <typename Char> struct type_mapper {\n  static auto map(signed char) -> int;\n  static auto map(unsigned char) -> unsigned;\n  static auto map(short) -> int;\n  static auto map(unsigned short) -> unsigned;\n  static auto map(int) -> int;\n  static auto map(unsigned) -> unsigned;\n  static auto map(long) -> long_type;\n  static auto map(unsigned long) -> ulong_type;\n  static auto map(long long) -> long long;\n  static auto map(unsigned long long) -> unsigned long long;\n  static auto map(int128_opt) -> int128_opt;\n  static auto map(uint128_opt) -> uint128_opt;\n  static auto map(bool) -> bool;\n\n  template <int N>\n  static auto map(bitint<N>) -> conditional_t<N <= 64, long long, void>;\n  template <int N>\n  static auto map(ubitint<N>)\n      -> conditional_t<N <= 64, unsigned long long, void>;\n\n  template <typename T, FMT_ENABLE_IF(is_code_unit<T>::value)>\n  static auto map(T) -> conditional_t<\n      std::is_same<T, char>::value || std::is_same<T, Char>::value, Char, void>;\n\n  static auto map(float) -> float;\n  static auto map(double) -> double;\n  static auto map(long double) -> long double;\n\n  static auto map(Char*) -> const Char*;\n  static auto map(const Char*) -> const Char*;\n  template <typename T, typename C = char_t<T>,\n            FMT_ENABLE_IF(!std::is_pointer<T>::value)>\n  static auto map(const T&) -> conditional_t<std::is_same<C, Char>::value,\n                                             basic_string_view<C>, void>;\n\n  static auto map(void*) -> const void*;\n  static auto map(const void*) -> const void*;\n  static auto map(volatile void*) -> const void*;\n  static auto map(const volatile void*) -> const void*;\n  static auto map(nullptr_t) -> const void*;\n  template <typename T, FMT_ENABLE_IF(std::is_pointer<T>::value ||\n                                      std::is_member_pointer<T>::value)>\n  static auto map(const T&) -> void;\n\n  template <typename T, FMT_ENABLE_IF(use_format_as<T>::value)>\n  static auto map(const T& x) -> decltype(map(format_as(x)));\n  template <typename T, FMT_ENABLE_IF(use_format_as_member<T>::value)>\n  static auto map(const T& x) -> decltype(map(formatter<T>::format_as(x)));\n\n  template <typename T, FMT_ENABLE_IF(use_formatter<T>::value)>\n  static auto map(T&) -> conditional_t<has_formatter<T, Char>(), T&, void>;\n\n  template <typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>\n  static auto map(const T& named_arg) -> decltype(map(named_arg.value));\n};\n\n// detail:: is used to workaround a bug in MSVC 2017.\ntemplate <typename T, typename Char>\nusing mapped_t = decltype(detail::type_mapper<Char>::map(std::declval<T&>()));\n\n// A type constant after applying type_mapper.\ntemplate <typename T, typename Char = char>\nusing mapped_type_constant = type_constant<mapped_t<T, Char>, Char>;\n\ntemplate <typename T, typename Context,\n          type TYPE =\n              mapped_type_constant<T, typename Context::char_type>::value>\nusing stored_type_constant = std::integral_constant<\n    type, Context::builtin_types || TYPE == type::int_type ? TYPE\n                                                           : type::custom_type>;\n// A parse context with extra data used only in compile-time checks.\ntemplate <typename Char>\nclass compile_parse_context : public parse_context<Char> {\n private:\n  int num_args_;\n  const type* types_;\n  using base = parse_context<Char>;\n\n public:\n  FMT_CONSTEXPR explicit compile_parse_context(basic_string_view<Char> fmt,\n                                               int num_args, const type* types,\n                                               int next_arg_id = 0)\n      : base(fmt, next_arg_id), num_args_(num_args), types_(types) {}\n\n  constexpr auto num_args() const -> int { return num_args_; }\n  constexpr auto arg_type(int id) const -> type { return types_[id]; }\n\n  FMT_CONSTEXPR auto next_arg_id() -> int {\n    int id = base::next_arg_id();\n    if (id >= num_args_) report_error(\"argument not found\");\n    return id;\n  }\n\n  FMT_CONSTEXPR void check_arg_id(int id) {\n    base::check_arg_id(id);\n    if (id >= num_args_) report_error(\"argument not found\");\n  }\n  using base::check_arg_id;\n\n  FMT_CONSTEXPR void check_dynamic_spec(int arg_id) {\n    ignore_unused(arg_id);\n    if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id]))\n      report_error(\"width/precision is not integer\");\n  }\n};\n\n// An argument reference.\ntemplate <typename Char> union arg_ref {\n  FMT_CONSTEXPR arg_ref(int idx = 0) : index(idx) {}\n  FMT_CONSTEXPR arg_ref(basic_string_view<Char> n) : name(n) {}\n\n  int index;\n  basic_string_view<Char> name;\n};\n\n// Format specifiers with width and precision resolved at formatting rather\n// than parsing time to allow reusing the same parsed specifiers with\n// different sets of arguments (precompilation of format strings).\ntemplate <typename Char = char> struct dynamic_format_specs : format_specs {\n  arg_ref<Char> width_ref;\n  arg_ref<Char> precision_ref;\n};\n\n// Converts a character to ASCII. Returns '\\0' on conversion failure.\ntemplate <typename Char, FMT_ENABLE_IF(std::is_integral<Char>::value)>\nconstexpr auto to_ascii(Char c) -> char {\n  return c <= 0xff ? static_cast<char>(c) : '\\0';\n}\n\n// Returns the number of code units in a code point or 1 on error.\ntemplate <typename Char>\nFMT_CONSTEXPR auto code_point_length(const Char* begin) -> int {\n  if (const_check(sizeof(Char) != 1)) return 1;\n  auto c = static_cast<unsigned char>(*begin);\n  return static_cast<int>((0x3a55000000000000ull >> (2 * (c >> 3))) & 3) + 1;\n}\n\n// Parses the range [begin, end) as an unsigned integer. This function assumes\n// that the range is non-empty and the first character is a digit.\ntemplate <typename Char>\nFMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end,\n                                         int error_value) noexcept -> int {\n  FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', \"\");\n  unsigned value = 0, prev = 0;\n  auto p = begin;\n  do {\n    prev = value;\n    value = value * 10 + unsigned(*p - '0');\n    ++p;\n  } while (p != end && '0' <= *p && *p <= '9');\n  auto num_digits = p - begin;\n  begin = p;\n  int digits10 = static_cast<int>(sizeof(int) * CHAR_BIT * 3 / 10);\n  if (num_digits <= digits10) return static_cast<int>(value);\n  // Check for overflow.\n  unsigned max = INT_MAX;\n  return num_digits == digits10 + 1 &&\n                 prev * 10ull + unsigned(p[-1] - '0') <= max\n             ? static_cast<int>(value)\n             : error_value;\n}\n\nFMT_CONSTEXPR inline auto parse_align(char c) -> align {\n  switch (c) {\n  case '<': return align::left;\n  case '>': return align::right;\n  case '^': return align::center;\n  }\n  return align::none;\n}\n\ntemplate <typename Char> constexpr auto is_name_start(Char c) -> bool {\n  return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_';\n}\n\ntemplate <typename Char, typename Handler>\nFMT_CONSTEXPR auto parse_arg_id(const Char* begin, const Char* end,\n                                Handler&& handler) -> const Char* {\n  Char c = *begin;\n  if (c >= '0' && c <= '9') {\n    int index = 0;\n    if (c != '0')\n      index = parse_nonnegative_int(begin, end, INT_MAX);\n    else\n      ++begin;\n    if (begin == end || (*begin != '}' && *begin != ':'))\n      report_error(\"invalid format string\");\n    else\n      handler.on_index(index);\n    return begin;\n  }\n  if (FMT_OPTIMIZE_SIZE > 1 || !is_name_start(c)) {\n    report_error(\"invalid format string\");\n    return begin;\n  }\n  auto it = begin;\n  do {\n    ++it;\n  } while (it != end && (is_name_start(*it) || ('0' <= *it && *it <= '9')));\n  handler.on_name({begin, to_unsigned(it - begin)});\n  return it;\n}\n\ntemplate <typename Char> struct dynamic_spec_handler {\n  parse_context<Char>& ctx;\n  arg_ref<Char>& ref;\n  arg_id_kind& kind;\n\n  FMT_CONSTEXPR void on_index(int id) {\n    ref = id;\n    kind = arg_id_kind::index;\n    ctx.check_arg_id(id);\n    ctx.check_dynamic_spec(id);\n  }\n  FMT_CONSTEXPR void on_name(basic_string_view<Char> id) {\n    ref = id;\n    kind = arg_id_kind::name;\n    ctx.check_arg_id(id);\n  }\n};\n\ntemplate <typename Char> struct parse_dynamic_spec_result {\n  const Char* end;\n  arg_id_kind kind;\n};\n\n// Parses integer | \"{\" [arg_id] \"}\".\ntemplate <typename Char>\nFMT_CONSTEXPR auto parse_dynamic_spec(const Char* begin, const Char* end,\n                                      int& value, arg_ref<Char>& ref,\n                                      parse_context<Char>& ctx)\n    -> parse_dynamic_spec_result<Char> {\n  FMT_ASSERT(begin != end, \"\");\n  auto kind = arg_id_kind::none;\n  if ('0' <= *begin && *begin <= '9') {\n    int val = parse_nonnegative_int(begin, end, -1);\n    if (val == -1) report_error(\"number is too big\");\n    value = val;\n  } else {\n    if (*begin == '{') {\n      ++begin;\n      if (begin != end) {\n        Char c = *begin;\n        if (c == '}' || c == ':') {\n          int id = ctx.next_arg_id();\n          ref = id;\n          kind = arg_id_kind::index;\n          ctx.check_dynamic_spec(id);\n        } else {\n          begin = parse_arg_id(begin, end,\n                               dynamic_spec_handler<Char>{ctx, ref, kind});\n        }\n      }\n      if (begin != end && *begin == '}') return {++begin, kind};\n    }\n    report_error(\"invalid format string\");\n  }\n  return {begin, kind};\n}\n\ntemplate <typename Char>\nFMT_CONSTEXPR auto parse_width(const Char* begin, const Char* end,\n                               format_specs& specs, arg_ref<Char>& width_ref,\n                               parse_context<Char>& ctx) -> const Char* {\n  auto result = parse_dynamic_spec(begin, end, specs.width, width_ref, ctx);\n  specs.set_dynamic_width(result.kind);\n  return result.end;\n}\n\ntemplate <typename Char>\nFMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end,\n                                   format_specs& specs,\n                                   arg_ref<Char>& precision_ref,\n                                   parse_context<Char>& ctx) -> const Char* {\n  ++begin;\n  if (begin == end) {\n    report_error(\"invalid precision\");\n    return begin;\n  }\n  auto result =\n      parse_dynamic_spec(begin, end, specs.precision, precision_ref, ctx);\n  specs.set_dynamic_precision(result.kind);\n  return result.end;\n}\n\nenum class state { start, align, sign, hash, zero, width, precision, locale };\n\n// Parses standard format specifiers.\ntemplate <typename Char>\nFMT_CONSTEXPR auto parse_format_specs(const Char* begin, const Char* end,\n                                      dynamic_format_specs<Char>& specs,\n                                      parse_context<Char>& ctx, type arg_type)\n    -> const Char* {\n  auto c = '\\0';\n  if (end - begin > 1) {\n    auto next = to_ascii(begin[1]);\n    c = parse_align(next) == align::none ? to_ascii(*begin) : '\\0';\n  } else {\n    if (begin == end) return begin;\n    c = to_ascii(*begin);\n  }\n\n  struct {\n    state current_state = state::start;\n    FMT_CONSTEXPR void operator()(state s, bool valid = true) {\n      if (current_state >= s || !valid)\n        report_error(\"invalid format specifier\");\n      current_state = s;\n    }\n  } enter_state;\n\n  using pres = presentation_type;\n  constexpr auto integral_set = sint_set | uint_set | bool_set | char_set;\n  struct {\n    const Char*& begin;\n    format_specs& specs;\n    type arg_type;\n\n    FMT_CONSTEXPR auto operator()(pres pres_type, int set) -> const Char* {\n      if (!in(arg_type, set)) report_error(\"invalid format specifier\");\n      specs.set_type(pres_type);\n      return begin + 1;\n    }\n  } parse_presentation_type{begin, specs, arg_type};\n\n  for (;;) {\n    switch (c) {\n    case '<':\n    case '>':\n    case '^':\n      enter_state(state::align);\n      specs.set_align(parse_align(c));\n      ++begin;\n      break;\n    case '+':\n    case ' ':\n      specs.set_sign(c == ' ' ? sign::space : sign::plus);\n      FMT_FALLTHROUGH;\n    case '-':\n      enter_state(state::sign, in(arg_type, sint_set | float_set));\n      ++begin;\n      break;\n    case '#':\n      enter_state(state::hash, is_arithmetic_type(arg_type));\n      specs.set_alt();\n      ++begin;\n      break;\n    case '0':\n      enter_state(state::zero);\n      if (!is_arithmetic_type(arg_type))\n        report_error(\"format specifier requires numeric argument\");\n      if (specs.align() == align::none) {\n        // Ignore 0 if align is specified for compatibility with std::format.\n        specs.set_align(align::numeric);\n        specs.set_fill('0');\n      }\n      ++begin;\n      break;\n      // clang-format off\n    case '1': case '2': case '3': case '4': case '5':\n    case '6': case '7': case '8': case '9': case '{':\n      // clang-format on\n      enter_state(state::width);\n      begin = parse_width(begin, end, specs, specs.width_ref, ctx);\n      break;\n    case '.':\n      enter_state(state::precision,\n                  in(arg_type, float_set | string_set | cstring_set));\n      begin = parse_precision(begin, end, specs, specs.precision_ref, ctx);\n      break;\n    case 'L':\n      enter_state(state::locale, is_arithmetic_type(arg_type));\n      specs.set_localized();\n      ++begin;\n      break;\n    case 'd': return parse_presentation_type(pres::dec, integral_set);\n    case 'X': specs.set_upper(); FMT_FALLTHROUGH;\n    case 'x': return parse_presentation_type(pres::hex, integral_set);\n    case 'o': return parse_presentation_type(pres::oct, integral_set);\n    case 'B': specs.set_upper(); FMT_FALLTHROUGH;\n    case 'b': return parse_presentation_type(pres::bin, integral_set);\n    case 'E': specs.set_upper(); FMT_FALLTHROUGH;\n    case 'e': return parse_presentation_type(pres::exp, float_set);\n    case 'F': specs.set_upper(); FMT_FALLTHROUGH;\n    case 'f': return parse_presentation_type(pres::fixed, float_set);\n    case 'G': specs.set_upper(); FMT_FALLTHROUGH;\n    case 'g': return parse_presentation_type(pres::general, float_set);\n    case 'A': specs.set_upper(); FMT_FALLTHROUGH;\n    case 'a': return parse_presentation_type(pres::hexfloat, float_set);\n    case 'c':\n      if (arg_type == type::bool_type) report_error(\"invalid format specifier\");\n      return parse_presentation_type(pres::chr, integral_set);\n    case 's':\n      return parse_presentation_type(pres::string,\n                                     bool_set | string_set | cstring_set);\n    case 'p':\n      return parse_presentation_type(pres::pointer, pointer_set | cstring_set);\n    case '?':\n      return parse_presentation_type(pres::debug,\n                                     char_set | string_set | cstring_set);\n    case '}': return begin;\n    default:  {\n      if (*begin == '}') return begin;\n      // Parse fill and alignment.\n      auto fill_end = begin + code_point_length(begin);\n      if (end - fill_end <= 0) {\n        report_error(\"invalid format specifier\");\n        return begin;\n      }\n      if (*begin == '{') {\n        report_error(\"invalid fill character '{'\");\n        return begin;\n      }\n      auto alignment = parse_align(to_ascii(*fill_end));\n      enter_state(state::align, alignment != align::none);\n      specs.set_fill(\n          basic_string_view<Char>(begin, to_unsigned(fill_end - begin)));\n      specs.set_align(alignment);\n      begin = fill_end + 1;\n    }\n    }\n    if (begin == end) return begin;\n    c = to_ascii(*begin);\n  }\n}\n\ntemplate <typename Char, typename Handler>\nFMT_CONSTEXPR FMT_INLINE auto parse_replacement_field(const Char* begin,\n                                                      const Char* end,\n                                                      Handler&& handler)\n    -> const Char* {\n  ++begin;\n  if (begin == end) {\n    handler.on_error(\"invalid format string\");\n    return end;\n  }\n  int arg_id = 0;\n  switch (*begin) {\n  case '}':\n    handler.on_replacement_field(handler.on_arg_id(), begin);\n    return begin + 1;\n  case '{': handler.on_text(begin, begin + 1); return begin + 1;\n  case ':': arg_id = handler.on_arg_id(); break;\n  default:  {\n    struct id_adapter {\n      Handler& handler;\n      int arg_id;\n\n      FMT_CONSTEXPR void on_index(int id) { arg_id = handler.on_arg_id(id); }\n      FMT_CONSTEXPR void on_name(basic_string_view<Char> id) {\n        arg_id = handler.on_arg_id(id);\n      }\n    } adapter = {handler, 0};\n    begin = parse_arg_id(begin, end, adapter);\n    arg_id = adapter.arg_id;\n    Char c = begin != end ? *begin : Char();\n    if (c == '}') {\n      handler.on_replacement_field(arg_id, begin);\n      return begin + 1;\n    }\n    if (c != ':') {\n      handler.on_error(\"missing '}' in format string\");\n      return end;\n    }\n    break;\n  }\n  }\n  begin = handler.on_format_specs(arg_id, begin + 1, end);\n  if (begin == end || *begin != '}')\n    return handler.on_error(\"unknown format specifier\"), end;\n  return begin + 1;\n}\n\ntemplate <typename Char, typename Handler>\nFMT_CONSTEXPR void parse_format_string(basic_string_view<Char> fmt,\n                                       Handler&& handler) {\n  auto begin = fmt.data(), end = begin + fmt.size();\n  auto p = begin;\n  while (p != end) {\n    auto c = *p++;\n    if (c == '{') {\n      handler.on_text(begin, p - 1);\n      begin = p = parse_replacement_field(p - 1, end, handler);\n    } else if (c == '}') {\n      if (p == end || *p != '}')\n        return handler.on_error(\"unmatched '}' in format string\");\n      handler.on_text(begin, p);\n      begin = ++p;\n    }\n  }\n  handler.on_text(begin, end);\n}\n\n// Checks char specs and returns true iff the presentation type is char-like.\nFMT_CONSTEXPR inline auto check_char_specs(const format_specs& specs) -> bool {\n  auto type = specs.type();\n  if (type != presentation_type::none && type != presentation_type::chr &&\n      type != presentation_type::debug) {\n    return false;\n  }\n  if (specs.align() == align::numeric || specs.sign() != sign::none ||\n      specs.alt()) {\n    report_error(\"invalid format specifier for char\");\n  }\n  return true;\n}\n\n// A base class for compile-time strings.\nstruct compile_string {};\n\ntemplate <typename T, typename Char>\nFMT_VISIBILITY(\"hidden\")  // Suppress an ld warning on macOS (#3769).\nFMT_CONSTEXPR auto invoke_parse(parse_context<Char>& ctx) -> const Char* {\n  using mapped_type = remove_cvref_t<mapped_t<T, Char>>;\n  constexpr bool formattable =\n      std::is_constructible<formatter<mapped_type, Char>>::value;\n  if (!formattable) return ctx.begin();  // Error is reported in the value ctor.\n  using formatted_type = conditional_t<formattable, mapped_type, int>;\n  return formatter<formatted_type, Char>().parse(ctx);\n}\n\ntemplate <typename... T> struct arg_pack {};\n\ntemplate <typename Char, int NUM_ARGS, int NUM_NAMED_ARGS, bool DYNAMIC_NAMES>\nclass format_string_checker {\n private:\n  type types_[max_of<size_t>(1, NUM_ARGS)];\n  named_arg_info<Char> named_args_[max_of<size_t>(1, NUM_NAMED_ARGS)];\n  compile_parse_context<Char> context_;\n\n  using parse_func = auto (*)(parse_context<Char>&) -> const Char*;\n  parse_func parse_funcs_[max_of<size_t>(1, NUM_ARGS)];\n\n public:\n  template <typename... T>\n  FMT_CONSTEXPR explicit format_string_checker(basic_string_view<Char> fmt,\n                                               arg_pack<T...>)\n      : types_{mapped_type_constant<T, Char>::value...},\n        named_args_{},\n        context_(fmt, NUM_ARGS, types_),\n        parse_funcs_{&invoke_parse<T, Char>...} {\n    int arg_index = 0, named_arg_index = 0;\n    FMT_APPLY_VARIADIC(\n        init_static_named_arg<T>(named_args_, arg_index, named_arg_index));\n    ignore_unused(arg_index, named_arg_index);\n  }\n\n  FMT_CONSTEXPR void on_text(const Char*, const Char*) {}\n\n  FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); }\n  FMT_CONSTEXPR auto on_arg_id(int id) -> int {\n    context_.check_arg_id(id);\n    return id;\n  }\n  FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {\n    for (int i = 0; i < NUM_NAMED_ARGS; ++i) {\n      if (named_args_[i].name == id) return named_args_[i].id;\n    }\n    if (!DYNAMIC_NAMES) on_error(\"argument not found\");\n    return -1;\n  }\n\n  FMT_CONSTEXPR void on_replacement_field(int id, const Char* begin) {\n    on_format_specs(id, begin, begin);  // Call parse() on empty specs.\n  }\n\n  FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char* end)\n      -> const Char* {\n    context_.advance_to(begin);\n    if (id >= 0 && id < NUM_ARGS) return parse_funcs_[id](context_);\n\n    // If id is out of range, it means we do not know the type and cannot parse\n    // the format at compile time. Instead, skip over content until we finish\n    // the format spec, accounting for any nested replacements.\n    for (int bracket_count = 0;\n         begin != end && (bracket_count > 0 || *begin != '}'); ++begin) {\n      if (*begin == '{')\n        ++bracket_count;\n      else if (*begin == '}')\n        --bracket_count;\n    }\n    return begin;\n  }\n\n  FMT_NORETURN FMT_CONSTEXPR void on_error(const char* message) {\n    report_error(message);\n  }\n};\n\n/// A contiguous memory buffer with an optional growing ability. It is an\n/// internal class and shouldn't be used directly, only via `memory_buffer`.\ntemplate <typename T> class buffer {\n private:\n  T* ptr_;\n  size_t size_;\n  size_t capacity_;\n\n  using grow_fun = void (*)(buffer& buf, size_t capacity);\n  grow_fun grow_;\n\n protected:\n  // Don't initialize ptr_ since it is not accessed to save a few cycles.\n  FMT_MSC_WARNING(suppress : 26495)\n  FMT_CONSTEXPR buffer(grow_fun grow, size_t sz) noexcept\n      : size_(sz), capacity_(sz), grow_(grow) {}\n\n  constexpr buffer(grow_fun grow, T* p = nullptr, size_t sz = 0,\n                   size_t cap = 0) noexcept\n      : ptr_(p), size_(sz), capacity_(cap), grow_(grow) {}\n\n  FMT_CONSTEXPR20 ~buffer() = default;\n  buffer(buffer&&) = default;\n\n  /// Sets the buffer data and capacity.\n  FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept {\n    ptr_ = buf_data;\n    capacity_ = buf_capacity;\n  }\n\n public:\n  using value_type = T;\n  using const_reference = const T&;\n\n  buffer(const buffer&) = delete;\n  void operator=(const buffer&) = delete;\n\n  auto begin() noexcept -> T* { return ptr_; }\n  auto end() noexcept -> T* { return ptr_ + size_; }\n\n  auto begin() const noexcept -> const T* { return ptr_; }\n  auto end() const noexcept -> const T* { return ptr_ + size_; }\n\n  /// Returns the size of this buffer.\n  constexpr auto size() const noexcept -> size_t { return size_; }\n\n  /// Returns the capacity of this buffer.\n  constexpr auto capacity() const noexcept -> size_t { return capacity_; }\n\n  /// Returns a pointer to the buffer data (not null-terminated).\n  FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; }\n  FMT_CONSTEXPR auto data() const noexcept -> const T* { return ptr_; }\n\n  /// Clears this buffer.\n  FMT_CONSTEXPR void clear() { size_ = 0; }\n\n  // Tries resizing the buffer to contain `count` elements. If T is a POD type\n  // the new elements may not be initialized.\n  FMT_CONSTEXPR void try_resize(size_t count) {\n    try_reserve(count);\n    size_ = min_of(count, capacity_);\n  }\n\n  // Tries increasing the buffer capacity to `new_capacity`. It can increase the\n  // capacity by a smaller amount than requested but guarantees there is space\n  // for at least one additional element either by increasing the capacity or by\n  // flushing the buffer if it is full.\n  FMT_CONSTEXPR void try_reserve(size_t new_capacity) {\n    if (new_capacity > capacity_) grow_(*this, new_capacity);\n  }\n\n  FMT_CONSTEXPR void push_back(const T& value) {\n    try_reserve(size_ + 1);\n    ptr_[size_++] = value;\n  }\n\n  /// Appends data to the end of the buffer.\n  template <typename U>\n// Workaround for MSVC2019 to fix error C2893: Failed to specialize function\n// template 'void fmt::v11::detail::buffer<T>::append(const U *,const U *)'.\n#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1940\n  FMT_CONSTEXPR20\n#endif\n      void\n      append(const U* begin, const U* end) {\n    while (begin != end) {\n      auto count = to_unsigned(end - begin);\n      try_reserve(size_ + count);\n      auto free_cap = capacity_ - size_;\n      if (free_cap < count) count = free_cap;\n      // A loop is faster than memcpy on small sizes.\n      T* out = ptr_ + size_;\n      for (size_t i = 0; i < count; ++i) out[i] = begin[i];\n      size_ += count;\n      begin += count;\n    }\n  }\n\n  template <typename Idx> FMT_CONSTEXPR auto operator[](Idx index) -> T& {\n    return ptr_[index];\n  }\n  template <typename Idx>\n  FMT_CONSTEXPR auto operator[](Idx index) const -> const T& {\n    return ptr_[index];\n  }\n};\n\nstruct buffer_traits {\n  constexpr explicit buffer_traits(size_t) {}\n  constexpr auto count() const -> size_t { return 0; }\n  constexpr auto limit(size_t size) const -> size_t { return size; }\n};\n\nclass fixed_buffer_traits {\n private:\n  size_t count_ = 0;\n  size_t limit_;\n\n public:\n  constexpr explicit fixed_buffer_traits(size_t limit) : limit_(limit) {}\n  constexpr auto count() const -> size_t { return count_; }\n  FMT_CONSTEXPR auto limit(size_t size) -> size_t {\n    size_t n = limit_ > count_ ? limit_ - count_ : 0;\n    count_ += size;\n    return min_of(size, n);\n  }\n};\n\n// A buffer that writes to an output iterator when flushed.\ntemplate <typename OutputIt, typename T, typename Traits = buffer_traits>\nclass iterator_buffer : public Traits, public buffer<T> {\n private:\n  OutputIt out_;\n  enum { buffer_size = 256 };\n  T data_[buffer_size];\n\n  static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {\n    if (buf.size() == buffer_size) static_cast<iterator_buffer&>(buf).flush();\n  }\n\n  void flush() {\n    auto size = this->size();\n    this->clear();\n    const T* begin = data_;\n    const T* end = begin + this->limit(size);\n    while (begin != end) *out_++ = *begin++;\n  }\n\n public:\n  explicit iterator_buffer(OutputIt out, size_t n = buffer_size)\n      : Traits(n), buffer<T>(grow, data_, 0, buffer_size), out_(out) {}\n  iterator_buffer(iterator_buffer&& other) noexcept\n      : Traits(other),\n        buffer<T>(grow, data_, 0, buffer_size),\n        out_(other.out_) {}\n  ~iterator_buffer() {\n    // Don't crash if flush fails during unwinding.\n    FMT_TRY { flush(); }\n    FMT_CATCH(...) {}\n  }\n\n  auto out() -> OutputIt {\n    flush();\n    return out_;\n  }\n  auto count() const -> size_t { return Traits::count() + this->size(); }\n};\n\ntemplate <typename T>\nclass iterator_buffer<T*, T, fixed_buffer_traits> : public fixed_buffer_traits,\n                                                    public buffer<T> {\n private:\n  T* out_;\n  enum { buffer_size = 256 };\n  T data_[buffer_size];\n\n  static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {\n    if (buf.size() == buf.capacity())\n      static_cast<iterator_buffer&>(buf).flush();\n  }\n\n  void flush() {\n    size_t n = this->limit(this->size());\n    if (this->data() == out_) {\n      out_ += n;\n      this->set(data_, buffer_size);\n    }\n    this->clear();\n  }\n\n public:\n  explicit iterator_buffer(T* out, size_t n = buffer_size)\n      : fixed_buffer_traits(n), buffer<T>(grow, out, 0, n), out_(out) {}\n  iterator_buffer(iterator_buffer&& other) noexcept\n      : fixed_buffer_traits(other),\n        buffer<T>(static_cast<iterator_buffer&&>(other)),\n        out_(other.out_) {\n    if (this->data() != out_) {\n      this->set(data_, buffer_size);\n      this->clear();\n    }\n  }\n  ~iterator_buffer() { flush(); }\n\n  auto out() -> T* {\n    flush();\n    return out_;\n  }\n  auto count() const -> size_t {\n    return fixed_buffer_traits::count() + this->size();\n  }\n};\n\ntemplate <typename T> class iterator_buffer<T*, T> : public buffer<T> {\n public:\n  explicit iterator_buffer(T* out, size_t = 0)\n      : buffer<T>([](buffer<T>&, size_t) {}, out, 0, ~size_t()) {}\n\n  auto out() -> T* { return &*this->end(); }\n};\n\ntemplate <typename Container>\nclass container_buffer : public buffer<typename Container::value_type> {\n private:\n  using value_type = typename Container::value_type;\n\n  static FMT_CONSTEXPR void grow(buffer<value_type>& buf, size_t capacity) {\n    auto& self = static_cast<container_buffer&>(buf);\n    self.container.resize(capacity);\n    self.set(&self.container[0], capacity);\n  }\n\n public:\n  Container& container;\n\n  explicit container_buffer(Container& c)\n      : buffer<value_type>(grow, c.size()), container(c) {}\n};\n\n// A buffer that writes to a container with the contiguous storage.\ntemplate <typename OutputIt>\nclass iterator_buffer<\n    OutputIt,\n    enable_if_t<is_back_insert_iterator<OutputIt>::value &&\n                    is_contiguous<typename OutputIt::container_type>::value,\n                typename OutputIt::container_type::value_type>>\n    : public container_buffer<typename OutputIt::container_type> {\n private:\n  using base = container_buffer<typename OutputIt::container_type>;\n\n public:\n  explicit iterator_buffer(typename OutputIt::container_type& c) : base(c) {}\n  explicit iterator_buffer(OutputIt out, size_t = 0)\n      : base(get_container(out)) {}\n\n  auto out() -> OutputIt { return OutputIt(this->container); }\n};\n\n// A buffer that counts the number of code units written discarding the output.\ntemplate <typename T = char> class counting_buffer : public buffer<T> {\n private:\n  enum { buffer_size = 256 };\n  T data_[buffer_size];\n  size_t count_ = 0;\n\n  static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {\n    if (buf.size() != buffer_size) return;\n    static_cast<counting_buffer&>(buf).count_ += buf.size();\n    buf.clear();\n  }\n\n public:\n  FMT_CONSTEXPR counting_buffer() : buffer<T>(grow, data_, 0, buffer_size) {}\n\n  constexpr auto count() const noexcept -> size_t {\n    return count_ + this->size();\n  }\n};\n\ntemplate <typename T>\nstruct is_back_insert_iterator<basic_appender<T>> : std::true_type {};\n\ntemplate <typename OutputIt, typename InputIt, typename = void>\nstruct has_back_insert_iterator_container_append : std::false_type {};\ntemplate <typename OutputIt, typename InputIt>\nstruct has_back_insert_iterator_container_append<\n    OutputIt, InputIt,\n    void_t<decltype(get_container(std::declval<OutputIt>())\n                        .append(std::declval<InputIt>(),\n                                std::declval<InputIt>()))>> : std::true_type {};\n\ntemplate <typename OutputIt, typename InputIt, typename = void>\nstruct has_back_insert_iterator_container_insert_at_end : std::false_type {};\n\ntemplate <typename OutputIt, typename InputIt>\nstruct has_back_insert_iterator_container_insert_at_end<\n    OutputIt, InputIt,\n    void_t<decltype(get_container(std::declval<OutputIt>())\n                        .insert(get_container(std::declval<OutputIt>()).end(),\n                                std::declval<InputIt>(),\n                                std::declval<InputIt>()))>> : std::true_type {};\n\n// An optimized version of std::copy with the output value type (T).\ntemplate <typename T, typename InputIt, typename OutputIt,\n          FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value&&\n                            has_back_insert_iterator_container_append<\n                                OutputIt, InputIt>::value)>\nFMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out)\n    -> OutputIt {\n  get_container(out).append(begin, end);\n  return out;\n}\n\ntemplate <typename T, typename InputIt, typename OutputIt,\n          FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value &&\n                        !has_back_insert_iterator_container_append<\n                            OutputIt, InputIt>::value &&\n                        has_back_insert_iterator_container_insert_at_end<\n                            OutputIt, InputIt>::value)>\nFMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out)\n    -> OutputIt {\n  auto& c = get_container(out);\n  c.insert(c.end(), begin, end);\n  return out;\n}\n\ntemplate <typename T, typename InputIt, typename OutputIt,\n          FMT_ENABLE_IF(!(is_back_insert_iterator<OutputIt>::value &&\n                          (has_back_insert_iterator_container_append<\n                               OutputIt, InputIt>::value ||\n                           has_back_insert_iterator_container_insert_at_end<\n                               OutputIt, InputIt>::value)))>\nFMT_CONSTEXPR auto copy(InputIt begin, InputIt end, OutputIt out) -> OutputIt {\n  while (begin != end) *out++ = static_cast<T>(*begin++);\n  return out;\n}\n\ntemplate <typename T, typename V, typename OutputIt>\nFMT_CONSTEXPR auto copy(basic_string_view<V> s, OutputIt out) -> OutputIt {\n  return copy<T>(s.begin(), s.end(), out);\n}\n\ntemplate <typename It, typename Enable = std::true_type>\nstruct is_buffer_appender : std::false_type {};\ntemplate <typename It>\nstruct is_buffer_appender<\n    It, bool_constant<\n            is_back_insert_iterator<It>::value &&\n            std::is_base_of<buffer<typename It::container_type::value_type>,\n                            typename It::container_type>::value>>\n    : std::true_type {};\n\n// Maps an output iterator to a buffer.\ntemplate <typename T, typename OutputIt,\n          FMT_ENABLE_IF(!is_buffer_appender<OutputIt>::value)>\nauto get_buffer(OutputIt out) -> iterator_buffer<OutputIt, T> {\n  return iterator_buffer<OutputIt, T>(out);\n}\ntemplate <typename T, typename OutputIt,\n          FMT_ENABLE_IF(is_buffer_appender<OutputIt>::value)>\nauto get_buffer(OutputIt out) -> buffer<T>& {\n  return get_container(out);\n}\n\ntemplate <typename Buf, typename OutputIt>\nauto get_iterator(Buf& buf, OutputIt) -> decltype(buf.out()) {\n  return buf.out();\n}\ntemplate <typename T, typename OutputIt>\nauto get_iterator(buffer<T>&, OutputIt out) -> OutputIt {\n  return out;\n}\n\n// This type is intentionally undefined, only used for errors.\ntemplate <typename T, typename Char> struct type_is_unformattable_for;\n\ntemplate <typename Char> struct string_value {\n  const Char* data;\n  size_t size;\n  auto str() const -> basic_string_view<Char> { return {data, size}; }\n};\n\ntemplate <typename Context> struct custom_value {\n  using char_type = typename Context::char_type;\n  void* value;\n  void (*format)(void* arg, parse_context<char_type>& parse_ctx, Context& ctx);\n};\n\ntemplate <typename Char> struct named_arg_value {\n  const named_arg_info<Char>* data;\n  size_t size;\n};\n\nstruct custom_tag {};\n\n#if !FMT_BUILTIN_TYPES\n#  define FMT_BUILTIN , monostate\n#else\n#  define FMT_BUILTIN\n#endif\n\n// A formatting argument value.\ntemplate <typename Context> class value {\n public:\n  using char_type = typename Context::char_type;\n\n  union {\n    monostate no_value;\n    int int_value;\n    unsigned uint_value;\n    long long long_long_value;\n    unsigned long long ulong_long_value;\n    int128_opt int128_value;\n    uint128_opt uint128_value;\n    bool bool_value;\n    char_type char_value;\n    float float_value;\n    double double_value;\n    long double long_double_value;\n    const void* pointer;\n    string_value<char_type> string;\n    custom_value<Context> custom;\n    named_arg_value<char_type> named_args;\n  };\n\n  constexpr FMT_INLINE value() : no_value() {}\n  constexpr FMT_INLINE value(signed char x) : int_value(x) {}\n  constexpr FMT_INLINE value(unsigned char x FMT_BUILTIN) : uint_value(x) {}\n  constexpr FMT_INLINE value(signed short x) : int_value(x) {}\n  constexpr FMT_INLINE value(unsigned short x FMT_BUILTIN) : uint_value(x) {}\n  constexpr FMT_INLINE value(int x) : int_value(x) {}\n  constexpr FMT_INLINE value(unsigned x FMT_BUILTIN) : uint_value(x) {}\n  FMT_CONSTEXPR FMT_INLINE value(long x FMT_BUILTIN) : value(long_type(x)) {}\n  FMT_CONSTEXPR FMT_INLINE value(unsigned long x FMT_BUILTIN)\n      : value(ulong_type(x)) {}\n  constexpr FMT_INLINE value(long long x FMT_BUILTIN) : long_long_value(x) {}\n  constexpr FMT_INLINE value(unsigned long long x FMT_BUILTIN)\n      : ulong_long_value(x) {}\n  FMT_INLINE value(int128_opt x FMT_BUILTIN) : int128_value(x) {}\n  FMT_INLINE value(uint128_opt x FMT_BUILTIN) : uint128_value(x) {}\n  constexpr FMT_INLINE value(bool x FMT_BUILTIN) : bool_value(x) {}\n\n  template <int N>\n  constexpr FMT_INLINE value(bitint<N> x FMT_BUILTIN) : long_long_value(x) {\n    static_assert(N <= 64, \"unsupported _BitInt\");\n  }\n  template <int N>\n  constexpr FMT_INLINE value(ubitint<N> x FMT_BUILTIN) : ulong_long_value(x) {\n    static_assert(N <= 64, \"unsupported _BitInt\");\n  }\n\n  template <typename T, FMT_ENABLE_IF(is_code_unit<T>::value)>\n  constexpr FMT_INLINE value(T x FMT_BUILTIN) : char_value(x) {\n    static_assert(\n        std::is_same<T, char>::value || std::is_same<T, char_type>::value,\n        \"mixing character types is disallowed\");\n  }\n\n  constexpr FMT_INLINE value(float x FMT_BUILTIN) : float_value(x) {}\n  constexpr FMT_INLINE value(double x FMT_BUILTIN) : double_value(x) {}\n  FMT_INLINE value(long double x FMT_BUILTIN) : long_double_value(x) {}\n\n  FMT_CONSTEXPR FMT_INLINE value(char_type* x FMT_BUILTIN) {\n    string.data = x;\n    if (is_constant_evaluated()) string.size = 0;\n  }\n  FMT_CONSTEXPR FMT_INLINE value(const char_type* x FMT_BUILTIN) {\n    string.data = x;\n    if (is_constant_evaluated()) string.size = 0;\n  }\n  template <typename T, typename C = char_t<T>,\n            FMT_ENABLE_IF(!std::is_pointer<T>::value)>\n  FMT_CONSTEXPR value(const T& x FMT_BUILTIN) {\n    static_assert(std::is_same<C, char_type>::value,\n                  \"mixing character types is disallowed\");\n    auto sv = to_string_view(x);\n    string.data = sv.data();\n    string.size = sv.size();\n  }\n  FMT_INLINE value(void* x FMT_BUILTIN) : pointer(x) {}\n  FMT_INLINE value(const void* x FMT_BUILTIN) : pointer(x) {}\n  FMT_INLINE value(volatile void* x FMT_BUILTIN)\n      : pointer(const_cast<const void*>(x)) {}\n  FMT_INLINE value(const volatile void* x FMT_BUILTIN)\n      : pointer(const_cast<const void*>(x)) {}\n  FMT_INLINE value(nullptr_t) : pointer(nullptr) {}\n\n  template <typename T, FMT_ENABLE_IF(std::is_pointer<T>::value ||\n                                      std::is_member_pointer<T>::value)>\n  value(const T&) {\n    // Formatting of arbitrary pointers is disallowed. If you want to format a\n    // pointer cast it to `void*` or `const void*`. In particular, this forbids\n    // formatting of `[const] volatile char*` printed as bool by iostreams.\n    static_assert(sizeof(T) == 0,\n                  \"formatting of non-void pointers is disallowed\");\n  }\n\n  template <typename T, FMT_ENABLE_IF(use_format_as<T>::value)>\n  value(const T& x) : value(format_as(x)) {}\n  template <typename T, FMT_ENABLE_IF(use_format_as_member<T>::value)>\n  value(const T& x) : value(formatter<T>::format_as(x)) {}\n\n  template <typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>\n  value(const T& named_arg) : value(named_arg.value) {}\n\n  template <typename T,\n            FMT_ENABLE_IF(use_formatter<T>::value || !FMT_BUILTIN_TYPES)>\n  FMT_CONSTEXPR20 FMT_INLINE value(T& x) : value(x, custom_tag()) {}\n\n  FMT_ALWAYS_INLINE value(const named_arg_info<char_type>* args, size_t size)\n      : named_args{args, size} {}\n\n private:\n  template <typename T, FMT_ENABLE_IF(has_formatter<T, char_type>())>\n  FMT_CONSTEXPR value(T& x, custom_tag) {\n    using value_type = remove_const_t<T>;\n    // T may overload operator& e.g. std::vector<bool>::reference in libc++.\n    if (!is_constant_evaluated()) {\n      custom.value =\n          const_cast<char*>(&reinterpret_cast<const volatile char&>(x));\n    } else {\n      custom.value = nullptr;\n#if defined(__cpp_if_constexpr)\n      if constexpr (std::is_same<decltype(&x), remove_reference_t<T>*>::value)\n        custom.value = const_cast<value_type*>(&x);\n#endif\n    }\n    custom.format = format_custom<value_type>;\n  }\n\n  template <typename T, FMT_ENABLE_IF(!has_formatter<T, char_type>())>\n  FMT_CONSTEXPR value(const T&, custom_tag) {\n    // Cannot format an argument; to make type T formattable provide a\n    // formatter<T> specialization: https://fmt.dev/latest/api.html#udt.\n    type_is_unformattable_for<T, char_type> _;\n  }\n\n  // Formats an argument of a custom type, such as a user-defined class.\n  template <typename T>\n  static void format_custom(void* arg, parse_context<char_type>& parse_ctx,\n                            Context& ctx) {\n    auto f = formatter<T, char_type>();\n    parse_ctx.advance_to(f.parse(parse_ctx));\n    using qualified_type =\n        conditional_t<has_formatter<const T, char_type>(), const T, T>;\n    // format must be const for compatibility with std::format and compilation.\n    const auto& cf = f;\n    ctx.advance_to(cf.format(*static_cast<qualified_type*>(arg), ctx));\n  }\n};\n\nenum { packed_arg_bits = 4 };\n// Maximum number of arguments with packed types.\nenum { max_packed_args = 62 / packed_arg_bits };\nenum : unsigned long long { is_unpacked_bit = 1ULL << 63 };\nenum : unsigned long long { has_named_args_bit = 1ULL << 62 };\n\ntemplate <typename It, typename T, typename Enable = void>\nstruct is_output_iterator : std::false_type {};\n\ntemplate <> struct is_output_iterator<appender, char> : std::true_type {};\n\ntemplate <typename It, typename T>\nstruct is_output_iterator<\n    It, T,\n    enable_if_t<std::is_assignable<decltype(*std::declval<decay_t<It>&>()++),\n                                   T>::value>> : std::true_type {};\n\ntemplate <typename> constexpr auto encode_types() -> unsigned long long {\n  return 0;\n}\n\ntemplate <typename Context, typename First, typename... T>\nconstexpr auto encode_types() -> unsigned long long {\n  return static_cast<unsigned>(stored_type_constant<First, Context>::value) |\n         (encode_types<Context, T...>() << packed_arg_bits);\n}\n\ntemplate <typename Context, typename... T, size_t NUM_ARGS = sizeof...(T)>\nconstexpr auto make_descriptor() -> unsigned long long {\n  return NUM_ARGS <= max_packed_args ? encode_types<Context, T...>()\n                                     : is_unpacked_bit | NUM_ARGS;\n}\n\ntemplate <typename Context, int NUM_ARGS>\nusing arg_t = conditional_t<NUM_ARGS <= max_packed_args, value<Context>,\n                            basic_format_arg<Context>>;\n\ntemplate <typename Context, int NUM_ARGS, int NUM_NAMED_ARGS,\n          unsigned long long DESC>\nstruct named_arg_store {\n  // args_[0].named_args points to named_args to avoid bloating format_args.\n  arg_t<Context, NUM_ARGS> args[1u + NUM_ARGS];\n  named_arg_info<typename Context::char_type>\n      named_args[static_cast<size_t>(NUM_NAMED_ARGS)];\n\n  template <typename... T>\n  FMT_CONSTEXPR FMT_ALWAYS_INLINE named_arg_store(T&... values)\n      : args{{named_args, NUM_NAMED_ARGS}, values...} {\n    int arg_index = 0, named_arg_index = 0;\n    FMT_APPLY_VARIADIC(\n        init_named_arg(named_args, arg_index, named_arg_index, values));\n  }\n\n  named_arg_store(named_arg_store&& rhs) {\n    args[0] = {named_args, NUM_NAMED_ARGS};\n    for (size_t i = 1; i < sizeof(args) / sizeof(*args); ++i)\n      args[i] = rhs.args[i];\n    for (size_t i = 0; i < NUM_NAMED_ARGS; ++i)\n      named_args[i] = rhs.named_args[i];\n  }\n\n  named_arg_store(const named_arg_store& rhs) = delete;\n  auto operator=(const named_arg_store& rhs) -> named_arg_store& = delete;\n  auto operator=(named_arg_store&& rhs) -> named_arg_store& = delete;\n  operator const arg_t<Context, NUM_ARGS>*() const { return args + 1; }\n};\n\n// An array of references to arguments. It can be implicitly converted to\n// `basic_format_args` for passing into type-erased formatting functions\n// such as `vformat`. It is a plain struct to reduce binary size in debug mode.\ntemplate <typename Context, int NUM_ARGS, int NUM_NAMED_ARGS,\n          unsigned long long DESC>\nstruct format_arg_store {\n  // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.\n  using type =\n      conditional_t<NUM_NAMED_ARGS == 0,\n                    arg_t<Context, NUM_ARGS>[max_of<size_t>(1, NUM_ARGS)],\n                    named_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC>>;\n  type args;\n};\n\n// TYPE can be different from type_constant<T>, e.g. for __float128.\ntemplate <typename T, typename Char, type TYPE> struct native_formatter {\n private:\n  dynamic_format_specs<Char> specs_;\n\n public:\n  using nonlocking = void;\n\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    if (ctx.begin() == ctx.end() || *ctx.begin() == '}') return ctx.begin();\n    auto end = parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, TYPE);\n    if (const_check(TYPE == type::char_type)) check_char_specs(specs_);\n    return end;\n  }\n\n  template <type U = TYPE,\n            FMT_ENABLE_IF(U == type::string_type || U == type::cstring_type ||\n                          U == type::char_type)>\n  FMT_CONSTEXPR void set_debug_format(bool set = true) {\n    specs_.set_type(set ? presentation_type::debug : presentation_type::none);\n  }\n\n  FMT_PRAGMA_CLANG(diagnostic ignored \"-Wundefined-inline\")\n  template <typename FormatContext>\n  FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const\n      -> decltype(ctx.out());\n};\n\ntemplate <typename T, typename Enable = void>\nstruct locking\n    : bool_constant<mapped_type_constant<T>::value == type::custom_type> {};\ntemplate <typename T>\nstruct locking<T, void_t<typename formatter<remove_cvref_t<T>>::nonlocking>>\n    : std::false_type {};\n\ntemplate <typename T = int> FMT_CONSTEXPR inline auto is_locking() -> bool {\n  return locking<T>::value;\n}\ntemplate <typename T1, typename T2, typename... Tail>\nFMT_CONSTEXPR inline auto is_locking() -> bool {\n  return locking<T1>::value || is_locking<T2, Tail...>();\n}\n\nFMT_API void vformat_to(buffer<char>& buf, string_view fmt, format_args args,\n                        locale_ref loc = {});\n\n#if FMT_WIN32\nFMT_API void vprint_mojibake(FILE*, string_view, format_args, bool);\n#else  // format_args is passed by reference since it is defined later.\ninline void vprint_mojibake(FILE*, string_view, const format_args&, bool) {}\n#endif\n}  // namespace detail\n\n// The main public API.\n\ntemplate <typename Char>\nFMT_CONSTEXPR void parse_context<Char>::do_check_arg_id(int arg_id) {\n  // Argument id is only checked at compile time during parsing because\n  // formatting has its own validation.\n  if (detail::is_constant_evaluated() && use_constexpr_cast) {\n    auto ctx = static_cast<detail::compile_parse_context<Char>*>(this);\n    if (arg_id >= ctx->num_args()) report_error(\"argument not found\");\n  }\n}\n\ntemplate <typename Char>\nFMT_CONSTEXPR void parse_context<Char>::check_dynamic_spec(int arg_id) {\n  using detail::compile_parse_context;\n  if (detail::is_constant_evaluated() && use_constexpr_cast)\n    static_cast<compile_parse_context<Char>*>(this)->check_dynamic_spec(arg_id);\n}\n\nFMT_BEGIN_EXPORT\n\n// An output iterator that appends to a buffer. It is used instead of\n// back_insert_iterator to reduce symbol sizes and avoid <iterator> dependency.\ntemplate <typename T> class basic_appender {\n protected:\n  detail::buffer<T>* container;\n\n public:\n  using container_type = detail::buffer<T>;\n\n  FMT_CONSTEXPR basic_appender(detail::buffer<T>& buf) : container(&buf) {}\n\n  FMT_CONSTEXPR20 auto operator=(T c) -> basic_appender& {\n    container->push_back(c);\n    return *this;\n  }\n  FMT_CONSTEXPR20 auto operator*() -> basic_appender& { return *this; }\n  FMT_CONSTEXPR20 auto operator++() -> basic_appender& { return *this; }\n  FMT_CONSTEXPR20 auto operator++(int) -> basic_appender { return *this; }\n};\n\n// A formatting argument. Context is a template parameter for the compiled API\n// where output can be unbuffered.\ntemplate <typename Context> class basic_format_arg {\n private:\n  detail::value<Context> value_;\n  detail::type type_;\n\n  friend class basic_format_args<Context>;\n\n  using char_type = typename Context::char_type;\n\n public:\n  class handle {\n   private:\n    detail::custom_value<Context> custom_;\n\n   public:\n    explicit handle(detail::custom_value<Context> custom) : custom_(custom) {}\n\n    void format(parse_context<char_type>& parse_ctx, Context& ctx) const {\n      custom_.format(custom_.value, parse_ctx, ctx);\n    }\n  };\n\n  constexpr basic_format_arg() : type_(detail::type::none_type) {}\n  basic_format_arg(const detail::named_arg_info<char_type>* args, size_t size)\n      : value_(args, size) {}\n  template <typename T>\n  basic_format_arg(T&& val)\n      : value_(val), type_(detail::stored_type_constant<T, Context>::value) {}\n\n  constexpr explicit operator bool() const noexcept {\n    return type_ != detail::type::none_type;\n  }\n  auto type() const -> detail::type { return type_; }\n\n  /**\n   * Visits an argument dispatching to the appropriate visit method based on\n   * the argument type. For example, if the argument type is `double` then\n   * `vis(value)` will be called with the value of type `double`.\n   */\n  template <typename Visitor>\n  FMT_CONSTEXPR FMT_INLINE auto visit(Visitor&& vis) const -> decltype(vis(0)) {\n    using detail::map;\n    switch (type_) {\n    case detail::type::none_type:        break;\n    case detail::type::int_type:         return vis(value_.int_value);\n    case detail::type::uint_type:        return vis(value_.uint_value);\n    case detail::type::long_long_type:   return vis(value_.long_long_value);\n    case detail::type::ulong_long_type:  return vis(value_.ulong_long_value);\n    case detail::type::int128_type:      return vis(map(value_.int128_value));\n    case detail::type::uint128_type:     return vis(map(value_.uint128_value));\n    case detail::type::bool_type:        return vis(value_.bool_value);\n    case detail::type::char_type:        return vis(value_.char_value);\n    case detail::type::float_type:       return vis(value_.float_value);\n    case detail::type::double_type:      return vis(value_.double_value);\n    case detail::type::long_double_type: return vis(value_.long_double_value);\n    case detail::type::cstring_type:     return vis(value_.string.data);\n    case detail::type::string_type:      return vis(value_.string.str());\n    case detail::type::pointer_type:     return vis(value_.pointer);\n    case detail::type::custom_type:      return vis(handle(value_.custom));\n    }\n    return vis(monostate());\n  }\n\n  auto format_custom(const char_type* parse_begin,\n                     parse_context<char_type>& parse_ctx, Context& ctx)\n      -> bool {\n    if (type_ != detail::type::custom_type) return false;\n    parse_ctx.advance_to(parse_begin);\n    value_.custom.format(value_.custom.value, parse_ctx, ctx);\n    return true;\n  }\n};\n\n/**\n * A view of a collection of formatting arguments. To avoid lifetime issues it\n * should only be used as a parameter type in type-erased functions such as\n * `vformat`:\n *\n *     void vlog(fmt::string_view fmt, fmt::format_args args);  // OK\n *     fmt::format_args args = fmt::make_format_args();  // Dangling reference\n */\ntemplate <typename Context> class basic_format_args {\n private:\n  // A descriptor that contains information about formatting arguments.\n  // If the number of arguments is less or equal to max_packed_args then\n  // argument types are passed in the descriptor. This reduces binary code size\n  // per formatting function call.\n  unsigned long long desc_;\n  union {\n    // If is_packed() returns true then argument values are stored in values_;\n    // otherwise they are stored in args_. This is done to improve cache\n    // locality and reduce compiled code size since storing larger objects\n    // may require more code (at least on x86-64) even if the same amount of\n    // data is actually copied to stack. It saves ~10% on the bloat test.\n    const detail::value<Context>* values_;\n    const basic_format_arg<Context>* args_;\n  };\n\n  constexpr auto is_packed() const -> bool {\n    return (desc_ & detail::is_unpacked_bit) == 0;\n  }\n  constexpr auto has_named_args() const -> bool {\n    return (desc_ & detail::has_named_args_bit) != 0;\n  }\n\n  FMT_CONSTEXPR auto type(int index) const -> detail::type {\n    int shift = index * detail::packed_arg_bits;\n    unsigned mask = (1 << detail::packed_arg_bits) - 1;\n    return static_cast<detail::type>((desc_ >> shift) & mask);\n  }\n\n  template <int NUM_ARGS, int NUM_NAMED_ARGS, unsigned long long DESC>\n  using store =\n      detail::format_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC>;\n\n public:\n  using format_arg = basic_format_arg<Context>;\n\n  constexpr basic_format_args() : desc_(0), args_(nullptr) {}\n\n  /// Constructs a `basic_format_args` object from `format_arg_store`.\n  template <int NUM_ARGS, int NUM_NAMED_ARGS, unsigned long long DESC,\n            FMT_ENABLE_IF(NUM_ARGS <= detail::max_packed_args)>\n  constexpr FMT_ALWAYS_INLINE basic_format_args(\n      const store<NUM_ARGS, NUM_NAMED_ARGS, DESC>& s)\n      : desc_(DESC | (NUM_NAMED_ARGS != 0 ? +detail::has_named_args_bit : 0)),\n        values_(s.args) {}\n\n  template <int NUM_ARGS, int NUM_NAMED_ARGS, unsigned long long DESC,\n            FMT_ENABLE_IF(NUM_ARGS > detail::max_packed_args)>\n  constexpr basic_format_args(const store<NUM_ARGS, NUM_NAMED_ARGS, DESC>& s)\n      : desc_(DESC | (NUM_NAMED_ARGS != 0 ? +detail::has_named_args_bit : 0)),\n        args_(s.args) {}\n\n  /// Constructs a `basic_format_args` object from a dynamic list of arguments.\n  constexpr basic_format_args(const format_arg* args, int count,\n                              bool has_named = false)\n      : desc_(detail::is_unpacked_bit | detail::to_unsigned(count) |\n              (has_named ? +detail::has_named_args_bit : 0)),\n        args_(args) {}\n\n  /// Returns the argument with the specified id.\n  FMT_CONSTEXPR auto get(int id) const -> format_arg {\n    auto arg = format_arg();\n    if (!is_packed()) {\n      if (id < max_size()) arg = args_[id];\n      return arg;\n    }\n    if (static_cast<unsigned>(id) >= detail::max_packed_args) return arg;\n    arg.type_ = type(id);\n    if (arg.type_ != detail::type::none_type) arg.value_ = values_[id];\n    return arg;\n  }\n\n  template <typename Char>\n  auto get(basic_string_view<Char> name) const -> format_arg {\n    int id = get_id(name);\n    return id >= 0 ? get(id) : format_arg();\n  }\n\n  template <typename Char>\n  FMT_CONSTEXPR auto get_id(basic_string_view<Char> name) const -> int {\n    if (!has_named_args()) return -1;\n    const auto& named_args =\n        (is_packed() ? values_[-1] : args_[-1].value_).named_args;\n    for (size_t i = 0; i < named_args.size; ++i) {\n      if (named_args.data[i].name == name) return named_args.data[i].id;\n    }\n    return -1;\n  }\n\n  auto max_size() const -> int {\n    unsigned long long max_packed = detail::max_packed_args;\n    return static_cast<int>(is_packed() ? max_packed\n                                        : desc_ & ~detail::is_unpacked_bit);\n  }\n};\n\n// A formatting context.\nclass context {\n private:\n  appender out_;\n  format_args args_;\n  FMT_NO_UNIQUE_ADDRESS locale_ref loc_;\n\n public:\n  using char_type = char;  ///< The character type for the output.\n  using iterator = appender;\n  using format_arg = basic_format_arg<context>;\n  enum { builtin_types = FMT_BUILTIN_TYPES };\n\n  /// Constructs a `context` object. References to the arguments are stored\n  /// in the object so make sure they have appropriate lifetimes.\n  FMT_CONSTEXPR context(iterator out, format_args args, locale_ref loc = {})\n      : out_(out), args_(args), loc_(loc) {}\n  context(context&&) = default;\n  context(const context&) = delete;\n  void operator=(const context&) = delete;\n\n  FMT_CONSTEXPR auto arg(int id) const -> format_arg { return args_.get(id); }\n  inline auto arg(string_view name) const -> format_arg {\n    return args_.get(name);\n  }\n  FMT_CONSTEXPR auto arg_id(string_view name) const -> int {\n    return args_.get_id(name);\n  }\n  auto args() const -> const format_args& { return args_; }\n\n  // Returns an iterator to the beginning of the output range.\n  FMT_CONSTEXPR auto out() const -> iterator { return out_; }\n\n  // Advances the begin iterator to `it`.\n  FMT_CONSTEXPR void advance_to(iterator) {}\n\n  FMT_CONSTEXPR auto locale() const -> locale_ref { return loc_; }\n};\n\ntemplate <typename Char = char> struct runtime_format_string {\n  basic_string_view<Char> str;\n};\n\n/**\n * Creates a runtime format string.\n *\n * **Example**:\n *\n *     // Check format string at runtime instead of compile-time.\n *     fmt::print(fmt::runtime(\"{:d}\"), \"I am not a number\");\n */\ninline auto runtime(string_view s) -> runtime_format_string<> { return {{s}}; }\n\n/// A compile-time format string. Use `format_string` in the public API to\n/// prevent type deduction.\ntemplate <typename... T> struct fstring {\n private:\n  static constexpr int num_static_named_args =\n      detail::count_static_named_args<T...>();\n\n  using checker = detail::format_string_checker<\n      char, static_cast<int>(sizeof...(T)), num_static_named_args,\n      num_static_named_args != detail::count_named_args<T...>()>;\n\n  using arg_pack = detail::arg_pack<T...>;\n\n public:\n  string_view str;\n  using t = fstring;\n\n  // Reports a compile-time error if S is not a valid format string for T.\n  template <size_t N>\n  FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const char (&s)[N]) : str(s, N - 1) {\n    using namespace detail;\n    static_assert(count<(is_view<remove_cvref_t<T>>::value &&\n                         std::is_reference<T>::value)...>() == 0,\n                  \"passing views as lvalues is disallowed\");\n    if (FMT_USE_CONSTEVAL) parse_format_string<char>(s, checker(s, arg_pack()));\n#ifdef FMT_ENFORCE_COMPILE_STRING\n    static_assert(\n        FMT_USE_CONSTEVAL && sizeof(s) != 0,\n        \"FMT_ENFORCE_COMPILE_STRING requires format strings to use FMT_STRING\");\n#endif\n  }\n  template <typename S,\n            FMT_ENABLE_IF(std::is_convertible<const S&, string_view>::value)>\n  FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const S& s) : str(s) {\n    auto sv = string_view(str);\n    if (FMT_USE_CONSTEVAL)\n      detail::parse_format_string<char>(sv, checker(sv, arg_pack()));\n#ifdef FMT_ENFORCE_COMPILE_STRING\n    static_assert(\n        FMT_USE_CONSTEVAL && sizeof(s) != 0,\n        \"FMT_ENFORCE_COMPILE_STRING requires format strings to use FMT_STRING\");\n#endif\n  }\n  template <typename S,\n            FMT_ENABLE_IF(std::is_base_of<detail::compile_string, S>::value&&\n                              std::is_same<typename S::char_type, char>::value)>\n  FMT_ALWAYS_INLINE fstring(const S&) : str(S()) {\n    FMT_CONSTEXPR auto sv = string_view(S());\n    FMT_CONSTEXPR int unused =\n        (parse_format_string(sv, checker(sv, arg_pack())), 0);\n    detail::ignore_unused(unused);\n  }\n  fstring(runtime_format_string<> fmt) : str(fmt.str) {}\n\n  // Returning by reference generates better code in debug mode.\n  FMT_ALWAYS_INLINE operator const string_view&() const { return str; }\n  auto get() const -> string_view { return str; }\n};\n\ntemplate <typename... T> using format_string = typename fstring<T...>::t;\n\ntemplate <typename T, typename Char = char>\nusing is_formattable = bool_constant<!std::is_same<\n    detail::mapped_t<conditional_t<std::is_void<T>::value, int*, T>, Char>,\n    void>::value>;\n#ifdef __cpp_concepts\ntemplate <typename T, typename Char = char>\nconcept formattable = is_formattable<remove_reference_t<T>, Char>::value;\n#endif\n\n// A formatter specialization for natively supported types.\ntemplate <typename T, typename Char>\nstruct formatter<T, Char,\n                 enable_if_t<detail::type_constant<T, Char>::value !=\n                             detail::type::custom_type>>\n    : detail::native_formatter<T, Char, detail::type_constant<T, Char>::value> {\n};\n\n/**\n * Constructs an object that stores references to arguments and can be\n * implicitly converted to `format_args`. `Context` can be omitted in which case\n * it defaults to `context`. See `arg` for lifetime considerations.\n */\n// Take arguments by lvalue references to avoid some lifetime issues, e.g.\n//   auto args = make_format_args(std::string());\ntemplate <typename Context = context, typename... T,\n          int NUM_ARGS = sizeof...(T),\n          int NUM_NAMED_ARGS = detail::count_named_args<T...>(),\n          unsigned long long DESC = detail::make_descriptor<Context, T...>()>\nconstexpr FMT_ALWAYS_INLINE auto make_format_args(T&... args)\n    -> detail::format_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC> {\n  // Suppress warnings for pathological types convertible to detail::value.\n  FMT_PRAGMA_GCC(diagnostic ignored \"-Wconversion\")\n  return {{args...}};\n}\n\ntemplate <typename... T>\nusing vargs =\n    detail::format_arg_store<context, sizeof...(T),\n                             detail::count_named_args<T...>(),\n                             detail::make_descriptor<context, T...>()>;\n\n/**\n * Returns a named argument to be used in a formatting function.\n * It should only be used in a call to a formatting function.\n *\n * **Example**:\n *\n *     fmt::print(\"The answer is {answer}.\", fmt::arg(\"answer\", 42));\n */\ntemplate <typename Char, typename T>\ninline auto arg(const Char* name, const T& arg) -> detail::named_arg<Char, T> {\n  return {name, arg};\n}\n\n/// Formats a string and writes the output to `out`.\ntemplate <typename OutputIt,\n          FMT_ENABLE_IF(detail::is_output_iterator<remove_cvref_t<OutputIt>,\n                                                   char>::value)>\nauto vformat_to(OutputIt&& out, string_view fmt, format_args args)\n    -> remove_cvref_t<OutputIt> {\n  auto&& buf = detail::get_buffer<char>(out);\n  detail::vformat_to(buf, fmt, args, {});\n  return detail::get_iterator(buf, out);\n}\n\n/**\n * Formats `args` according to specifications in `fmt`, writes the result to\n * the output iterator `out` and returns the iterator past the end of the output\n * range. `format_to` does not append a terminating null character.\n *\n * **Example**:\n *\n *     auto out = std::vector<char>();\n *     fmt::format_to(std::back_inserter(out), \"{}\", 42);\n */\ntemplate <typename OutputIt, typename... T,\n          FMT_ENABLE_IF(detail::is_output_iterator<remove_cvref_t<OutputIt>,\n                                                   char>::value)>\nFMT_INLINE auto format_to(OutputIt&& out, format_string<T...> fmt, T&&... args)\n    -> remove_cvref_t<OutputIt> {\n  return vformat_to(out, fmt.str, vargs<T...>{{args...}});\n}\n\ntemplate <typename OutputIt> struct format_to_n_result {\n  /// Iterator past the end of the output range.\n  OutputIt out;\n  /// Total (not truncated) output size.\n  size_t size;\n};\n\ntemplate <typename OutputIt, typename... T,\n          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>\nauto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args)\n    -> format_to_n_result<OutputIt> {\n  using traits = detail::fixed_buffer_traits;\n  auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n);\n  detail::vformat_to(buf, fmt, args, {});\n  return {buf.out(), buf.count()};\n}\n\n/**\n * Formats `args` according to specifications in `fmt`, writes up to `n`\n * characters of the result to the output iterator `out` and returns the total\n * (not truncated) output size and the iterator past the end of the output\n * range. `format_to_n` does not append a terminating null character.\n */\ntemplate <typename OutputIt, typename... T,\n          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>\nFMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string<T...> fmt,\n                            T&&... args) -> format_to_n_result<OutputIt> {\n  return vformat_to_n(out, n, fmt.str, vargs<T...>{{args...}});\n}\n\nstruct format_to_result {\n  /// Pointer to just after the last successful write in the array.\n  char* out;\n  /// Specifies if the output was truncated.\n  bool truncated;\n\n  FMT_CONSTEXPR operator char*() const {\n    // Report truncation to prevent silent data loss.\n    if (truncated) report_error(\"output is truncated\");\n    return out;\n  }\n};\n\ntemplate <size_t N>\nauto vformat_to(char (&out)[N], string_view fmt, format_args args)\n    -> format_to_result {\n  auto result = vformat_to_n(out, N, fmt, args);\n  return {result.out, result.size > N};\n}\n\ntemplate <size_t N, typename... T>\nFMT_INLINE auto format_to(char (&out)[N], format_string<T...> fmt, T&&... args)\n    -> format_to_result {\n  auto result = vformat_to_n(out, N, fmt.str, vargs<T...>{{args...}});\n  return {result.out, result.size > N};\n}\n\n/// Returns the number of chars in the output of `format(fmt, args...)`.\ntemplate <typename... T>\nFMT_NODISCARD FMT_INLINE auto formatted_size(format_string<T...> fmt,\n                                             T&&... args) -> size_t {\n  auto buf = detail::counting_buffer<>();\n  detail::vformat_to(buf, fmt.str, vargs<T...>{{args...}}, {});\n  return buf.count();\n}\n\nFMT_API void vprint(string_view fmt, format_args args);\nFMT_API void vprint(FILE* f, string_view fmt, format_args args);\nFMT_API void vprintln(FILE* f, string_view fmt, format_args args);\nFMT_API void vprint_buffered(FILE* f, string_view fmt, format_args args);\n\n/**\n * Formats `args` according to specifications in `fmt` and writes the output\n * to `stdout`.\n *\n * **Example**:\n *\n *     fmt::print(\"The answer is {}.\", 42);\n */\ntemplate <typename... T>\nFMT_INLINE void print(format_string<T...> fmt, T&&... args) {\n  vargs<T...> va = {{args...}};\n  if (detail::const_check(!detail::use_utf8))\n    return detail::vprint_mojibake(stdout, fmt.str, va, false);\n  return detail::is_locking<T...>() ? vprint_buffered(stdout, fmt.str, va)\n                                    : vprint(fmt.str, va);\n}\n\n/**\n * Formats `args` according to specifications in `fmt` and writes the\n * output to the file `f`.\n *\n * **Example**:\n *\n *     fmt::print(stderr, \"Don't {}!\", \"panic\");\n */\ntemplate <typename... T>\nFMT_INLINE void print(FILE* f, format_string<T...> fmt, T&&... args) {\n  vargs<T...> va = {{args...}};\n  if (detail::const_check(!detail::use_utf8))\n    return detail::vprint_mojibake(f, fmt.str, va, false);\n  return detail::is_locking<T...>() ? vprint_buffered(f, fmt.str, va)\n                                    : vprint(f, fmt.str, va);\n}\n\n/// Formats `args` according to specifications in `fmt` and writes the output\n/// to the file `f` followed by a newline.\ntemplate <typename... T>\nFMT_INLINE void println(FILE* f, format_string<T...> fmt, T&&... args) {\n  vargs<T...> va = {{args...}};\n  return detail::const_check(detail::use_utf8)\n             ? vprintln(f, fmt.str, va)\n             : detail::vprint_mojibake(f, fmt.str, va, true);\n}\n\n/// Formats `args` according to specifications in `fmt` and writes the output\n/// to `stdout` followed by a newline.\ntemplate <typename... T>\nFMT_INLINE void println(format_string<T...> fmt, T&&... args) {\n  return fmt::println(stdout, fmt, static_cast<T&&>(args)...);\n}\n\nFMT_PRAGMA_CLANG(diagnostic pop)\nFMT_PRAGMA_GCC(pop_options)\nFMT_END_EXPORT\nFMT_END_NAMESPACE\n\n#ifdef FMT_HEADER_ONLY\n#  include \"format.h\"\n#endif\n#endif  // FMT_BASE_H_\n"
  },
  {
    "path": "include/fmt/chrono.h",
    "content": "// Formatting library for C++ - chrono support\n//\n// Copyright (c) 2012 - present, Victor Zverovich\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_CHRONO_H_\n#define FMT_CHRONO_H_\n\n#ifndef FMT_MODULE\n#  include <algorithm>\n#  include <chrono>\n#  include <cmath>    // std::isfinite\n#  include <cstring>  // std::memcpy\n#  include <ctime>\n#  include <iterator>\n#  include <locale>\n#  include <ostream>\n#  include <type_traits>\n#endif\n\n#include \"format.h\"\n\nFMT_BEGIN_NAMESPACE\n\n// Enable safe chrono durations, unless explicitly disabled.\n#ifndef FMT_SAFE_DURATION_CAST\n#  define FMT_SAFE_DURATION_CAST 1\n#endif\n#if FMT_SAFE_DURATION_CAST\n\n// For conversion between std::chrono::durations without undefined\n// behaviour or erroneous results.\n// This is a stripped down version of duration_cast, for inclusion in fmt.\n// See https://github.com/pauldreik/safe_duration_cast\n//\n// Copyright Paul Dreik 2019\nnamespace safe_duration_cast {\n\n// DEPRECATED!\ntemplate <typename To, typename From,\n          FMT_ENABLE_IF(!std::is_same<From, To>::value &&\n                        std::numeric_limits<From>::is_signed ==\n                            std::numeric_limits<To>::is_signed)>\nFMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)\n    -> To {\n  ec = 0;\n  using F = std::numeric_limits<From>;\n  using T = std::numeric_limits<To>;\n  static_assert(F::is_integer, \"From must be integral\");\n  static_assert(T::is_integer, \"To must be integral\");\n\n  // A and B are both signed, or both unsigned.\n  if (detail::const_check(F::digits <= T::digits)) {\n    // From fits in To without any problem.\n  } else {\n    // From does not always fit in To, resort to a dynamic check.\n    if (from < (T::min)() || from > (T::max)()) {\n      // outside range.\n      ec = 1;\n      return {};\n    }\n  }\n  return static_cast<To>(from);\n}\n\n/// Converts From to To, without loss. If the dynamic value of from\n/// can't be converted to To without loss, ec is set.\ntemplate <typename To, typename From,\n          FMT_ENABLE_IF(!std::is_same<From, To>::value &&\n                        std::numeric_limits<From>::is_signed !=\n                            std::numeric_limits<To>::is_signed)>\nFMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)\n    -> To {\n  ec = 0;\n  using F = std::numeric_limits<From>;\n  using T = std::numeric_limits<To>;\n  static_assert(F::is_integer, \"From must be integral\");\n  static_assert(T::is_integer, \"To must be integral\");\n\n  if (detail::const_check(F::is_signed && !T::is_signed)) {\n    // From may be negative, not allowed!\n    if (fmt::detail::is_negative(from)) {\n      ec = 1;\n      return {};\n    }\n    // From is positive. Can it always fit in To?\n    if (detail::const_check(F::digits > T::digits) &&\n        from > static_cast<From>(detail::max_value<To>())) {\n      ec = 1;\n      return {};\n    }\n  }\n\n  if (detail::const_check(!F::is_signed && T::is_signed &&\n                          F::digits >= T::digits) &&\n      from > static_cast<From>(detail::max_value<To>())) {\n    ec = 1;\n    return {};\n  }\n  return static_cast<To>(from);  // Lossless conversion.\n}\n\ntemplate <typename To, typename From,\n          FMT_ENABLE_IF(std::is_same<From, To>::value)>\nFMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)\n    -> To {\n  ec = 0;\n  return from;\n}  // function\n\n// clang-format off\n/**\n * converts From to To if possible, otherwise ec is set.\n *\n * input                            |    output\n * ---------------------------------|---------------\n * NaN                              | NaN\n * Inf                              | Inf\n * normal, fits in output           | converted (possibly lossy)\n * normal, does not fit in output   | ec is set\n * subnormal                        | best effort\n * -Inf                             | -Inf\n */\n// clang-format on\ntemplate <typename To, typename From,\n          FMT_ENABLE_IF(!std::is_same<From, To>::value)>\nFMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To {\n  ec = 0;\n  using T = std::numeric_limits<To>;\n  static_assert(std::is_floating_point<From>::value, \"From must be floating\");\n  static_assert(std::is_floating_point<To>::value, \"To must be floating\");\n\n  // catch the only happy case\n  if (std::isfinite(from)) {\n    if (from >= T::lowest() && from <= (T::max)()) {\n      return static_cast<To>(from);\n    }\n    // not within range.\n    ec = 1;\n    return {};\n  }\n\n  // nan and inf will be preserved\n  return static_cast<To>(from);\n}  // function\n\ntemplate <typename To, typename From,\n          FMT_ENABLE_IF(std::is_same<From, To>::value)>\nFMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To {\n  ec = 0;\n  static_assert(std::is_floating_point<From>::value, \"From must be floating\");\n  return from;\n}\n\n/// Safe duration_cast between floating point durations\ntemplate <typename To, typename FromRep, typename FromPeriod,\n          FMT_ENABLE_IF(std::is_floating_point<FromRep>::value),\n          FMT_ENABLE_IF(std::is_floating_point<typename To::rep>::value)>\nauto safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,\n                        int& ec) -> To {\n  using From = std::chrono::duration<FromRep, FromPeriod>;\n  ec = 0;\n\n  // the basic idea is that we need to convert from count() in the from type\n  // to count() in the To type, by multiplying it with this:\n  struct Factor\n      : std::ratio_divide<typename From::period, typename To::period> {};\n\n  static_assert(Factor::num > 0, \"num must be positive\");\n  static_assert(Factor::den > 0, \"den must be positive\");\n\n  // the conversion is like this: multiply from.count() with Factor::num\n  // /Factor::den and convert it to To::rep, all this without\n  // overflow/underflow. let's start by finding a suitable type that can hold\n  // both To, From and Factor::num\n  using IntermediateRep =\n      typename std::common_type<typename From::rep, typename To::rep,\n                                decltype(Factor::num)>::type;\n\n  // force conversion of From::rep -> IntermediateRep to be safe,\n  // even if it will never happen be narrowing in this context.\n  IntermediateRep count =\n      safe_float_conversion<IntermediateRep>(from.count(), ec);\n  if (ec) {\n    return {};\n  }\n\n  // multiply with Factor::num without overflow or underflow\n  if (detail::const_check(Factor::num != 1)) {\n    constexpr auto max1 = detail::max_value<IntermediateRep>() /\n                          static_cast<IntermediateRep>(Factor::num);\n    if (count > max1) {\n      ec = 1;\n      return {};\n    }\n    constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() /\n                          static_cast<IntermediateRep>(Factor::num);\n    if (count < min1) {\n      ec = 1;\n      return {};\n    }\n    count *= static_cast<IntermediateRep>(Factor::num);\n  }\n\n  // this can't go wrong, right? den>0 is checked earlier.\n  if (detail::const_check(Factor::den != 1)) {\n    using common_t = typename std::common_type<IntermediateRep, intmax_t>::type;\n    count /= static_cast<common_t>(Factor::den);\n  }\n\n  // convert to the to type, safely\n  using ToRep = typename To::rep;\n\n  const ToRep tocount = safe_float_conversion<ToRep>(count, ec);\n  if (ec) {\n    return {};\n  }\n  return To{tocount};\n}\n}  // namespace safe_duration_cast\n#endif\n\nnamespace detail {\n\n// Check if std::chrono::utc_time is available.\n#ifdef FMT_USE_UTC_TIME\n// Use the provided definition.\n#elif defined(__cpp_lib_chrono)\n#  define FMT_USE_UTC_TIME (__cpp_lib_chrono >= 201907L)\n#else\n#  define FMT_USE_UTC_TIME 0\n#endif\n#if FMT_USE_UTC_TIME\nusing utc_clock = std::chrono::utc_clock;\n#else\nstruct utc_clock {\n  template <typename T> void to_sys(T);\n};\n#endif\n\n// Check if std::chrono::local_time is available.\n#ifdef FMT_USE_LOCAL_TIME\n// Use the provided definition.\n#elif defined(__cpp_lib_chrono)\n#  define FMT_USE_LOCAL_TIME (__cpp_lib_chrono >= 201907L)\n#else\n#  define FMT_USE_LOCAL_TIME 0\n#endif\n#if FMT_USE_LOCAL_TIME\nusing local_t = std::chrono::local_t;\n#else\nstruct local_t {};\n#endif\n\n}  // namespace detail\n\ntemplate <typename Duration>\nusing sys_time = std::chrono::time_point<std::chrono::system_clock, Duration>;\n\ntemplate <typename Duration>\nusing utc_time = std::chrono::time_point<detail::utc_clock, Duration>;\n\ntemplate <class Duration>\nusing local_time = std::chrono::time_point<detail::local_t, Duration>;\n\nnamespace detail {\n\n// Prevents expansion of a preceding token as a function-style macro.\n// Usage: f FMT_NOMACRO()\n#define FMT_NOMACRO\n\ntemplate <typename T = void> struct null {};\ninline auto gmtime_r(...) -> null<> { return null<>(); }\ninline auto gmtime_s(...) -> null<> { return null<>(); }\n\n// It is defined here and not in ostream.h because the latter has expensive\n// includes.\ntemplate <typename StreamBuf> class formatbuf : public StreamBuf {\n private:\n  using char_type = typename StreamBuf::char_type;\n  using streamsize = decltype(std::declval<StreamBuf>().sputn(nullptr, 0));\n  using int_type = typename StreamBuf::int_type;\n  using traits_type = typename StreamBuf::traits_type;\n\n  buffer<char_type>& buffer_;\n\n public:\n  explicit formatbuf(buffer<char_type>& buf) : buffer_(buf) {}\n\n protected:\n  // The put area is always empty. This makes the implementation simpler and has\n  // the advantage that the streambuf and the buffer are always in sync and\n  // sputc never writes into uninitialized memory. A disadvantage is that each\n  // call to sputc always results in a (virtual) call to overflow. There is no\n  // disadvantage here for sputn since this always results in a call to xsputn.\n\n  auto overflow(int_type ch) -> int_type override {\n    if (!traits_type::eq_int_type(ch, traits_type::eof()))\n      buffer_.push_back(static_cast<char_type>(ch));\n    return ch;\n  }\n\n  auto xsputn(const char_type* s, streamsize count) -> streamsize override {\n    buffer_.append(s, s + count);\n    return count;\n  }\n};\n\ninline auto get_classic_locale() -> const std::locale& {\n  static const auto& locale = std::locale::classic();\n  return locale;\n}\n\ntemplate <typename CodeUnit> struct codecvt_result {\n  static constexpr size_t max_size = 32;\n  CodeUnit buf[max_size];\n  CodeUnit* end;\n};\n\ntemplate <typename CodeUnit>\nvoid write_codecvt(codecvt_result<CodeUnit>& out, string_view in,\n                   const std::locale& loc) {\n  FMT_PRAGMA_CLANG(diagnostic push)\n  FMT_PRAGMA_CLANG(diagnostic ignored \"-Wdeprecated\")\n  auto& f = std::use_facet<std::codecvt<CodeUnit, char, std::mbstate_t>>(loc);\n  FMT_PRAGMA_CLANG(diagnostic pop)\n  auto mb = std::mbstate_t();\n  const char* from_next = nullptr;\n  auto result = f.in(mb, in.begin(), in.end(), from_next, std::begin(out.buf),\n                     std::end(out.buf), out.end);\n  if (result != std::codecvt_base::ok)\n    FMT_THROW(format_error(\"failed to format time\"));\n}\n\ntemplate <typename OutputIt>\nauto write_encoded_tm_str(OutputIt out, string_view in, const std::locale& loc)\n    -> OutputIt {\n  if (const_check(detail::use_utf8) && loc != get_classic_locale()) {\n    // char16_t and char32_t codecvts are broken in MSVC (linkage errors) and\n    // gcc-4.\n#if FMT_MSC_VERSION != 0 ||  \\\n    (defined(__GLIBCXX__) && \\\n     (!defined(_GLIBCXX_USE_DUAL_ABI) || _GLIBCXX_USE_DUAL_ABI == 0))\n    // The _GLIBCXX_USE_DUAL_ABI macro is always defined in libstdc++ from gcc-5\n    // and newer.\n    using code_unit = wchar_t;\n#else\n    using code_unit = char32_t;\n#endif\n\n    using unit_t = codecvt_result<code_unit>;\n    unit_t unit;\n    write_codecvt(unit, in, loc);\n    // In UTF-8 is used one to four one-byte code units.\n    auto u =\n        to_utf8<code_unit, basic_memory_buffer<char, unit_t::max_size * 4>>();\n    if (!u.convert({unit.buf, to_unsigned(unit.end - unit.buf)}))\n      FMT_THROW(format_error(\"failed to format time\"));\n    return copy<char>(u.c_str(), u.c_str() + u.size(), out);\n  }\n  return copy<char>(in.data(), in.data() + in.size(), out);\n}\n\ntemplate <typename Char, typename OutputIt,\n          FMT_ENABLE_IF(!std::is_same<Char, char>::value)>\nauto write_tm_str(OutputIt out, string_view sv, const std::locale& loc)\n    -> OutputIt {\n  codecvt_result<Char> unit;\n  write_codecvt(unit, sv, loc);\n  return copy<Char>(unit.buf, unit.end, out);\n}\n\ntemplate <typename Char, typename OutputIt,\n          FMT_ENABLE_IF(std::is_same<Char, char>::value)>\nauto write_tm_str(OutputIt out, string_view sv, const std::locale& loc)\n    -> OutputIt {\n  return write_encoded_tm_str(out, sv, loc);\n}\n\ntemplate <typename Char>\ninline void do_write(buffer<Char>& buf, const std::tm& time,\n                     const std::locale& loc, char format, char modifier) {\n  auto&& format_buf = formatbuf<std::basic_streambuf<Char>>(buf);\n  auto&& os = std::basic_ostream<Char>(&format_buf);\n  os.imbue(loc);\n  const auto& facet = std::use_facet<std::time_put<Char>>(loc);\n  auto end = facet.put(os, os, Char(' '), &time, format, modifier);\n  if (end.failed()) FMT_THROW(format_error(\"failed to format time\"));\n}\n\ntemplate <typename Char, typename OutputIt,\n          FMT_ENABLE_IF(!std::is_same<Char, char>::value)>\nauto write(OutputIt out, const std::tm& time, const std::locale& loc,\n           char format, char modifier = 0) -> OutputIt {\n  auto&& buf = get_buffer<Char>(out);\n  do_write<Char>(buf, time, loc, format, modifier);\n  return get_iterator(buf, out);\n}\n\ntemplate <typename Char, typename OutputIt,\n          FMT_ENABLE_IF(std::is_same<Char, char>::value)>\nauto write(OutputIt out, const std::tm& time, const std::locale& loc,\n           char format, char modifier = 0) -> OutputIt {\n  auto&& buf = basic_memory_buffer<Char>();\n  do_write<char>(buf, time, loc, format, modifier);\n  return write_encoded_tm_str(out, string_view(buf.data(), buf.size()), loc);\n}\n\ntemplate <typename T, typename U>\nusing is_similar_arithmetic_type =\n    bool_constant<(std::is_integral<T>::value && std::is_integral<U>::value) ||\n                  (std::is_floating_point<T>::value &&\n                   std::is_floating_point<U>::value)>;\n\nFMT_NORETURN inline void throw_duration_error() {\n  FMT_THROW(format_error(\"cannot format duration\"));\n}\n\n// Cast one integral duration to another with an overflow check.\ntemplate <typename To, typename FromRep, typename FromPeriod,\n          FMT_ENABLE_IF(std::is_integral<FromRep>::value&&\n                            std::is_integral<typename To::rep>::value)>\nauto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {\n#if !FMT_SAFE_DURATION_CAST\n  return std::chrono::duration_cast<To>(from);\n#else\n  // The conversion factor: to.count() == factor * from.count().\n  using factor = std::ratio_divide<FromPeriod, typename To::period>;\n\n  using common_rep = typename std::common_type<FromRep, typename To::rep,\n                                               decltype(factor::num)>::type;\n  common_rep count = from.count();  // This conversion is lossless.\n\n  // Multiply from.count() by factor and check for overflow.\n  if (const_check(factor::num != 1)) {\n    if (count > max_value<common_rep>() / factor::num) throw_duration_error();\n    const auto min = (std::numeric_limits<common_rep>::min)() / factor::num;\n    if (const_check(!std::is_unsigned<common_rep>::value) && count < min)\n      throw_duration_error();\n    count *= factor::num;\n  }\n  if (const_check(factor::den != 1)) count /= factor::den;\n  int ec = 0;\n  auto to =\n      To(safe_duration_cast::lossless_integral_conversion<typename To::rep>(\n          count, ec));\n  if (ec) throw_duration_error();\n  return to;\n#endif\n}\n\ntemplate <typename To, typename FromRep, typename FromPeriod,\n          FMT_ENABLE_IF(std::is_floating_point<FromRep>::value&&\n                            std::is_floating_point<typename To::rep>::value)>\nauto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {\n#if FMT_SAFE_DURATION_CAST\n  // Preserve infinity and NaN.\n  if (!isfinite(from.count())) return static_cast<To>(from.count());\n  // Throwing version of safe_duration_cast is only available for\n  // integer to integer or float to float casts.\n  int ec;\n  To to = safe_duration_cast::safe_duration_cast<To>(from, ec);\n  if (ec) throw_duration_error();\n  return to;\n#else\n  // Standard duration cast, may overflow.\n  return std::chrono::duration_cast<To>(from);\n#endif\n}\n\ntemplate <typename To, typename FromRep, typename FromPeriod,\n          FMT_ENABLE_IF(\n              !is_similar_arithmetic_type<FromRep, typename To::rep>::value)>\nauto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {\n  // Mixed integer <-> float cast is not supported by safe duration_cast.\n  return std::chrono::duration_cast<To>(from);\n}\n\ntemplate <typename Duration>\nauto to_time_t(sys_time<Duration> time_point) -> std::time_t {\n  // Cannot use std::chrono::system_clock::to_time_t since this would first\n  // require a cast to std::chrono::system_clock::time_point, which could\n  // overflow.\n  return detail::duration_cast<std::chrono::duration<std::time_t>>(\n             time_point.time_since_epoch())\n      .count();\n}\n\n}  // namespace detail\n\nFMT_BEGIN_EXPORT\n\n/**\n * Converts given time since epoch as `std::time_t` value into calendar time,\n * expressed in Coordinated Universal Time (UTC). Unlike `std::gmtime`, this\n * function is thread-safe on most platforms.\n */\ninline auto gmtime(std::time_t time) -> std::tm {\n  struct dispatcher {\n    std::time_t time_;\n    std::tm tm_;\n\n    inline dispatcher(std::time_t t) : time_(t) {}\n\n    inline auto run() -> bool {\n      using namespace fmt::detail;\n      return handle(gmtime_r(&time_, &tm_));\n    }\n\n    inline auto handle(std::tm* tm) -> bool { return tm != nullptr; }\n\n    inline auto handle(detail::null<>) -> bool {\n      using namespace fmt::detail;\n      return fallback(gmtime_s(&tm_, &time_));\n    }\n\n    inline auto fallback(int res) -> bool { return res == 0; }\n\n#if !FMT_MSC_VERSION\n    inline auto fallback(detail::null<>) -> bool {\n      std::tm* tm = std::gmtime(&time_);\n      if (tm) tm_ = *tm;\n      return tm != nullptr;\n    }\n#endif\n  };\n  auto gt = dispatcher(time);\n  // Too big time values may be unsupported.\n  if (!gt.run()) FMT_THROW(format_error(\"time_t value out of range\"));\n  return gt.tm_;\n}\n\ntemplate <typename Duration>\ninline auto gmtime(sys_time<Duration> time_point) -> std::tm {\n  return gmtime(detail::to_time_t(time_point));\n}\n\nnamespace detail {\n\n// Writes two-digit numbers a, b and c separated by sep to buf.\n// The method by Pavel Novikov based on\n// https://johnnylee-sde.github.io/Fast-unsigned-integer-to-time-string/.\ninline void write_digit2_separated(char* buf, unsigned a, unsigned b,\n                                   unsigned c, char sep) {\n  unsigned long long digits =\n      a | (b << 24) | (static_cast<unsigned long long>(c) << 48);\n  // Convert each value to BCD.\n  // We have x = a * 10 + b and we want to convert it to BCD y = a * 16 + b.\n  // The difference is\n  //   y - x = a * 6\n  // a can be found from x:\n  //   a = floor(x / 10)\n  // then\n  //   y = x + a * 6 = x + floor(x / 10) * 6\n  // floor(x / 10) is (x * 205) >> 11 (needs 16 bits).\n  digits += (((digits * 205) >> 11) & 0x000f00000f00000f) * 6;\n  // Put low nibbles to high bytes and high nibbles to low bytes.\n  digits = ((digits & 0x00f00000f00000f0) >> 4) |\n           ((digits & 0x000f00000f00000f) << 8);\n  auto usep = static_cast<unsigned long long>(sep);\n  // Add ASCII '0' to each digit byte and insert separators.\n  digits |= 0x3030003030003030 | (usep << 16) | (usep << 40);\n\n  constexpr size_t len = 8;\n  if (const_check(is_big_endian())) {\n    char tmp[len];\n    std::memcpy(tmp, &digits, len);\n    std::reverse_copy(tmp, tmp + len, buf);\n  } else {\n    std::memcpy(buf, &digits, len);\n  }\n}\n\ntemplate <typename Period>\nFMT_CONSTEXPR inline auto get_units() -> const char* {\n  if (std::is_same<Period, std::atto>::value) return \"as\";\n  if (std::is_same<Period, std::femto>::value) return \"fs\";\n  if (std::is_same<Period, std::pico>::value) return \"ps\";\n  if (std::is_same<Period, std::nano>::value) return \"ns\";\n  if (std::is_same<Period, std::micro>::value)\n    return detail::use_utf8 ? \"µs\" : \"us\";\n  if (std::is_same<Period, std::milli>::value) return \"ms\";\n  if (std::is_same<Period, std::centi>::value) return \"cs\";\n  if (std::is_same<Period, std::deci>::value) return \"ds\";\n  if (std::is_same<Period, std::ratio<1>>::value) return \"s\";\n  if (std::is_same<Period, std::deca>::value) return \"das\";\n  if (std::is_same<Period, std::hecto>::value) return \"hs\";\n  if (std::is_same<Period, std::kilo>::value) return \"ks\";\n  if (std::is_same<Period, std::mega>::value) return \"Ms\";\n  if (std::is_same<Period, std::giga>::value) return \"Gs\";\n  if (std::is_same<Period, std::tera>::value) return \"Ts\";\n  if (std::is_same<Period, std::peta>::value) return \"Ps\";\n  if (std::is_same<Period, std::exa>::value) return \"Es\";\n  if (std::is_same<Period, std::ratio<60>>::value) return \"min\";\n  if (std::is_same<Period, std::ratio<3600>>::value) return \"h\";\n  if (std::is_same<Period, std::ratio<86400>>::value) return \"d\";\n  return nullptr;\n}\n\nenum class numeric_system {\n  standard,\n  // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale.\n  alternative\n};\n\n// Glibc extensions for formatting numeric values.\nenum class pad_type {\n  // Pad a numeric result string with zeros (the default).\n  zero,\n  // Do not pad a numeric result string.\n  none,\n  // Pad a numeric result string with spaces.\n  space,\n};\n\ntemplate <typename OutputIt>\nauto write_padding(OutputIt out, pad_type pad, int width) -> OutputIt {\n  if (pad == pad_type::none) return out;\n  return detail::fill_n(out, width, pad == pad_type::space ? ' ' : '0');\n}\n\ntemplate <typename OutputIt>\nauto write_padding(OutputIt out, pad_type pad) -> OutputIt {\n  if (pad != pad_type::none) *out++ = pad == pad_type::space ? ' ' : '0';\n  return out;\n}\n\n// Parses a put_time-like format string and invokes handler actions.\ntemplate <typename Char, typename Handler>\nFMT_CONSTEXPR auto parse_chrono_format(const Char* begin, const Char* end,\n                                       Handler&& handler) -> const Char* {\n  if (begin == end || *begin == '}') return begin;\n  if (*begin != '%') FMT_THROW(format_error(\"invalid format\"));\n  auto ptr = begin;\n  while (ptr != end) {\n    pad_type pad = pad_type::zero;\n    auto c = *ptr;\n    if (c == '}') break;\n    if (c != '%') {\n      ++ptr;\n      continue;\n    }\n    if (begin != ptr) handler.on_text(begin, ptr);\n    ++ptr;  // consume '%'\n    if (ptr == end) FMT_THROW(format_error(\"invalid format\"));\n    c = *ptr;\n    switch (c) {\n    case '_':\n      pad = pad_type::space;\n      ++ptr;\n      break;\n    case '-':\n      pad = pad_type::none;\n      ++ptr;\n      break;\n    }\n    if (ptr == end) FMT_THROW(format_error(\"invalid format\"));\n    c = *ptr++;\n    switch (c) {\n    case '%': handler.on_text(ptr - 1, ptr); break;\n    case 'n': {\n      const Char newline[] = {'\\n'};\n      handler.on_text(newline, newline + 1);\n      break;\n    }\n    case 't': {\n      const Char tab[] = {'\\t'};\n      handler.on_text(tab, tab + 1);\n      break;\n    }\n    // Year:\n    case 'Y': handler.on_year(numeric_system::standard, pad); break;\n    case 'y': handler.on_short_year(numeric_system::standard); break;\n    case 'C': handler.on_century(numeric_system::standard); break;\n    case 'G': handler.on_iso_week_based_year(); break;\n    case 'g': handler.on_iso_week_based_short_year(); break;\n    // Day of the week:\n    case 'a': handler.on_abbr_weekday(); break;\n    case 'A': handler.on_full_weekday(); break;\n    case 'w': handler.on_dec0_weekday(numeric_system::standard); break;\n    case 'u': handler.on_dec1_weekday(numeric_system::standard); break;\n    // Month:\n    case 'b':\n    case 'h': handler.on_abbr_month(); break;\n    case 'B': handler.on_full_month(); break;\n    case 'm': handler.on_dec_month(numeric_system::standard, pad); break;\n    // Day of the year/month:\n    case 'U':\n      handler.on_dec0_week_of_year(numeric_system::standard, pad);\n      break;\n    case 'W':\n      handler.on_dec1_week_of_year(numeric_system::standard, pad);\n      break;\n    case 'V': handler.on_iso_week_of_year(numeric_system::standard, pad); break;\n    case 'j': handler.on_day_of_year(pad); break;\n    case 'd': handler.on_day_of_month(numeric_system::standard, pad); break;\n    case 'e':\n      handler.on_day_of_month(numeric_system::standard, pad_type::space);\n      break;\n    // Hour, minute, second:\n    case 'H': handler.on_24_hour(numeric_system::standard, pad); break;\n    case 'I': handler.on_12_hour(numeric_system::standard, pad); break;\n    case 'M': handler.on_minute(numeric_system::standard, pad); break;\n    case 'S': handler.on_second(numeric_system::standard, pad); break;\n    // Other:\n    case 'c': handler.on_datetime(numeric_system::standard); break;\n    case 'x': handler.on_loc_date(numeric_system::standard); break;\n    case 'X': handler.on_loc_time(numeric_system::standard); break;\n    case 'D': handler.on_us_date(); break;\n    case 'F': handler.on_iso_date(); break;\n    case 'r': handler.on_12_hour_time(); break;\n    case 'R': handler.on_24_hour_time(); break;\n    case 'T': handler.on_iso_time(); break;\n    case 'p': handler.on_am_pm(); break;\n    case 'Q': handler.on_duration_value(); break;\n    case 'q': handler.on_duration_unit(); break;\n    case 'z': handler.on_utc_offset(numeric_system::standard); break;\n    case 'Z': handler.on_tz_name(); break;\n    // Alternative representation:\n    case 'E': {\n      if (ptr == end) FMT_THROW(format_error(\"invalid format\"));\n      c = *ptr++;\n      switch (c) {\n      case 'Y': handler.on_year(numeric_system::alternative, pad); break;\n      case 'y': handler.on_offset_year(); break;\n      case 'C': handler.on_century(numeric_system::alternative); break;\n      case 'c': handler.on_datetime(numeric_system::alternative); break;\n      case 'x': handler.on_loc_date(numeric_system::alternative); break;\n      case 'X': handler.on_loc_time(numeric_system::alternative); break;\n      case 'z': handler.on_utc_offset(numeric_system::alternative); break;\n      default:  FMT_THROW(format_error(\"invalid format\"));\n      }\n      break;\n    }\n    case 'O':\n      if (ptr == end) FMT_THROW(format_error(\"invalid format\"));\n      c = *ptr++;\n      switch (c) {\n      case 'y': handler.on_short_year(numeric_system::alternative); break;\n      case 'm': handler.on_dec_month(numeric_system::alternative, pad); break;\n      case 'U':\n        handler.on_dec0_week_of_year(numeric_system::alternative, pad);\n        break;\n      case 'W':\n        handler.on_dec1_week_of_year(numeric_system::alternative, pad);\n        break;\n      case 'V':\n        handler.on_iso_week_of_year(numeric_system::alternative, pad);\n        break;\n      case 'd':\n        handler.on_day_of_month(numeric_system::alternative, pad);\n        break;\n      case 'e':\n        handler.on_day_of_month(numeric_system::alternative, pad_type::space);\n        break;\n      case 'w': handler.on_dec0_weekday(numeric_system::alternative); break;\n      case 'u': handler.on_dec1_weekday(numeric_system::alternative); break;\n      case 'H': handler.on_24_hour(numeric_system::alternative, pad); break;\n      case 'I': handler.on_12_hour(numeric_system::alternative, pad); break;\n      case 'M': handler.on_minute(numeric_system::alternative, pad); break;\n      case 'S': handler.on_second(numeric_system::alternative, pad); break;\n      case 'z': handler.on_utc_offset(numeric_system::alternative); break;\n      default:  FMT_THROW(format_error(\"invalid format\"));\n      }\n      break;\n    default: FMT_THROW(format_error(\"invalid format\"));\n    }\n    begin = ptr;\n  }\n  if (begin != ptr) handler.on_text(begin, ptr);\n  return ptr;\n}\n\ntemplate <typename Derived> struct null_chrono_spec_handler {\n  FMT_CONSTEXPR void unsupported() {\n    static_cast<Derived*>(this)->unsupported();\n  }\n  FMT_CONSTEXPR void on_year(numeric_system, pad_type) { unsupported(); }\n  FMT_CONSTEXPR void on_short_year(numeric_system) { unsupported(); }\n  FMT_CONSTEXPR void on_offset_year() { unsupported(); }\n  FMT_CONSTEXPR void on_century(numeric_system) { unsupported(); }\n  FMT_CONSTEXPR void on_iso_week_based_year() { unsupported(); }\n  FMT_CONSTEXPR void on_iso_week_based_short_year() { unsupported(); }\n  FMT_CONSTEXPR void on_abbr_weekday() { unsupported(); }\n  FMT_CONSTEXPR void on_full_weekday() { unsupported(); }\n  FMT_CONSTEXPR void on_dec0_weekday(numeric_system) { unsupported(); }\n  FMT_CONSTEXPR void on_dec1_weekday(numeric_system) { unsupported(); }\n  FMT_CONSTEXPR void on_abbr_month() { unsupported(); }\n  FMT_CONSTEXPR void on_full_month() { unsupported(); }\n  FMT_CONSTEXPR void on_dec_month(numeric_system, pad_type) { unsupported(); }\n  FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system, pad_type) {\n    unsupported();\n  }\n  FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system, pad_type) {\n    unsupported();\n  }\n  FMT_CONSTEXPR void on_iso_week_of_year(numeric_system, pad_type) {\n    unsupported();\n  }\n  FMT_CONSTEXPR void on_day_of_year(pad_type) { unsupported(); }\n  FMT_CONSTEXPR void on_day_of_month(numeric_system, pad_type) {\n    unsupported();\n  }\n  FMT_CONSTEXPR void on_24_hour(numeric_system) { unsupported(); }\n  FMT_CONSTEXPR void on_12_hour(numeric_system) { unsupported(); }\n  FMT_CONSTEXPR void on_minute(numeric_system) { unsupported(); }\n  FMT_CONSTEXPR void on_second(numeric_system) { unsupported(); }\n  FMT_CONSTEXPR void on_datetime(numeric_system) { unsupported(); }\n  FMT_CONSTEXPR void on_loc_date(numeric_system) { unsupported(); }\n  FMT_CONSTEXPR void on_loc_time(numeric_system) { unsupported(); }\n  FMT_CONSTEXPR void on_us_date() { unsupported(); }\n  FMT_CONSTEXPR void on_iso_date() { unsupported(); }\n  FMT_CONSTEXPR void on_12_hour_time() { unsupported(); }\n  FMT_CONSTEXPR void on_24_hour_time() { unsupported(); }\n  FMT_CONSTEXPR void on_iso_time() { unsupported(); }\n  FMT_CONSTEXPR void on_am_pm() { unsupported(); }\n  FMT_CONSTEXPR void on_duration_value() { unsupported(); }\n  FMT_CONSTEXPR void on_duration_unit() { unsupported(); }\n  FMT_CONSTEXPR void on_utc_offset(numeric_system) { unsupported(); }\n  FMT_CONSTEXPR void on_tz_name() { unsupported(); }\n};\n\nclass tm_format_checker : public null_chrono_spec_handler<tm_format_checker> {\n private:\n  bool has_timezone_ = false;\n\n public:\n  constexpr explicit tm_format_checker(bool has_timezone)\n      : has_timezone_(has_timezone) {}\n\n  FMT_NORETURN inline void unsupported() {\n    FMT_THROW(format_error(\"no format\"));\n  }\n\n  template <typename Char>\n  FMT_CONSTEXPR void on_text(const Char*, const Char*) {}\n  FMT_CONSTEXPR void on_year(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_short_year(numeric_system) {}\n  FMT_CONSTEXPR void on_offset_year() {}\n  FMT_CONSTEXPR void on_century(numeric_system) {}\n  FMT_CONSTEXPR void on_iso_week_based_year() {}\n  FMT_CONSTEXPR void on_iso_week_based_short_year() {}\n  FMT_CONSTEXPR void on_abbr_weekday() {}\n  FMT_CONSTEXPR void on_full_weekday() {}\n  FMT_CONSTEXPR void on_dec0_weekday(numeric_system) {}\n  FMT_CONSTEXPR void on_dec1_weekday(numeric_system) {}\n  FMT_CONSTEXPR void on_abbr_month() {}\n  FMT_CONSTEXPR void on_full_month() {}\n  FMT_CONSTEXPR void on_dec_month(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_iso_week_of_year(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_day_of_year(pad_type) {}\n  FMT_CONSTEXPR void on_day_of_month(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_second(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_datetime(numeric_system) {}\n  FMT_CONSTEXPR void on_loc_date(numeric_system) {}\n  FMT_CONSTEXPR void on_loc_time(numeric_system) {}\n  FMT_CONSTEXPR void on_us_date() {}\n  FMT_CONSTEXPR void on_iso_date() {}\n  FMT_CONSTEXPR void on_12_hour_time() {}\n  FMT_CONSTEXPR void on_24_hour_time() {}\n  FMT_CONSTEXPR void on_iso_time() {}\n  FMT_CONSTEXPR void on_am_pm() {}\n  FMT_CONSTEXPR void on_utc_offset(numeric_system) {\n    if (!has_timezone_) FMT_THROW(format_error(\"no timezone\"));\n  }\n  FMT_CONSTEXPR void on_tz_name() {\n    if (!has_timezone_) FMT_THROW(format_error(\"no timezone\"));\n  }\n};\n\ninline auto tm_wday_full_name(int wday) -> const char* {\n  static constexpr const char* full_name_list[] = {\n      \"Sunday\",   \"Monday\", \"Tuesday\", \"Wednesday\",\n      \"Thursday\", \"Friday\", \"Saturday\"};\n  return wday >= 0 && wday <= 6 ? full_name_list[wday] : \"?\";\n}\ninline auto tm_wday_short_name(int wday) -> const char* {\n  static constexpr const char* short_name_list[] = {\"Sun\", \"Mon\", \"Tue\", \"Wed\",\n                                                    \"Thu\", \"Fri\", \"Sat\"};\n  return wday >= 0 && wday <= 6 ? short_name_list[wday] : \"???\";\n}\n\ninline auto tm_mon_full_name(int mon) -> const char* {\n  static constexpr const char* full_name_list[] = {\n      \"January\", \"February\", \"March\",     \"April\",   \"May\",      \"June\",\n      \"July\",    \"August\",   \"September\", \"October\", \"November\", \"December\"};\n  return mon >= 0 && mon <= 11 ? full_name_list[mon] : \"?\";\n}\ninline auto tm_mon_short_name(int mon) -> const char* {\n  static constexpr const char* short_name_list[] = {\n      \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n      \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\",\n  };\n  return mon >= 0 && mon <= 11 ? short_name_list[mon] : \"???\";\n}\n\ntemplate <typename T, typename = void>\nstruct has_tm_gmtoff : std::false_type {};\ntemplate <typename T>\nstruct has_tm_gmtoff<T, void_t<decltype(T::tm_gmtoff)>> : std::true_type {};\n\ntemplate <typename T, typename = void> struct has_tm_zone : std::false_type {};\ntemplate <typename T>\nstruct has_tm_zone<T, void_t<decltype(T::tm_zone)>> : std::true_type {};\n\ntemplate <typename T, FMT_ENABLE_IF(has_tm_zone<T>::value)>\nauto set_tm_zone(T& time, char* tz) -> bool {\n  time.tm_zone = tz;\n  return true;\n}\ntemplate <typename T, FMT_ENABLE_IF(!has_tm_zone<T>::value)>\nauto set_tm_zone(T&, char*) -> bool {\n  return false;\n}\n\ninline auto utc() -> char* {\n  static char tz[] = \"UTC\";\n  return tz;\n}\n\n// Converts value to Int and checks that it's in the range [0, upper).\ntemplate <typename T, typename Int, FMT_ENABLE_IF(std::is_integral<T>::value)>\ninline auto to_nonnegative_int(T value, Int upper) -> Int {\n  if (!std::is_unsigned<Int>::value &&\n      (value < 0 || to_unsigned(value) > to_unsigned(upper))) {\n    FMT_THROW(format_error(\"chrono value is out of range\"));\n  }\n  return static_cast<Int>(value);\n}\ntemplate <typename T, typename Int, FMT_ENABLE_IF(!std::is_integral<T>::value)>\ninline auto to_nonnegative_int(T value, Int upper) -> Int {\n  auto int_value = static_cast<Int>(value);\n  if (int_value < 0 || value > static_cast<T>(upper))\n    FMT_THROW(format_error(\"invalid value\"));\n  return int_value;\n}\n\nconstexpr auto pow10(std::uint32_t n) -> long long {\n  return n == 0 ? 1 : 10 * pow10(n - 1);\n}\n\n// Counts the number of fractional digits in the range [0, 18] according to the\n// C++20 spec. If more than 18 fractional digits are required then returns 6 for\n// microseconds precision.\ntemplate <long long Num, long long Den, int N = 0,\n          bool Enabled = (N < 19) && (Num <= max_value<long long>() / 10)>\nstruct count_fractional_digits {\n  static constexpr int value =\n      Num % Den == 0 ? N : count_fractional_digits<Num * 10, Den, N + 1>::value;\n};\n\n// Base case that doesn't instantiate any more templates\n// in order to avoid overflow.\ntemplate <long long Num, long long Den, int N>\nstruct count_fractional_digits<Num, Den, N, false> {\n  static constexpr int value = (Num % Den == 0) ? N : 6;\n};\n\n// Format subseconds which are given as an integer type with an appropriate\n// number of digits.\ntemplate <typename Char, typename OutputIt, typename Duration>\nvoid write_fractional_seconds(OutputIt& out, Duration d, int precision = -1) {\n  constexpr auto num_fractional_digits =\n      count_fractional_digits<Duration::period::num,\n                              Duration::period::den>::value;\n\n  using subsecond_precision = std::chrono::duration<\n      typename std::common_type<typename Duration::rep,\n                                std::chrono::seconds::rep>::type,\n      std::ratio<1, pow10(num_fractional_digits)>>;\n\n  const auto fractional = d - detail::duration_cast<std::chrono::seconds>(d);\n  const auto subseconds =\n      std::chrono::treat_as_floating_point<\n          typename subsecond_precision::rep>::value\n          ? fractional.count()\n          : detail::duration_cast<subsecond_precision>(fractional).count();\n  auto n = static_cast<uint32_or_64_or_128_t<long long>>(subseconds);\n  const int num_digits = count_digits(n);\n\n  int leading_zeroes = (std::max)(0, num_fractional_digits - num_digits);\n  if (precision < 0) {\n    FMT_ASSERT(!std::is_floating_point<typename Duration::rep>::value, \"\");\n    if (std::ratio_less<typename subsecond_precision::period,\n                        std::chrono::seconds::period>::value) {\n      *out++ = '.';\n      out = detail::fill_n(out, leading_zeroes, '0');\n      out = format_decimal<Char>(out, n, num_digits);\n    }\n  } else if (precision > 0) {\n    *out++ = '.';\n    leading_zeroes = min_of(leading_zeroes, precision);\n    int remaining = precision - leading_zeroes;\n    out = detail::fill_n(out, leading_zeroes, '0');\n    if (remaining < num_digits) {\n      int num_truncated_digits = num_digits - remaining;\n      n /= to_unsigned(pow10(to_unsigned(num_truncated_digits)));\n      if (n != 0) out = format_decimal<Char>(out, n, remaining);\n      return;\n    }\n    if (n != 0) {\n      out = format_decimal<Char>(out, n, num_digits);\n      remaining -= num_digits;\n    }\n    out = detail::fill_n(out, remaining, '0');\n  }\n}\n\n// Format subseconds which are given as a floating point type with an\n// appropriate number of digits. We cannot pass the Duration here, as we\n// explicitly need to pass the Rep value in the duration_formatter.\ntemplate <typename Duration>\nvoid write_floating_seconds(memory_buffer& buf, Duration duration,\n                            int num_fractional_digits = -1) {\n  using rep = typename Duration::rep;\n  FMT_ASSERT(std::is_floating_point<rep>::value, \"\");\n\n  auto val = duration.count();\n\n  if (num_fractional_digits < 0) {\n    // For `std::round` with fallback to `round`:\n    // On some toolchains `std::round` is not available (e.g. GCC 6).\n    using namespace std;\n    num_fractional_digits =\n        count_fractional_digits<Duration::period::num,\n                                Duration::period::den>::value;\n    if (num_fractional_digits < 6 && static_cast<rep>(round(val)) != val)\n      num_fractional_digits = 6;\n  }\n\n  fmt::format_to(std::back_inserter(buf), FMT_STRING(\"{:.{}f}\"),\n                 std::fmod(val * static_cast<rep>(Duration::period::num) /\n                               static_cast<rep>(Duration::period::den),\n                           static_cast<rep>(60)),\n                 num_fractional_digits);\n}\n\ntemplate <typename OutputIt, typename Char,\n          typename Duration = std::chrono::seconds>\nclass tm_writer {\n private:\n  static constexpr int days_per_week = 7;\n\n  const std::locale& loc_;\n  bool is_classic_;\n  OutputIt out_;\n  const Duration* subsecs_;\n  const std::tm& tm_;\n\n  auto tm_sec() const noexcept -> int {\n    FMT_ASSERT(tm_.tm_sec >= 0 && tm_.tm_sec <= 61, \"\");\n    return tm_.tm_sec;\n  }\n  auto tm_min() const noexcept -> int {\n    FMT_ASSERT(tm_.tm_min >= 0 && tm_.tm_min <= 59, \"\");\n    return tm_.tm_min;\n  }\n  auto tm_hour() const noexcept -> int {\n    FMT_ASSERT(tm_.tm_hour >= 0 && tm_.tm_hour <= 23, \"\");\n    return tm_.tm_hour;\n  }\n  auto tm_mday() const noexcept -> int {\n    FMT_ASSERT(tm_.tm_mday >= 1 && tm_.tm_mday <= 31, \"\");\n    return tm_.tm_mday;\n  }\n  auto tm_mon() const noexcept -> int {\n    FMT_ASSERT(tm_.tm_mon >= 0 && tm_.tm_mon <= 11, \"\");\n    return tm_.tm_mon;\n  }\n  auto tm_year() const noexcept -> long long { return 1900ll + tm_.tm_year; }\n  auto tm_wday() const noexcept -> int {\n    FMT_ASSERT(tm_.tm_wday >= 0 && tm_.tm_wday <= 6, \"\");\n    return tm_.tm_wday;\n  }\n  auto tm_yday() const noexcept -> int {\n    FMT_ASSERT(tm_.tm_yday >= 0 && tm_.tm_yday <= 365, \"\");\n    return tm_.tm_yday;\n  }\n\n  auto tm_hour12() const noexcept -> int {\n    auto h = tm_hour();\n    auto z = h < 12 ? h : h - 12;\n    return z == 0 ? 12 : z;\n  }\n\n  // POSIX and the C Standard are unclear or inconsistent about what %C and %y\n  // do if the year is negative or exceeds 9999. Use the convention that %C\n  // concatenated with %y yields the same output as %Y, and that %Y contains at\n  // least 4 characters, with more only if necessary.\n  auto split_year_lower(long long year) const noexcept -> int {\n    auto l = year % 100;\n    if (l < 0) l = -l;  // l in [0, 99]\n    return static_cast<int>(l);\n  }\n\n  // Algorithm: https://en.wikipedia.org/wiki/ISO_week_date.\n  auto iso_year_weeks(long long curr_year) const noexcept -> int {\n    auto prev_year = curr_year - 1;\n    auto curr_p =\n        (curr_year + curr_year / 4 - curr_year / 100 + curr_year / 400) %\n        days_per_week;\n    auto prev_p =\n        (prev_year + prev_year / 4 - prev_year / 100 + prev_year / 400) %\n        days_per_week;\n    return 52 + ((curr_p == 4 || prev_p == 3) ? 1 : 0);\n  }\n  auto iso_week_num(int tm_yday, int tm_wday) const noexcept -> int {\n    return (tm_yday + 11 - (tm_wday == 0 ? days_per_week : tm_wday)) /\n           days_per_week;\n  }\n  auto tm_iso_week_year() const noexcept -> long long {\n    auto year = tm_year();\n    auto w = iso_week_num(tm_yday(), tm_wday());\n    if (w < 1) return year - 1;\n    if (w > iso_year_weeks(year)) return year + 1;\n    return year;\n  }\n  auto tm_iso_week_of_year() const noexcept -> int {\n    auto year = tm_year();\n    auto w = iso_week_num(tm_yday(), tm_wday());\n    if (w < 1) return iso_year_weeks(year - 1);\n    if (w > iso_year_weeks(year)) return 1;\n    return w;\n  }\n\n  void write1(int value) {\n    *out_++ = static_cast<char>('0' + to_unsigned(value) % 10);\n  }\n  void write2(int value) {\n    const char* d = digits2(to_unsigned(value) % 100);\n    *out_++ = *d++;\n    *out_++ = *d;\n  }\n  void write2(int value, pad_type pad) {\n    unsigned int v = to_unsigned(value) % 100;\n    if (v >= 10) {\n      const char* d = digits2(v);\n      *out_++ = *d++;\n      *out_++ = *d;\n    } else {\n      out_ = detail::write_padding(out_, pad);\n      *out_++ = static_cast<char>('0' + v);\n    }\n  }\n\n  void write_year_extended(long long year, pad_type pad) {\n    // At least 4 characters.\n    int width = 4;\n    bool negative = year < 0;\n    if (negative) {\n      year = 0 - year;\n      --width;\n    }\n    uint32_or_64_or_128_t<long long> n = to_unsigned(year);\n    const int num_digits = count_digits(n);\n    if (negative && pad == pad_type::zero) *out_++ = '-';\n    if (width > num_digits)\n      out_ = detail::write_padding(out_, pad, width - num_digits);\n    if (negative && pad != pad_type::zero) *out_++ = '-';\n    out_ = format_decimal<Char>(out_, n, num_digits);\n  }\n  void write_year(long long year, pad_type pad) {\n    write_year_extended(year, pad);\n  }\n\n  void write_utc_offset(long long offset, numeric_system ns) {\n    if (offset < 0) {\n      *out_++ = '-';\n      offset = -offset;\n    } else {\n      *out_++ = '+';\n    }\n    offset /= 60;\n    write2(static_cast<int>(offset / 60));\n    if (ns != numeric_system::standard) *out_++ = ':';\n    write2(static_cast<int>(offset % 60));\n  }\n\n  template <typename T, FMT_ENABLE_IF(has_tm_gmtoff<T>::value)>\n  void format_utc_offset(const T& tm, numeric_system ns) {\n    write_utc_offset(tm.tm_gmtoff, ns);\n  }\n  template <typename T, FMT_ENABLE_IF(!has_tm_gmtoff<T>::value)>\n  void format_utc_offset(const T&, numeric_system ns) {\n    write_utc_offset(0, ns);\n  }\n\n  template <typename T, FMT_ENABLE_IF(has_tm_zone<T>::value)>\n  void format_tz_name(const T& tm) {\n    out_ = write_tm_str<Char>(out_, tm.tm_zone, loc_);\n  }\n  template <typename T, FMT_ENABLE_IF(!has_tm_zone<T>::value)>\n  void format_tz_name(const T&) {\n    out_ = std::copy_n(utc(), 3, out_);\n  }\n\n  void format_localized(char format, char modifier = 0) {\n    out_ = write<Char>(out_, tm_, loc_, format, modifier);\n  }\n\n public:\n  tm_writer(const std::locale& loc, OutputIt out, const std::tm& tm,\n            const Duration* subsecs = nullptr)\n      : loc_(loc),\n        is_classic_(loc_ == get_classic_locale()),\n        out_(out),\n        subsecs_(subsecs),\n        tm_(tm) {}\n\n  auto out() const -> OutputIt { return out_; }\n\n  FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {\n    out_ = copy<Char>(begin, end, out_);\n  }\n\n  void on_abbr_weekday() {\n    if (is_classic_)\n      out_ = write(out_, tm_wday_short_name(tm_wday()));\n    else\n      format_localized('a');\n  }\n  void on_full_weekday() {\n    if (is_classic_)\n      out_ = write(out_, tm_wday_full_name(tm_wday()));\n    else\n      format_localized('A');\n  }\n  void on_dec0_weekday(numeric_system ns) {\n    if (is_classic_ || ns == numeric_system::standard) return write1(tm_wday());\n    format_localized('w', 'O');\n  }\n  void on_dec1_weekday(numeric_system ns) {\n    if (is_classic_ || ns == numeric_system::standard) {\n      auto wday = tm_wday();\n      write1(wday == 0 ? days_per_week : wday);\n    } else {\n      format_localized('u', 'O');\n    }\n  }\n\n  void on_abbr_month() {\n    if (is_classic_)\n      out_ = write(out_, tm_mon_short_name(tm_mon()));\n    else\n      format_localized('b');\n  }\n  void on_full_month() {\n    if (is_classic_)\n      out_ = write(out_, tm_mon_full_name(tm_mon()));\n    else\n      format_localized('B');\n  }\n\n  void on_datetime(numeric_system ns) {\n    if (is_classic_) {\n      on_abbr_weekday();\n      *out_++ = ' ';\n      on_abbr_month();\n      *out_++ = ' ';\n      on_day_of_month(numeric_system::standard, pad_type::space);\n      *out_++ = ' ';\n      on_iso_time();\n      *out_++ = ' ';\n      on_year(numeric_system::standard, pad_type::space);\n    } else {\n      format_localized('c', ns == numeric_system::standard ? '\\0' : 'E');\n    }\n  }\n  void on_loc_date(numeric_system ns) {\n    if (is_classic_)\n      on_us_date();\n    else\n      format_localized('x', ns == numeric_system::standard ? '\\0' : 'E');\n  }\n  void on_loc_time(numeric_system ns) {\n    if (is_classic_)\n      on_iso_time();\n    else\n      format_localized('X', ns == numeric_system::standard ? '\\0' : 'E');\n  }\n  void on_us_date() {\n    char buf[8];\n    write_digit2_separated(buf, to_unsigned(tm_mon() + 1),\n                           to_unsigned(tm_mday()),\n                           to_unsigned(split_year_lower(tm_year())), '/');\n    out_ = copy<Char>(std::begin(buf), std::end(buf), out_);\n  }\n  void on_iso_date() {\n    auto year = tm_year();\n    char buf[10];\n    size_t offset = 0;\n    if (year >= 0 && year < 10000) {\n      write2digits(buf, static_cast<size_t>(year / 100));\n    } else {\n      offset = 4;\n      write_year_extended(year, pad_type::zero);\n      year = 0;\n    }\n    write_digit2_separated(buf + 2, static_cast<unsigned>(year % 100),\n                           to_unsigned(tm_mon() + 1), to_unsigned(tm_mday()),\n                           '-');\n    out_ = copy<Char>(std::begin(buf) + offset, std::end(buf), out_);\n  }\n\n  void on_utc_offset(numeric_system ns) { format_utc_offset(tm_, ns); }\n  void on_tz_name() { format_tz_name(tm_); }\n\n  void on_year(numeric_system ns, pad_type pad) {\n    if (is_classic_ || ns == numeric_system::standard)\n      return write_year(tm_year(), pad);\n    format_localized('Y', 'E');\n  }\n  void on_short_year(numeric_system ns) {\n    if (is_classic_ || ns == numeric_system::standard)\n      return write2(split_year_lower(tm_year()));\n    format_localized('y', 'O');\n  }\n  void on_offset_year() {\n    if (is_classic_) return write2(split_year_lower(tm_year()));\n    format_localized('y', 'E');\n  }\n\n  void on_century(numeric_system ns) {\n    if (is_classic_ || ns == numeric_system::standard) {\n      auto year = tm_year();\n      auto upper = year / 100;\n      if (year >= -99 && year < 0) {\n        // Zero upper on negative year.\n        *out_++ = '-';\n        *out_++ = '0';\n      } else if (upper >= 0 && upper < 100) {\n        write2(static_cast<int>(upper));\n      } else {\n        out_ = write<Char>(out_, upper);\n      }\n    } else {\n      format_localized('C', 'E');\n    }\n  }\n\n  void on_dec_month(numeric_system ns, pad_type pad) {\n    if (is_classic_ || ns == numeric_system::standard)\n      return write2(tm_mon() + 1, pad);\n    format_localized('m', 'O');\n  }\n\n  void on_dec0_week_of_year(numeric_system ns, pad_type pad) {\n    if (is_classic_ || ns == numeric_system::standard)\n      return write2((tm_yday() + days_per_week - tm_wday()) / days_per_week,\n                    pad);\n    format_localized('U', 'O');\n  }\n  void on_dec1_week_of_year(numeric_system ns, pad_type pad) {\n    if (is_classic_ || ns == numeric_system::standard) {\n      auto wday = tm_wday();\n      write2((tm_yday() + days_per_week -\n              (wday == 0 ? (days_per_week - 1) : (wday - 1))) /\n                 days_per_week,\n             pad);\n    } else {\n      format_localized('W', 'O');\n    }\n  }\n  void on_iso_week_of_year(numeric_system ns, pad_type pad) {\n    if (is_classic_ || ns == numeric_system::standard)\n      return write2(tm_iso_week_of_year(), pad);\n    format_localized('V', 'O');\n  }\n\n  void on_iso_week_based_year() {\n    write_year(tm_iso_week_year(), pad_type::zero);\n  }\n  void on_iso_week_based_short_year() {\n    write2(split_year_lower(tm_iso_week_year()));\n  }\n\n  void on_day_of_year(pad_type pad) {\n    auto yday = tm_yday() + 1;\n    auto digit1 = yday / 100;\n    if (digit1 != 0)\n      write1(digit1);\n    else\n      out_ = detail::write_padding(out_, pad);\n    write2(yday % 100, pad);\n  }\n\n  void on_day_of_month(numeric_system ns, pad_type pad) {\n    if (is_classic_ || ns == numeric_system::standard)\n      return write2(tm_mday(), pad);\n    format_localized('d', 'O');\n  }\n\n  void on_24_hour(numeric_system ns, pad_type pad) {\n    if (is_classic_ || ns == numeric_system::standard)\n      return write2(tm_hour(), pad);\n    format_localized('H', 'O');\n  }\n  void on_12_hour(numeric_system ns, pad_type pad) {\n    if (is_classic_ || ns == numeric_system::standard)\n      return write2(tm_hour12(), pad);\n    format_localized('I', 'O');\n  }\n  void on_minute(numeric_system ns, pad_type pad) {\n    if (is_classic_ || ns == numeric_system::standard)\n      return write2(tm_min(), pad);\n    format_localized('M', 'O');\n  }\n\n  void on_second(numeric_system ns, pad_type pad) {\n    if (is_classic_ || ns == numeric_system::standard) {\n      write2(tm_sec(), pad);\n      if (subsecs_) {\n        if (std::is_floating_point<typename Duration::rep>::value) {\n          auto buf = memory_buffer();\n          write_floating_seconds(buf, *subsecs_);\n          if (buf.size() > 1) {\n            // Remove the leading \"0\", write something like \".123\".\n            out_ = copy<Char>(buf.begin() + 1, buf.end(), out_);\n          }\n        } else {\n          write_fractional_seconds<Char>(out_, *subsecs_);\n        }\n      }\n    } else {\n      // Currently no formatting of subseconds when a locale is set.\n      format_localized('S', 'O');\n    }\n  }\n\n  void on_12_hour_time() {\n    if (is_classic_) {\n      char buf[8];\n      write_digit2_separated(buf, to_unsigned(tm_hour12()),\n                             to_unsigned(tm_min()), to_unsigned(tm_sec()), ':');\n      out_ = copy<Char>(std::begin(buf), std::end(buf), out_);\n      *out_++ = ' ';\n      on_am_pm();\n    } else {\n      format_localized('r');\n    }\n  }\n  void on_24_hour_time() {\n    write2(tm_hour());\n    *out_++ = ':';\n    write2(tm_min());\n  }\n  void on_iso_time() {\n    on_24_hour_time();\n    *out_++ = ':';\n    on_second(numeric_system::standard, pad_type::zero);\n  }\n\n  void on_am_pm() {\n    if (is_classic_) {\n      *out_++ = tm_hour() < 12 ? 'A' : 'P';\n      *out_++ = 'M';\n    } else {\n      format_localized('p');\n    }\n  }\n\n  // These apply to chrono durations but not tm.\n  void on_duration_value() {}\n  void on_duration_unit() {}\n};\n\nstruct chrono_format_checker : null_chrono_spec_handler<chrono_format_checker> {\n  bool has_precision_integral = false;\n\n  FMT_NORETURN inline void unsupported() { FMT_THROW(format_error(\"no date\")); }\n\n  template <typename Char>\n  FMT_CONSTEXPR void on_text(const Char*, const Char*) {}\n  FMT_CONSTEXPR void on_day_of_year(pad_type) {}\n  FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_second(numeric_system, pad_type) {}\n  FMT_CONSTEXPR void on_12_hour_time() {}\n  FMT_CONSTEXPR void on_24_hour_time() {}\n  FMT_CONSTEXPR void on_iso_time() {}\n  FMT_CONSTEXPR void on_am_pm() {}\n  FMT_CONSTEXPR void on_duration_value() const {\n    if (has_precision_integral)\n      FMT_THROW(format_error(\"precision not allowed for this argument type\"));\n  }\n  FMT_CONSTEXPR void on_duration_unit() {}\n};\n\ntemplate <typename T,\n          FMT_ENABLE_IF(std::is_integral<T>::value&& has_isfinite<T>::value)>\ninline auto isfinite(T) -> bool {\n  return true;\n}\n\ntemplate <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>\ninline auto mod(T x, int y) -> T {\n  return x % static_cast<T>(y);\n}\ntemplate <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>\ninline auto mod(T x, int y) -> T {\n  return std::fmod(x, static_cast<T>(y));\n}\n\n// If T is an integral type, maps T to its unsigned counterpart, otherwise\n// leaves it unchanged (unlike std::make_unsigned).\ntemplate <typename T, bool INTEGRAL = std::is_integral<T>::value>\nstruct make_unsigned_or_unchanged {\n  using type = T;\n};\n\ntemplate <typename T> struct make_unsigned_or_unchanged<T, true> {\n  using type = typename std::make_unsigned<T>::type;\n};\n\ntemplate <typename Rep, typename Period,\n          FMT_ENABLE_IF(std::is_integral<Rep>::value)>\ninline auto get_milliseconds(std::chrono::duration<Rep, Period> d)\n    -> std::chrono::duration<Rep, std::milli> {\n  // This may overflow and/or the result may not fit in the target type.\n#if FMT_SAFE_DURATION_CAST\n  using common_seconds_type =\n      typename std::common_type<decltype(d), std::chrono::seconds>::type;\n  auto d_as_common = detail::duration_cast<common_seconds_type>(d);\n  auto d_as_whole_seconds =\n      detail::duration_cast<std::chrono::seconds>(d_as_common);\n  // This conversion should be nonproblematic.\n  auto diff = d_as_common - d_as_whole_seconds;\n  auto ms = detail::duration_cast<std::chrono::duration<Rep, std::milli>>(diff);\n  return ms;\n#else\n  auto s = detail::duration_cast<std::chrono::seconds>(d);\n  return detail::duration_cast<std::chrono::milliseconds>(d - s);\n#endif\n}\n\ntemplate <typename Char, typename Rep, typename OutputIt,\n          FMT_ENABLE_IF(std::is_integral<Rep>::value)>\nauto format_duration_value(OutputIt out, Rep val, int) -> OutputIt {\n  return write<Char>(out, val);\n}\n\ntemplate <typename Char, typename Rep, typename OutputIt,\n          FMT_ENABLE_IF(std::is_floating_point<Rep>::value)>\nauto format_duration_value(OutputIt out, Rep val, int precision) -> OutputIt {\n  auto specs = format_specs();\n  specs.precision = precision;\n  specs.set_type(precision >= 0 ? presentation_type::fixed\n                                : presentation_type::general);\n  return write<Char>(out, val, specs);\n}\n\ntemplate <typename Char, typename OutputIt>\nauto copy_unit(string_view unit, OutputIt out, Char) -> OutputIt {\n  return copy<Char>(unit.begin(), unit.end(), out);\n}\n\ntemplate <typename OutputIt>\nauto copy_unit(string_view unit, OutputIt out, wchar_t) -> OutputIt {\n  // This works when wchar_t is UTF-32 because units only contain characters\n  // that have the same representation in UTF-16 and UTF-32.\n  utf8_to_utf16 u(unit);\n  return copy<wchar_t>(u.c_str(), u.c_str() + u.size(), out);\n}\n\ntemplate <typename Char, typename Period, typename OutputIt>\nauto format_duration_unit(OutputIt out) -> OutputIt {\n  if (const char* unit = get_units<Period>())\n    return copy_unit(string_view(unit), out, Char());\n  *out++ = '[';\n  out = write<Char>(out, Period::num);\n  if (const_check(Period::den != 1)) {\n    *out++ = '/';\n    out = write<Char>(out, Period::den);\n  }\n  *out++ = ']';\n  *out++ = 's';\n  return out;\n}\n\nclass get_locale {\n private:\n  union {\n    std::locale locale_;\n  };\n  bool has_locale_ = false;\n\n public:\n  inline get_locale(bool localized, locale_ref loc) : has_locale_(localized) {\n    if (localized)\n      ::new (&locale_) std::locale(loc.template get<std::locale>());\n  }\n  inline ~get_locale() {\n    if (has_locale_) locale_.~locale();\n  }\n  inline operator const std::locale&() const {\n    return has_locale_ ? locale_ : get_classic_locale();\n  }\n};\n\ntemplate <typename Char, typename Rep, typename Period>\nstruct duration_formatter {\n  using iterator = basic_appender<Char>;\n  iterator out;\n  // rep is unsigned to avoid overflow.\n  using rep =\n      conditional_t<std::is_integral<Rep>::value && sizeof(Rep) < sizeof(int),\n                    unsigned, typename make_unsigned_or_unchanged<Rep>::type>;\n  rep val;\n  int precision;\n  locale_ref locale;\n  bool localized = false;\n  using seconds = std::chrono::duration<rep>;\n  seconds s;\n  using milliseconds = std::chrono::duration<rep, std::milli>;\n  bool negative;\n\n  using tm_writer_type = tm_writer<iterator, Char>;\n\n  duration_formatter(iterator o, std::chrono::duration<Rep, Period> d,\n                     locale_ref loc)\n      : out(o), val(static_cast<rep>(d.count())), locale(loc), negative(false) {\n    if (d.count() < 0) {\n      val = 0 - val;\n      negative = true;\n    }\n\n    // this may overflow and/or the result may not fit in the\n    // target type.\n    // might need checked conversion (rep!=Rep)\n    s = detail::duration_cast<seconds>(std::chrono::duration<rep, Period>(val));\n  }\n\n  // returns true if nan or inf, writes to out.\n  auto handle_nan_inf() -> bool {\n    if (isfinite(val)) return false;\n    if (isnan(val)) {\n      write_nan();\n      return true;\n    }\n    // must be +-inf\n    if (val > 0)\n      std::copy_n(\"inf\", 3, out);\n    else\n      std::copy_n(\"-inf\", 4, out);\n    return true;\n  }\n\n  auto days() const -> Rep { return static_cast<Rep>(s.count() / 86400); }\n  auto hour() const -> Rep {\n    return static_cast<Rep>(mod((s.count() / 3600), 24));\n  }\n\n  auto hour12() const -> Rep {\n    Rep hour = static_cast<Rep>(mod((s.count() / 3600), 12));\n    return hour <= 0 ? 12 : hour;\n  }\n\n  auto minute() const -> Rep {\n    return static_cast<Rep>(mod((s.count() / 60), 60));\n  }\n  auto second() const -> Rep { return static_cast<Rep>(mod(s.count(), 60)); }\n\n  auto time() const -> std::tm {\n    auto time = std::tm();\n    time.tm_hour = to_nonnegative_int(hour(), 24);\n    time.tm_min = to_nonnegative_int(minute(), 60);\n    time.tm_sec = to_nonnegative_int(second(), 60);\n    return time;\n  }\n\n  void write_sign() {\n    if (!negative) return;\n    *out++ = '-';\n    negative = false;\n  }\n\n  void write(Rep value, int width, pad_type pad = pad_type::zero) {\n    write_sign();\n    if (isnan(value)) return write_nan();\n    uint32_or_64_or_128_t<int> n =\n        to_unsigned(to_nonnegative_int(value, max_value<int>()));\n    int num_digits = detail::count_digits(n);\n    if (width > num_digits) {\n      out = detail::write_padding(out, pad, width - num_digits);\n    }\n    out = format_decimal<Char>(out, n, num_digits);\n  }\n\n  void write_nan() { std::copy_n(\"nan\", 3, out); }\n\n  template <typename Callback, typename... Args>\n  void format_tm(const tm& time, Callback cb, Args... args) {\n    if (isnan(val)) return write_nan();\n    get_locale loc(localized, locale);\n    auto w = tm_writer_type(loc, out, time);\n    (w.*cb)(args...);\n    out = w.out();\n  }\n\n  void on_text(const Char* begin, const Char* end) {\n    copy<Char>(begin, end, out);\n  }\n\n  // These are not implemented because durations don't have date information.\n  void on_abbr_weekday() {}\n  void on_full_weekday() {}\n  void on_dec0_weekday(numeric_system) {}\n  void on_dec1_weekday(numeric_system) {}\n  void on_abbr_month() {}\n  void on_full_month() {}\n  void on_datetime(numeric_system) {}\n  void on_loc_date(numeric_system) {}\n  void on_loc_time(numeric_system) {}\n  void on_us_date() {}\n  void on_iso_date() {}\n  void on_utc_offset(numeric_system) {}\n  void on_tz_name() {}\n  void on_year(numeric_system, pad_type) {}\n  void on_short_year(numeric_system) {}\n  void on_offset_year() {}\n  void on_century(numeric_system) {}\n  void on_iso_week_based_year() {}\n  void on_iso_week_based_short_year() {}\n  void on_dec_month(numeric_system, pad_type) {}\n  void on_dec0_week_of_year(numeric_system, pad_type) {}\n  void on_dec1_week_of_year(numeric_system, pad_type) {}\n  void on_iso_week_of_year(numeric_system, pad_type) {}\n  void on_day_of_month(numeric_system, pad_type) {}\n\n  void on_day_of_year(pad_type) {\n    if (handle_nan_inf()) return;\n    write(days(), 0);\n  }\n\n  void on_24_hour(numeric_system ns, pad_type pad) {\n    if (handle_nan_inf()) return;\n\n    if (ns == numeric_system::standard) return write(hour(), 2, pad);\n    auto time = tm();\n    time.tm_hour = to_nonnegative_int(hour(), 24);\n    format_tm(time, &tm_writer_type::on_24_hour, ns, pad);\n  }\n\n  void on_12_hour(numeric_system ns, pad_type pad) {\n    if (handle_nan_inf()) return;\n\n    if (ns == numeric_system::standard) return write(hour12(), 2, pad);\n    auto time = tm();\n    time.tm_hour = to_nonnegative_int(hour12(), 12);\n    format_tm(time, &tm_writer_type::on_12_hour, ns, pad);\n  }\n\n  void on_minute(numeric_system ns, pad_type pad) {\n    if (handle_nan_inf()) return;\n\n    if (ns == numeric_system::standard) return write(minute(), 2, pad);\n    auto time = tm();\n    time.tm_min = to_nonnegative_int(minute(), 60);\n    format_tm(time, &tm_writer_type::on_minute, ns, pad);\n  }\n\n  void on_second(numeric_system ns, pad_type pad) {\n    if (handle_nan_inf()) return;\n\n    if (ns == numeric_system::standard) {\n      if (std::is_floating_point<rep>::value) {\n        auto buf = memory_buffer();\n        write_floating_seconds(buf, std::chrono::duration<rep, Period>(val),\n                               precision);\n        if (negative) *out++ = '-';\n        if (buf.size() < 2 || buf[1] == '.')\n          out = detail::write_padding(out, pad);\n        out = copy<Char>(buf.begin(), buf.end(), out);\n      } else {\n        write(second(), 2, pad);\n        write_fractional_seconds<Char>(\n            out, std::chrono::duration<rep, Period>(val), precision);\n      }\n      return;\n    }\n    auto time = tm();\n    time.tm_sec = to_nonnegative_int(second(), 60);\n    format_tm(time, &tm_writer_type::on_second, ns, pad);\n  }\n\n  void on_12_hour_time() {\n    if (handle_nan_inf()) return;\n    format_tm(time(), &tm_writer_type::on_12_hour_time);\n  }\n\n  void on_24_hour_time() {\n    if (handle_nan_inf()) {\n      *out++ = ':';\n      handle_nan_inf();\n      return;\n    }\n\n    write(hour(), 2);\n    *out++ = ':';\n    write(minute(), 2);\n  }\n\n  void on_iso_time() {\n    on_24_hour_time();\n    *out++ = ':';\n    if (handle_nan_inf()) return;\n    on_second(numeric_system::standard, pad_type::zero);\n  }\n\n  void on_am_pm() {\n    if (handle_nan_inf()) return;\n    format_tm(time(), &tm_writer_type::on_am_pm);\n  }\n\n  void on_duration_value() {\n    if (handle_nan_inf()) return;\n    write_sign();\n    out = format_duration_value<Char>(out, val, precision);\n  }\n\n  void on_duration_unit() { out = format_duration_unit<Char, Period>(out); }\n};\n\n}  // namespace detail\n\n#if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907\nusing weekday = std::chrono::weekday;\nusing day = std::chrono::day;\nusing month = std::chrono::month;\nusing year = std::chrono::year;\nusing year_month_day = std::chrono::year_month_day;\n#else\n// A fallback version of weekday.\nclass weekday {\n private:\n  unsigned char value_;\n\n public:\n  weekday() = default;\n  constexpr explicit weekday(unsigned wd) noexcept\n      : value_(static_cast<unsigned char>(wd != 7 ? wd : 0)) {}\n  constexpr auto c_encoding() const noexcept -> unsigned { return value_; }\n};\n\nclass day {\n private:\n  unsigned char value_;\n\n public:\n  day() = default;\n  constexpr explicit day(unsigned d) noexcept\n      : value_(static_cast<unsigned char>(d)) {}\n  constexpr explicit operator unsigned() const noexcept { return value_; }\n};\n\nclass month {\n private:\n  unsigned char value_;\n\n public:\n  month() = default;\n  constexpr explicit month(unsigned m) noexcept\n      : value_(static_cast<unsigned char>(m)) {}\n  constexpr explicit operator unsigned() const noexcept { return value_; }\n};\n\nclass year {\n private:\n  int value_;\n\n public:\n  year() = default;\n  constexpr explicit year(int y) noexcept : value_(y) {}\n  constexpr explicit operator int() const noexcept { return value_; }\n};\n\nclass year_month_day {\n private:\n  fmt::year year_;\n  fmt::month month_;\n  fmt::day day_;\n\n public:\n  year_month_day() = default;\n  constexpr year_month_day(const year& y, const month& m, const day& d) noexcept\n      : year_(y), month_(m), day_(d) {}\n  constexpr auto year() const noexcept -> fmt::year { return year_; }\n  constexpr auto month() const noexcept -> fmt::month { return month_; }\n  constexpr auto day() const noexcept -> fmt::day { return day_; }\n};\n#endif  // __cpp_lib_chrono >= 201907\n\ntemplate <typename Char>\nstruct formatter<weekday, Char> : private formatter<std::tm, Char> {\n private:\n  bool use_tm_formatter_ = false;\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    auto it = ctx.begin(), end = ctx.end();\n    if (it != end && *it == 'L') {\n      ++it;\n      this->set_localized();\n    }\n    use_tm_formatter_ = it != end && *it != '}';\n    return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;\n  }\n\n  template <typename FormatContext>\n  auto format(weekday wd, FormatContext& ctx) const -> decltype(ctx.out()) {\n    auto time = std::tm();\n    time.tm_wday = static_cast<int>(wd.c_encoding());\n    if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);\n    detail::get_locale loc(this->localized(), ctx.locale());\n    auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);\n    w.on_abbr_weekday();\n    return w.out();\n  }\n};\n\ntemplate <typename Char>\nstruct formatter<day, Char> : private formatter<std::tm, Char> {\n private:\n  bool use_tm_formatter_ = false;\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    auto it = ctx.begin(), end = ctx.end();\n    use_tm_formatter_ = it != end && *it != '}';\n    return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;\n  }\n\n  template <typename FormatContext>\n  auto format(day d, FormatContext& ctx) const -> decltype(ctx.out()) {\n    auto time = std::tm();\n    time.tm_mday = static_cast<int>(static_cast<unsigned>(d));\n    if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);\n    detail::get_locale loc(false, ctx.locale());\n    auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);\n    w.on_day_of_month(detail::numeric_system::standard, detail::pad_type::zero);\n    return w.out();\n  }\n};\n\ntemplate <typename Char>\nstruct formatter<month, Char> : private formatter<std::tm, Char> {\n private:\n  bool use_tm_formatter_ = false;\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    auto it = ctx.begin(), end = ctx.end();\n    if (it != end && *it == 'L') {\n      ++it;\n      this->set_localized();\n    }\n    use_tm_formatter_ = it != end && *it != '}';\n    return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;\n  }\n\n  template <typename FormatContext>\n  auto format(month m, FormatContext& ctx) const -> decltype(ctx.out()) {\n    auto time = std::tm();\n    time.tm_mon = static_cast<int>(static_cast<unsigned>(m)) - 1;\n    if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);\n    detail::get_locale loc(this->localized(), ctx.locale());\n    auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);\n    w.on_abbr_month();\n    return w.out();\n  }\n};\n\ntemplate <typename Char>\nstruct formatter<year, Char> : private formatter<std::tm, Char> {\n private:\n  bool use_tm_formatter_ = false;\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    auto it = ctx.begin(), end = ctx.end();\n    use_tm_formatter_ = it != end && *it != '}';\n    return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;\n  }\n\n  template <typename FormatContext>\n  auto format(year y, FormatContext& ctx) const -> decltype(ctx.out()) {\n    auto time = std::tm();\n    time.tm_year = static_cast<int>(y) - 1900;\n    if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);\n    detail::get_locale loc(false, ctx.locale());\n    auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);\n    w.on_year(detail::numeric_system::standard, detail::pad_type::zero);\n    return w.out();\n  }\n};\n\ntemplate <typename Char>\nstruct formatter<year_month_day, Char> : private formatter<std::tm, Char> {\n private:\n  bool use_tm_formatter_ = false;\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    auto it = ctx.begin(), end = ctx.end();\n    use_tm_formatter_ = it != end && *it != '}';\n    return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;\n  }\n\n  template <typename FormatContext>\n  auto format(year_month_day val, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    auto time = std::tm();\n    time.tm_year = static_cast<int>(val.year()) - 1900;\n    time.tm_mon = static_cast<int>(static_cast<unsigned>(val.month())) - 1;\n    time.tm_mday = static_cast<int>(static_cast<unsigned>(val.day()));\n    if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);\n    detail::get_locale loc(true, ctx.locale());\n    auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);\n    w.on_iso_date();\n    return w.out();\n  }\n};\n\ntemplate <typename Rep, typename Period, typename Char>\nstruct formatter<std::chrono::duration<Rep, Period>, Char> {\n private:\n  format_specs specs_;\n  detail::arg_ref<Char> width_ref_;\n  detail::arg_ref<Char> precision_ref_;\n  basic_string_view<Char> fmt_;\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    auto it = ctx.begin(), end = ctx.end();\n    if (it == end || *it == '}') return it;\n\n    it = detail::parse_align(it, end, specs_);\n    if (it == end) return it;\n\n    Char c = *it;\n    if ((c >= '0' && c <= '9') || c == '{') {\n      it = detail::parse_width(it, end, specs_, width_ref_, ctx);\n      if (it == end) return it;\n    }\n\n    auto checker = detail::chrono_format_checker();\n    if (*it == '.') {\n      checker.has_precision_integral = !std::is_floating_point<Rep>::value;\n      it = detail::parse_precision(it, end, specs_, precision_ref_, ctx);\n    }\n    if (it != end && *it == 'L') {\n      specs_.set_localized();\n      ++it;\n    }\n    end = detail::parse_chrono_format(it, end, checker);\n    fmt_ = {it, detail::to_unsigned(end - it)};\n    return end;\n  }\n\n  template <typename FormatContext>\n  auto format(std::chrono::duration<Rep, Period> d, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    auto specs = specs_;\n    auto precision = specs.precision;\n    specs.precision = -1;\n    auto begin = fmt_.begin(), end = fmt_.end();\n    // As a possible future optimization, we could avoid extra copying if width\n    // is not specified.\n    auto buf = basic_memory_buffer<Char>();\n    auto out = basic_appender<Char>(buf);\n    detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,\n                                ctx);\n    detail::handle_dynamic_spec(specs.dynamic_precision(), precision,\n                                precision_ref_, ctx);\n    if (begin == end || *begin == '}') {\n      out = detail::format_duration_value<Char>(out, d.count(), precision);\n      detail::format_duration_unit<Char, Period>(out);\n    } else {\n      auto f =\n          detail::duration_formatter<Char, Rep, Period>(out, d, ctx.locale());\n      f.precision = precision;\n      f.localized = specs_.localized();\n      detail::parse_chrono_format(begin, end, f);\n    }\n    return detail::write(\n        ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs);\n  }\n};\n\ntemplate <typename Char> struct formatter<std::tm, Char> {\n private:\n  format_specs specs_;\n  detail::arg_ref<Char> width_ref_;\n  basic_string_view<Char> fmt_ =\n      detail::string_literal<Char, '%', 'F', ' ', '%', 'T'>();\n\n protected:\n  auto localized() const -> bool { return specs_.localized(); }\n  FMT_CONSTEXPR void set_localized() { specs_.set_localized(); }\n\n  FMT_CONSTEXPR auto do_parse(parse_context<Char>& ctx, bool has_timezone)\n      -> const Char* {\n    auto it = ctx.begin(), end = ctx.end();\n    if (it == end || *it == '}') return it;\n\n    it = detail::parse_align(it, end, specs_);\n    if (it == end) return it;\n\n    Char c = *it;\n    if ((c >= '0' && c <= '9') || c == '{') {\n      it = detail::parse_width(it, end, specs_, width_ref_, ctx);\n      if (it == end) return it;\n    }\n\n    if (*it == 'L') {\n      specs_.set_localized();\n      ++it;\n    }\n\n    end = detail::parse_chrono_format(it, end,\n                                      detail::tm_format_checker(has_timezone));\n    // Replace the default format string only if the new spec is not empty.\n    if (end != it) fmt_ = {it, detail::to_unsigned(end - it)};\n    return end;\n  }\n\n  template <typename Duration, typename FormatContext>\n  auto do_format(const std::tm& tm, FormatContext& ctx,\n                 const Duration* subsecs) const -> decltype(ctx.out()) {\n    auto specs = specs_;\n    auto buf = basic_memory_buffer<Char>();\n    auto out = basic_appender<Char>(buf);\n    detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,\n                                ctx);\n\n    auto loc_ref = specs.localized() ? ctx.locale() : locale_ref();\n    detail::get_locale loc(static_cast<bool>(loc_ref), loc_ref);\n    auto w = detail::tm_writer<basic_appender<Char>, Char, Duration>(\n        loc, out, tm, subsecs);\n    detail::parse_chrono_format(fmt_.begin(), fmt_.end(), w);\n    return detail::write(\n        ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs);\n  }\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    return do_parse(ctx, detail::has_tm_gmtoff<std::tm>::value);\n  }\n\n  template <typename FormatContext>\n  auto format(const std::tm& tm, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    return do_format<std::chrono::seconds>(tm, ctx, nullptr);\n  }\n};\n\n// DEPRECATED! Reversed order of template parameters.\ntemplate <typename Char, typename Duration>\nstruct formatter<sys_time<Duration>, Char> : private formatter<std::tm, Char> {\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    return this->do_parse(ctx, true);\n  }\n\n  template <typename FormatContext>\n  auto format(sys_time<Duration> val, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    std::tm tm = gmtime(val);\n    using period = typename Duration::period;\n    if (detail::const_check(\n            period::num == 1 && period::den == 1 &&\n            !std::is_floating_point<typename Duration::rep>::value)) {\n      detail::set_tm_zone(tm, detail::utc());\n      return formatter<std::tm, Char>::format(tm, ctx);\n    }\n    Duration epoch = val.time_since_epoch();\n    Duration subsecs = detail::duration_cast<Duration>(\n        epoch - detail::duration_cast<std::chrono::seconds>(epoch));\n    if (subsecs.count() < 0) {\n      auto second = detail::duration_cast<Duration>(std::chrono::seconds(1));\n      if (tm.tm_sec != 0) {\n        --tm.tm_sec;\n      } else {\n        tm = gmtime(val - second);\n        detail::set_tm_zone(tm, detail::utc());\n      }\n      subsecs += second;\n    }\n    return formatter<std::tm, Char>::do_format(tm, ctx, &subsecs);\n  }\n};\n\ntemplate <typename Duration, typename Char>\nstruct formatter<utc_time<Duration>, Char>\n    : formatter<sys_time<Duration>, Char> {\n  template <typename FormatContext>\n  auto format(utc_time<Duration> val, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    return formatter<sys_time<Duration>, Char>::format(\n        detail::utc_clock::to_sys(val), ctx);\n  }\n};\n\ntemplate <typename Duration, typename Char>\nstruct formatter<local_time<Duration>, Char>\n    : private formatter<std::tm, Char> {\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    return this->do_parse(ctx, false);\n  }\n\n  template <typename FormatContext>\n  auto format(local_time<Duration> val, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    auto time_since_epoch = val.time_since_epoch();\n    auto seconds_since_epoch =\n        detail::duration_cast<std::chrono::seconds>(time_since_epoch);\n    // Use gmtime to prevent time zone conversion since local_time has an\n    // unspecified time zone.\n    std::tm t = gmtime(seconds_since_epoch.count());\n    using period = typename Duration::period;\n    if (period::num == 1 && period::den == 1 &&\n        !std::is_floating_point<typename Duration::rep>::value) {\n      return formatter<std::tm, Char>::format(t, ctx);\n    }\n    auto subsecs =\n        detail::duration_cast<Duration>(time_since_epoch - seconds_since_epoch);\n    return formatter<std::tm, Char>::do_format(t, ctx, &subsecs);\n  }\n};\n\nFMT_END_EXPORT\nFMT_END_NAMESPACE\n\n#endif  // FMT_CHRONO_H_\n"
  },
  {
    "path": "include/fmt/color.h",
    "content": "// Formatting library for C++ - color support\n//\n// Copyright (c) 2018 - present, Victor Zverovich and fmt contributors\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_COLOR_H_\n#define FMT_COLOR_H_\n\n#include \"format.h\"\n\nFMT_BEGIN_NAMESPACE\nFMT_BEGIN_EXPORT\n\nenum class color : uint32_t {\n  alice_blue = 0xF0F8FF,               // rgb(240,248,255)\n  antique_white = 0xFAEBD7,            // rgb(250,235,215)\n  aqua = 0x00FFFF,                     // rgb(0,255,255)\n  aquamarine = 0x7FFFD4,               // rgb(127,255,212)\n  azure = 0xF0FFFF,                    // rgb(240,255,255)\n  beige = 0xF5F5DC,                    // rgb(245,245,220)\n  bisque = 0xFFE4C4,                   // rgb(255,228,196)\n  black = 0x000000,                    // rgb(0,0,0)\n  blanched_almond = 0xFFEBCD,          // rgb(255,235,205)\n  blue = 0x0000FF,                     // rgb(0,0,255)\n  blue_violet = 0x8A2BE2,              // rgb(138,43,226)\n  brown = 0xA52A2A,                    // rgb(165,42,42)\n  burly_wood = 0xDEB887,               // rgb(222,184,135)\n  cadet_blue = 0x5F9EA0,               // rgb(95,158,160)\n  chartreuse = 0x7FFF00,               // rgb(127,255,0)\n  chocolate = 0xD2691E,                // rgb(210,105,30)\n  coral = 0xFF7F50,                    // rgb(255,127,80)\n  cornflower_blue = 0x6495ED,          // rgb(100,149,237)\n  cornsilk = 0xFFF8DC,                 // rgb(255,248,220)\n  crimson = 0xDC143C,                  // rgb(220,20,60)\n  cyan = 0x00FFFF,                     // rgb(0,255,255)\n  dark_blue = 0x00008B,                // rgb(0,0,139)\n  dark_cyan = 0x008B8B,                // rgb(0,139,139)\n  dark_golden_rod = 0xB8860B,          // rgb(184,134,11)\n  dark_gray = 0xA9A9A9,                // rgb(169,169,169)\n  dark_green = 0x006400,               // rgb(0,100,0)\n  dark_khaki = 0xBDB76B,               // rgb(189,183,107)\n  dark_magenta = 0x8B008B,             // rgb(139,0,139)\n  dark_olive_green = 0x556B2F,         // rgb(85,107,47)\n  dark_orange = 0xFF8C00,              // rgb(255,140,0)\n  dark_orchid = 0x9932CC,              // rgb(153,50,204)\n  dark_red = 0x8B0000,                 // rgb(139,0,0)\n  dark_salmon = 0xE9967A,              // rgb(233,150,122)\n  dark_sea_green = 0x8FBC8F,           // rgb(143,188,143)\n  dark_slate_blue = 0x483D8B,          // rgb(72,61,139)\n  dark_slate_gray = 0x2F4F4F,          // rgb(47,79,79)\n  dark_turquoise = 0x00CED1,           // rgb(0,206,209)\n  dark_violet = 0x9400D3,              // rgb(148,0,211)\n  deep_pink = 0xFF1493,                // rgb(255,20,147)\n  deep_sky_blue = 0x00BFFF,            // rgb(0,191,255)\n  dim_gray = 0x696969,                 // rgb(105,105,105)\n  dodger_blue = 0x1E90FF,              // rgb(30,144,255)\n  fire_brick = 0xB22222,               // rgb(178,34,34)\n  floral_white = 0xFFFAF0,             // rgb(255,250,240)\n  forest_green = 0x228B22,             // rgb(34,139,34)\n  fuchsia = 0xFF00FF,                  // rgb(255,0,255)\n  gainsboro = 0xDCDCDC,                // rgb(220,220,220)\n  ghost_white = 0xF8F8FF,              // rgb(248,248,255)\n  gold = 0xFFD700,                     // rgb(255,215,0)\n  golden_rod = 0xDAA520,               // rgb(218,165,32)\n  gray = 0x808080,                     // rgb(128,128,128)\n  green = 0x008000,                    // rgb(0,128,0)\n  green_yellow = 0xADFF2F,             // rgb(173,255,47)\n  honey_dew = 0xF0FFF0,                // rgb(240,255,240)\n  hot_pink = 0xFF69B4,                 // rgb(255,105,180)\n  indian_red = 0xCD5C5C,               // rgb(205,92,92)\n  indigo = 0x4B0082,                   // rgb(75,0,130)\n  ivory = 0xFFFFF0,                    // rgb(255,255,240)\n  khaki = 0xF0E68C,                    // rgb(240,230,140)\n  lavender = 0xE6E6FA,                 // rgb(230,230,250)\n  lavender_blush = 0xFFF0F5,           // rgb(255,240,245)\n  lawn_green = 0x7CFC00,               // rgb(124,252,0)\n  lemon_chiffon = 0xFFFACD,            // rgb(255,250,205)\n  light_blue = 0xADD8E6,               // rgb(173,216,230)\n  light_coral = 0xF08080,              // rgb(240,128,128)\n  light_cyan = 0xE0FFFF,               // rgb(224,255,255)\n  light_golden_rod_yellow = 0xFAFAD2,  // rgb(250,250,210)\n  light_gray = 0xD3D3D3,               // rgb(211,211,211)\n  light_green = 0x90EE90,              // rgb(144,238,144)\n  light_pink = 0xFFB6C1,               // rgb(255,182,193)\n  light_salmon = 0xFFA07A,             // rgb(255,160,122)\n  light_sea_green = 0x20B2AA,          // rgb(32,178,170)\n  light_sky_blue = 0x87CEFA,           // rgb(135,206,250)\n  light_slate_gray = 0x778899,         // rgb(119,136,153)\n  light_steel_blue = 0xB0C4DE,         // rgb(176,196,222)\n  light_yellow = 0xFFFFE0,             // rgb(255,255,224)\n  lime = 0x00FF00,                     // rgb(0,255,0)\n  lime_green = 0x32CD32,               // rgb(50,205,50)\n  linen = 0xFAF0E6,                    // rgb(250,240,230)\n  magenta = 0xFF00FF,                  // rgb(255,0,255)\n  maroon = 0x800000,                   // rgb(128,0,0)\n  medium_aquamarine = 0x66CDAA,        // rgb(102,205,170)\n  medium_blue = 0x0000CD,              // rgb(0,0,205)\n  medium_orchid = 0xBA55D3,            // rgb(186,85,211)\n  medium_purple = 0x9370DB,            // rgb(147,112,219)\n  medium_sea_green = 0x3CB371,         // rgb(60,179,113)\n  medium_slate_blue = 0x7B68EE,        // rgb(123,104,238)\n  medium_spring_green = 0x00FA9A,      // rgb(0,250,154)\n  medium_turquoise = 0x48D1CC,         // rgb(72,209,204)\n  medium_violet_red = 0xC71585,        // rgb(199,21,133)\n  midnight_blue = 0x191970,            // rgb(25,25,112)\n  mint_cream = 0xF5FFFA,               // rgb(245,255,250)\n  misty_rose = 0xFFE4E1,               // rgb(255,228,225)\n  moccasin = 0xFFE4B5,                 // rgb(255,228,181)\n  navajo_white = 0xFFDEAD,             // rgb(255,222,173)\n  navy = 0x000080,                     // rgb(0,0,128)\n  old_lace = 0xFDF5E6,                 // rgb(253,245,230)\n  olive = 0x808000,                    // rgb(128,128,0)\n  olive_drab = 0x6B8E23,               // rgb(107,142,35)\n  orange = 0xFFA500,                   // rgb(255,165,0)\n  orange_red = 0xFF4500,               // rgb(255,69,0)\n  orchid = 0xDA70D6,                   // rgb(218,112,214)\n  pale_golden_rod = 0xEEE8AA,          // rgb(238,232,170)\n  pale_green = 0x98FB98,               // rgb(152,251,152)\n  pale_turquoise = 0xAFEEEE,           // rgb(175,238,238)\n  pale_violet_red = 0xDB7093,          // rgb(219,112,147)\n  papaya_whip = 0xFFEFD5,              // rgb(255,239,213)\n  peach_puff = 0xFFDAB9,               // rgb(255,218,185)\n  peru = 0xCD853F,                     // rgb(205,133,63)\n  pink = 0xFFC0CB,                     // rgb(255,192,203)\n  plum = 0xDDA0DD,                     // rgb(221,160,221)\n  powder_blue = 0xB0E0E6,              // rgb(176,224,230)\n  purple = 0x800080,                   // rgb(128,0,128)\n  rebecca_purple = 0x663399,           // rgb(102,51,153)\n  red = 0xFF0000,                      // rgb(255,0,0)\n  rosy_brown = 0xBC8F8F,               // rgb(188,143,143)\n  royal_blue = 0x4169E1,               // rgb(65,105,225)\n  saddle_brown = 0x8B4513,             // rgb(139,69,19)\n  salmon = 0xFA8072,                   // rgb(250,128,114)\n  sandy_brown = 0xF4A460,              // rgb(244,164,96)\n  sea_green = 0x2E8B57,                // rgb(46,139,87)\n  sea_shell = 0xFFF5EE,                // rgb(255,245,238)\n  sienna = 0xA0522D,                   // rgb(160,82,45)\n  silver = 0xC0C0C0,                   // rgb(192,192,192)\n  sky_blue = 0x87CEEB,                 // rgb(135,206,235)\n  slate_blue = 0x6A5ACD,               // rgb(106,90,205)\n  slate_gray = 0x708090,               // rgb(112,128,144)\n  snow = 0xFFFAFA,                     // rgb(255,250,250)\n  spring_green = 0x00FF7F,             // rgb(0,255,127)\n  steel_blue = 0x4682B4,               // rgb(70,130,180)\n  tan = 0xD2B48C,                      // rgb(210,180,140)\n  teal = 0x008080,                     // rgb(0,128,128)\n  thistle = 0xD8BFD8,                  // rgb(216,191,216)\n  tomato = 0xFF6347,                   // rgb(255,99,71)\n  turquoise = 0x40E0D0,                // rgb(64,224,208)\n  violet = 0xEE82EE,                   // rgb(238,130,238)\n  wheat = 0xF5DEB3,                    // rgb(245,222,179)\n  white = 0xFFFFFF,                    // rgb(255,255,255)\n  white_smoke = 0xF5F5F5,              // rgb(245,245,245)\n  yellow = 0xFFFF00,                   // rgb(255,255,0)\n  yellow_green = 0x9ACD32              // rgb(154,205,50)\n};                                     // enum class color\n\nenum class terminal_color : uint8_t {\n  black = 30,\n  red,\n  green,\n  yellow,\n  blue,\n  magenta,\n  cyan,\n  white,\n  bright_black = 90,\n  bright_red,\n  bright_green,\n  bright_yellow,\n  bright_blue,\n  bright_magenta,\n  bright_cyan,\n  bright_white\n};\n\nenum class emphasis : uint8_t {\n  bold = 1,\n  faint = 1 << 1,\n  italic = 1 << 2,\n  underline = 1 << 3,\n  blink = 1 << 4,\n  reverse = 1 << 5,\n  conceal = 1 << 6,\n  strikethrough = 1 << 7,\n};\n\n// rgb is a struct for red, green and blue colors.\n// Using the name \"rgb\" makes some editors show the color in a tooltip.\nstruct rgb {\n  constexpr rgb() : r(0), g(0), b(0) {}\n  constexpr rgb(uint8_t r_, uint8_t g_, uint8_t b_) : r(r_), g(g_), b(b_) {}\n  constexpr rgb(uint32_t hex)\n      : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b(hex & 0xFF) {}\n  constexpr rgb(color hex)\n      : r((uint32_t(hex) >> 16) & 0xFF),\n        g((uint32_t(hex) >> 8) & 0xFF),\n        b(uint32_t(hex) & 0xFF) {}\n  uint8_t r;\n  uint8_t g;\n  uint8_t b;\n};\n\nnamespace detail {\n\n// A bit-packed variant of an RGB color, a terminal color, or unset color.\n// see text_style for the bit-packing scheme.\nstruct color_type {\n  constexpr color_type() noexcept = default;\n  constexpr color_type(color rgb_color) noexcept\n      : value_(static_cast<uint32_t>(rgb_color) | (1 << 24)) {}\n  constexpr color_type(rgb rgb_color) noexcept\n      : color_type(static_cast<color>(\n            (static_cast<uint32_t>(rgb_color.r) << 16) |\n            (static_cast<uint32_t>(rgb_color.g) << 8) | rgb_color.b)) {}\n  constexpr color_type(terminal_color term_color) noexcept\n      : value_(static_cast<uint32_t>(term_color) | (3 << 24)) {}\n\n  constexpr auto is_terminal_color() const noexcept -> bool {\n    return (value_ & (1 << 25)) != 0;\n  }\n\n  constexpr auto value() const noexcept -> uint32_t {\n    return value_ & 0xFFFFFF;\n  }\n\n  constexpr color_type(uint32_t value) noexcept : value_(value) {}\n\n  uint32_t value_ = 0;\n};\n}  // namespace detail\n\n/// A text style consisting of foreground and background colors and emphasis.\nclass text_style {\n  // The information is packed as follows:\n  // ┌──┐\n  // │ 0│─┐\n  // │..│ ├── foreground color value\n  // │23│─┘\n  // ├──┤\n  // │24│─┬── discriminator for the above value. 00 if unset, 01 if it's\n  // │25│─┘   an RGB color, or 11 if it's a terminal color (10 is unused)\n  // ├──┤\n  // │26│──── overflow bit, always zero (see below)\n  // ├──┤\n  // │27│─┐\n  // │..│ │\n  // │50│ │\n  // ├──┤ │\n  // │51│ ├── background color (same format as the foreground color)\n  // │52│ │\n  // ├──┤ │\n  // │53│─┘\n  // ├──┤\n  // │54│─┐\n  // │..│ ├── emphases\n  // │61│─┘\n  // ├──┤\n  // │62│─┬── unused\n  // │63│─┘\n  // └──┘\n  // The overflow bits are there to make operator|= efficient.\n  // When ORing, we must throw if, for either the foreground or background,\n  // one style specifies a terminal color and the other specifies any color\n  // (terminal or RGB); in other words, if one discriminator is 11 and the\n  // other is 11 or 01.\n  //\n  // We do that check by adding the styles. Consider what adding does to each\n  // possible pair of discriminators:\n  //    00 + 00 = 000\n  //    01 + 00 = 001\n  //    11 + 00 = 011\n  //    01 + 01 = 010\n  //    11 + 01 = 100 (!!)\n  //    11 + 11 = 110 (!!)\n  // In the last two cases, the ones we want to catch, the third bit——the\n  // overflow bit——is set. Bingo.\n  //\n  // We must take into account the possible carry bit from the bits\n  // before the discriminator. The only potentially problematic case is\n  // 11 + 00 = 011 (a carry bit would make it 100, not good!), but a carry\n  // bit is impossible in that case, because 00 (unset color) means the\n  // 24 bits that precede the discriminator are all zero.\n  //\n  // This test can be applied to both colors simultaneously.\n\n public:\n  FMT_CONSTEXPR text_style(emphasis em = emphasis()) noexcept\n      : style_(static_cast<uint64_t>(em) << 54) {}\n\n  FMT_CONSTEXPR auto operator|=(text_style rhs) -> text_style& {\n    if (((style_ + rhs.style_) & ((1ULL << 26) | (1ULL << 53))) != 0)\n      report_error(\"can't OR a terminal color\");\n    style_ |= rhs.style_;\n    return *this;\n  }\n\n  friend FMT_CONSTEXPR auto operator|(text_style lhs, text_style rhs)\n      -> text_style {\n    return lhs |= rhs;\n  }\n\n  FMT_CONSTEXPR auto operator==(text_style rhs) const noexcept -> bool {\n    return style_ == rhs.style_;\n  }\n\n  FMT_CONSTEXPR auto operator!=(text_style rhs) const noexcept -> bool {\n    return !(*this == rhs);\n  }\n\n  FMT_CONSTEXPR auto has_foreground() const noexcept -> bool {\n    return (style_ & (1 << 24)) != 0;\n  }\n  FMT_CONSTEXPR auto has_background() const noexcept -> bool {\n    return (style_ & (1ULL << 51)) != 0;\n  }\n  FMT_CONSTEXPR auto has_emphasis() const noexcept -> bool {\n    return (style_ >> 54) != 0;\n  }\n  FMT_CONSTEXPR auto get_foreground() const noexcept -> detail::color_type {\n    FMT_ASSERT(has_foreground(), \"no foreground specified for this style\");\n    return style_ & 0x3FFFFFF;\n  }\n  FMT_CONSTEXPR auto get_background() const noexcept -> detail::color_type {\n    FMT_ASSERT(has_background(), \"no background specified for this style\");\n    return (style_ >> 27) & 0x3FFFFFF;\n  }\n  FMT_CONSTEXPR auto get_emphasis() const noexcept -> emphasis {\n    FMT_ASSERT(has_emphasis(), \"no emphasis specified for this style\");\n    return static_cast<emphasis>(style_ >> 54);\n  }\n\n private:\n  FMT_CONSTEXPR text_style(uint64_t style) noexcept : style_(style) {}\n\n  friend FMT_CONSTEXPR auto fg(detail::color_type foreground) noexcept\n      -> text_style;\n\n  friend FMT_CONSTEXPR auto bg(detail::color_type background) noexcept\n      -> text_style;\n\n  uint64_t style_ = 0;\n};\n\n/// Creates a text style from the foreground (text) color.\nFMT_CONSTEXPR inline auto fg(detail::color_type foreground) noexcept\n    -> text_style {\n  return foreground.value_;\n}\n\n/// Creates a text style from the background color.\nFMT_CONSTEXPR inline auto bg(detail::color_type background) noexcept\n    -> text_style {\n  return static_cast<uint64_t>(background.value_) << 27;\n}\n\nFMT_CONSTEXPR inline auto operator|(emphasis lhs, emphasis rhs) noexcept\n    -> text_style {\n  return text_style(lhs) | rhs;\n}\n\nnamespace detail {\n\ntemplate <typename Char> struct ansi_color_escape {\n  FMT_CONSTEXPR ansi_color_escape(color_type text_color,\n                                  const char* esc) noexcept {\n    // If we have a terminal color, we need to output another escape code\n    // sequence.\n    if (text_color.is_terminal_color()) {\n      bool is_background = esc == string_view(\"\\x1b[48;2;\");\n      uint32_t value = text_color.value();\n      // Background ASCII codes are the same as the foreground ones but with\n      // 10 more.\n      if (is_background) value += 10u;\n\n      buffer[size++] = static_cast<Char>('\\x1b');\n      buffer[size++] = static_cast<Char>('[');\n\n      if (value >= 100u) {\n        buffer[size++] = static_cast<Char>('1');\n        value %= 100u;\n      }\n      buffer[size++] = static_cast<Char>('0' + value / 10u);\n      buffer[size++] = static_cast<Char>('0' + value % 10u);\n\n      buffer[size++] = static_cast<Char>('m');\n      return;\n    }\n\n    for (int i = 0; i < 7; i++) {\n      buffer[i] = static_cast<Char>(esc[i]);\n    }\n    rgb color(text_color.value());\n    to_esc(color.r, buffer + 7, ';');\n    to_esc(color.g, buffer + 11, ';');\n    to_esc(color.b, buffer + 15, 'm');\n    size = 19;\n  }\n  FMT_CONSTEXPR ansi_color_escape(emphasis em) noexcept {\n    uint8_t em_codes[num_emphases] = {};\n    if (has_emphasis(em, emphasis::bold)) em_codes[0] = 1;\n    if (has_emphasis(em, emphasis::faint)) em_codes[1] = 2;\n    if (has_emphasis(em, emphasis::italic)) em_codes[2] = 3;\n    if (has_emphasis(em, emphasis::underline)) em_codes[3] = 4;\n    if (has_emphasis(em, emphasis::blink)) em_codes[4] = 5;\n    if (has_emphasis(em, emphasis::reverse)) em_codes[5] = 7;\n    if (has_emphasis(em, emphasis::conceal)) em_codes[6] = 8;\n    if (has_emphasis(em, emphasis::strikethrough)) em_codes[7] = 9;\n\n    buffer[size++] = static_cast<Char>('\\x1b');\n    buffer[size++] = static_cast<Char>('[');\n\n    for (size_t i = 0; i < num_emphases; ++i) {\n      if (!em_codes[i]) continue;\n      buffer[size++] = static_cast<Char>('0' + em_codes[i]);\n      buffer[size++] = static_cast<Char>(';');\n    }\n\n    buffer[size - 1] = static_cast<Char>('m');\n  }\n  FMT_CONSTEXPR operator const Char*() const noexcept { return buffer; }\n\n  FMT_CONSTEXPR auto begin() const noexcept -> const Char* { return buffer; }\n  FMT_CONSTEXPR auto end() const noexcept -> const Char* {\n    return buffer + size;\n  }\n\n private:\n  static constexpr size_t num_emphases = 8;\n  Char buffer[7u + 4u * num_emphases];\n  size_t size = 0;\n\n  static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out,\n                                   char delimiter) noexcept {\n    out[0] = static_cast<Char>('0' + c / 100);\n    out[1] = static_cast<Char>('0' + c / 10 % 10);\n    out[2] = static_cast<Char>('0' + c % 10);\n    out[3] = static_cast<Char>(delimiter);\n  }\n  static FMT_CONSTEXPR auto has_emphasis(emphasis em, emphasis mask) noexcept\n      -> bool {\n    return static_cast<uint8_t>(em) & static_cast<uint8_t>(mask);\n  }\n};\n\ntemplate <typename Char>\nFMT_CONSTEXPR auto make_foreground_color(color_type foreground) noexcept\n    -> ansi_color_escape<Char> {\n  return ansi_color_escape<Char>(foreground, \"\\x1b[38;2;\");\n}\n\ntemplate <typename Char>\nFMT_CONSTEXPR auto make_background_color(color_type background) noexcept\n    -> ansi_color_escape<Char> {\n  return ansi_color_escape<Char>(background, \"\\x1b[48;2;\");\n}\n\ntemplate <typename Char>\nFMT_CONSTEXPR auto make_emphasis(emphasis em) noexcept\n    -> ansi_color_escape<Char> {\n  return ansi_color_escape<Char>(em);\n}\n\ntemplate <typename Char> inline void reset_color(buffer<Char>& buffer) {\n  auto reset_color = string_view(\"\\x1b[0m\");\n  buffer.append(reset_color.begin(), reset_color.end());\n}\n\ntemplate <typename T> struct styled_arg : view {\n  const T& value;\n  text_style style;\n  styled_arg(const T& v, text_style s) : value(v), style(s) {}\n};\n\ntemplate <typename Char>\nvoid vformat_to(buffer<Char>& buf, text_style ts, basic_string_view<Char> fmt,\n                basic_format_args<buffered_context<Char>> args) {\n  if (ts.has_emphasis()) {\n    auto emphasis = make_emphasis<Char>(ts.get_emphasis());\n    buf.append(emphasis.begin(), emphasis.end());\n  }\n  if (ts.has_foreground()) {\n    auto foreground = make_foreground_color<Char>(ts.get_foreground());\n    buf.append(foreground.begin(), foreground.end());\n  }\n  if (ts.has_background()) {\n    auto background = make_background_color<Char>(ts.get_background());\n    buf.append(background.begin(), background.end());\n  }\n  vformat_to(buf, fmt, args);\n  if (ts != text_style()) reset_color<Char>(buf);\n}\n}  // namespace detail\n\ninline void vprint(FILE* f, text_style ts, string_view fmt, format_args args) {\n  auto buf = memory_buffer();\n  detail::vformat_to(buf, ts, fmt, args);\n  print(f, FMT_STRING(\"{}\"), string_view(buf.begin(), buf.size()));\n}\n\n/**\n * Formats a string and prints it to the specified file stream using ANSI\n * escape sequences to specify text formatting.\n *\n * **Example**:\n *\n *     fmt::print(fmt::emphasis::bold | fg(fmt::color::red),\n *                \"Elapsed time: {0:.2f} seconds\", 1.23);\n */\ntemplate <typename... T>\nvoid print(FILE* f, text_style ts, format_string<T...> fmt, T&&... args) {\n  vprint(f, ts, fmt.str, vargs<T...>{{args...}});\n}\n\n/**\n * Formats a string and prints it to stdout using ANSI escape sequences to\n * specify text formatting.\n *\n * **Example**:\n *\n *     fmt::print(fmt::emphasis::bold | fg(fmt::color::red),\n *                \"Elapsed time: {0:.2f} seconds\", 1.23);\n */\ntemplate <typename... T>\nvoid print(text_style ts, format_string<T...> fmt, T&&... args) {\n  return print(stdout, ts, fmt, std::forward<T>(args)...);\n}\n\ninline auto vformat(text_style ts, string_view fmt, format_args args)\n    -> std::string {\n  auto buf = memory_buffer();\n  detail::vformat_to(buf, ts, fmt, args);\n  return fmt::to_string(buf);\n}\n\n/**\n * Formats arguments and returns the result as a string using ANSI escape\n * sequences to specify text formatting.\n *\n * **Example**:\n *\n * ```\n * #include <fmt/color.h>\n * std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red),\n *                                   \"The answer is {}\", 42);\n * ```\n */\ntemplate <typename... T>\ninline auto format(text_style ts, format_string<T...> fmt, T&&... args)\n    -> std::string {\n  return fmt::vformat(ts, fmt.str, vargs<T...>{{args...}});\n}\n\n/// Formats a string with the given text_style and writes the output to `out`.\ntemplate <typename OutputIt,\n          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>\nauto vformat_to(OutputIt out, text_style ts, string_view fmt, format_args args)\n    -> OutputIt {\n  auto&& buf = detail::get_buffer<char>(out);\n  detail::vformat_to(buf, ts, fmt, args);\n  return detail::get_iterator(buf, out);\n}\n\n/**\n * Formats arguments with the given text style, writes the result to the output\n * iterator `out` and returns the iterator past the end of the output range.\n *\n * **Example**:\n *\n *     std::vector<char> out;\n *     fmt::format_to(std::back_inserter(out),\n *                    fmt::emphasis::bold | fg(fmt::color::red), \"{}\", 42);\n */\ntemplate <typename OutputIt, typename... T,\n          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>\ninline auto format_to(OutputIt out, text_style ts, format_string<T...> fmt,\n                      T&&... args) -> OutputIt {\n  return vformat_to(out, ts, fmt.str, vargs<T...>{{args...}});\n}\n\ntemplate <typename T, typename Char>\nstruct formatter<detail::styled_arg<T>, Char> : formatter<T, Char> {\n  template <typename FormatContext>\n  auto format(const detail::styled_arg<T>& arg, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    const auto& ts = arg.style;\n    auto out = ctx.out();\n\n    bool has_style = false;\n    if (ts.has_emphasis()) {\n      has_style = true;\n      auto emphasis = detail::make_emphasis<Char>(ts.get_emphasis());\n      out = detail::copy<Char>(emphasis.begin(), emphasis.end(), out);\n    }\n    if (ts.has_foreground()) {\n      has_style = true;\n      auto foreground =\n          detail::make_foreground_color<Char>(ts.get_foreground());\n      out = detail::copy<Char>(foreground.begin(), foreground.end(), out);\n    }\n    if (ts.has_background()) {\n      has_style = true;\n      auto background =\n          detail::make_background_color<Char>(ts.get_background());\n      out = detail::copy<Char>(background.begin(), background.end(), out);\n    }\n    out = formatter<T, Char>::format(arg.value, ctx);\n    if (has_style) {\n      auto reset_color = string_view(\"\\x1b[0m\");\n      out = detail::copy<Char>(reset_color.begin(), reset_color.end(), out);\n    }\n    return out;\n  }\n};\n\n/**\n * Returns an argument that will be formatted using ANSI escape sequences,\n * to be used in a formatting function.\n *\n * **Example**:\n *\n *     fmt::print(\"Elapsed time: {0:.2f} seconds\",\n *                fmt::styled(1.23, fmt::fg(fmt::color::green) |\n *                                  fmt::bg(fmt::color::blue)));\n */\ntemplate <typename T>\nFMT_CONSTEXPR auto styled(const T& value, text_style ts)\n    -> detail::styled_arg<remove_cvref_t<T>> {\n  return detail::styled_arg<remove_cvref_t<T>>{value, ts};\n}\n\nFMT_END_EXPORT\nFMT_END_NAMESPACE\n\n#endif  // FMT_COLOR_H_\n"
  },
  {
    "path": "include/fmt/compile.h",
    "content": "// Formatting library for C++ - experimental format string compilation\n//\n// Copyright (c) 2012 - present, Victor Zverovich and fmt contributors\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_COMPILE_H_\n#define FMT_COMPILE_H_\n\n#ifndef FMT_MODULE\n#  include <iterator>  // std::back_inserter\n#endif\n\n#include \"format.h\"\n\nFMT_BEGIN_NAMESPACE\n\n// A compile-time string which is compiled into fast formatting code.\nFMT_EXPORT class compiled_string {};\n\ntemplate <typename S>\nstruct is_compiled_string : std::is_base_of<compiled_string, S> {};\n\n/**\n * Converts a string literal `s` into a format string that will be parsed at\n * compile time and converted into efficient formatting code. Requires C++17\n * `constexpr if` compiler support.\n *\n * **Example**:\n *\n *     // Converts 42 into std::string using the most efficient method and no\n *     // runtime format string processing.\n *     std::string s = fmt::format(FMT_COMPILE(\"{}\"), 42);\n */\n#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)\n#  define FMT_COMPILE(s) FMT_STRING_IMPL(s, fmt::compiled_string)\n#else\n#  define FMT_COMPILE(s) FMT_STRING(s)\n#endif\n\n/**\n * Converts a string literal into a format string that will be parsed at\n * compile time and converted into efficient formatting code. Requires support\n * for class types in constant template parameters (a C++20 feature).\n *\n *  **Example**:\n *\n *     // Converts 42 into std::string using the most efficient method and no\n *     // runtime format string processing.\n *     using namespace fmt::literals;\n *     std::string s = fmt::format(\"{}\"_cf, 42);\n */\n#if FMT_USE_NONTYPE_TEMPLATE_ARGS\ninline namespace literals {\ntemplate <detail::fixed_string Str> constexpr auto operator\"\"_cf() {\n  return FMT_COMPILE(Str.data);\n}\n}  // namespace literals\n#endif\n\nnamespace detail {\n\ntemplate <typename T, typename... Tail>\nconstexpr auto first(const T& value, const Tail&...) -> const T& {\n  return value;\n}\n\n#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)\ntemplate <typename... T> struct type_list {};\n\n// Returns a reference to the argument at index N from [first, rest...].\ntemplate <int N, typename T, typename... Args>\nconstexpr auto get([[maybe_unused]] const T& first,\n                   [[maybe_unused]] const Args&... rest) -> const auto& {\n  static_assert(N < 1 + sizeof...(Args), \"index is out of bounds\");\n  if constexpr (N == 0)\n    return first;\n  else\n    return detail::get<N - 1>(rest...);\n}\n\n#  if FMT_USE_NONTYPE_TEMPLATE_ARGS\ntemplate <int N, typename T, typename... Args, typename Char>\nconstexpr auto get_arg_index_by_name(basic_string_view<Char> name) -> int {\n  if constexpr (is_static_named_arg<T>()) {\n    if (name == T::name) return N;\n  }\n  if constexpr (sizeof...(Args) > 0)\n    return get_arg_index_by_name<N + 1, Args...>(name);\n  (void)name;  // Workaround an MSVC bug about \"unused\" parameter.\n  return -1;\n}\n#  endif\n\ntemplate <typename... Args, typename Char>\nFMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view<Char> name) -> int {\n#  if FMT_USE_NONTYPE_TEMPLATE_ARGS\n  if constexpr (sizeof...(Args) > 0)\n    return get_arg_index_by_name<0, Args...>(name);\n#  endif\n  (void)name;\n  return -1;\n}\n\ntemplate <typename Char, typename... Args>\nconstexpr auto get_arg_index_by_name(basic_string_view<Char> name,\n                                     type_list<Args...>) -> int {\n  return get_arg_index_by_name<Args...>(name);\n}\n\ntemplate <int N, typename> struct get_type_impl;\n\ntemplate <int N, typename... Args> struct get_type_impl<N, type_list<Args...>> {\n  using type =\n      remove_cvref_t<decltype(detail::get<N>(std::declval<Args>()...))>;\n};\n\ntemplate <int N, typename T>\nusing get_type = typename get_type_impl<N, T>::type;\n\ntemplate <typename T> struct is_compiled_format : std::false_type {};\n\ntemplate <typename Char> struct text {\n  basic_string_view<Char> data;\n  using char_type = Char;\n\n  template <typename OutputIt, typename... T>\n  constexpr auto format(OutputIt out, const T&...) const -> OutputIt {\n    return write<Char>(out, data);\n  }\n};\n\ntemplate <typename Char>\nstruct is_compiled_format<text<Char>> : std::true_type {};\n\ntemplate <typename Char>\nconstexpr auto make_text(basic_string_view<Char> s, size_t pos, size_t size)\n    -> text<Char> {\n  return {{&s[pos], size}};\n}\n\ntemplate <typename Char> struct code_unit {\n  Char value;\n  using char_type = Char;\n\n  template <typename OutputIt, typename... T>\n  constexpr auto format(OutputIt out, const T&...) const -> OutputIt {\n    *out++ = value;\n    return out;\n  }\n};\n\n// This ensures that the argument type is convertible to `const T&`.\ntemplate <typename T, int N, typename... Args>\nconstexpr auto get_arg_checked(const Args&... args) -> const T& {\n  const auto& arg = detail::get<N>(args...);\n  if constexpr (detail::is_named_arg<remove_cvref_t<decltype(arg)>>()) {\n    return arg.value;\n  } else {\n    return arg;\n  }\n}\n\ntemplate <typename Char>\nstruct is_compiled_format<code_unit<Char>> : std::true_type {};\n\n// A replacement field that refers to argument N.\ntemplate <typename Char, typename V, int N> struct field {\n  using char_type = Char;\n\n  template <typename OutputIt, typename... T>\n  constexpr auto format(OutputIt out, const T&... args) const -> OutputIt {\n    const V& arg = get_arg_checked<V, N>(args...);\n    if constexpr (std::is_convertible<V, basic_string_view<Char>>::value) {\n      auto s = basic_string_view<Char>(arg);\n      return copy<Char>(s.begin(), s.end(), out);\n    } else {\n      return write<Char>(out, arg);\n    }\n  }\n};\n\ntemplate <typename Char, typename T, int N>\nstruct is_compiled_format<field<Char, T, N>> : std::true_type {};\n\n// A replacement field that refers to argument with name.\ntemplate <typename Char> struct runtime_named_field {\n  using char_type = Char;\n  basic_string_view<Char> name;\n\n  template <typename OutputIt, typename T>\n  constexpr static auto try_format_argument(\n      OutputIt& out,\n      // [[maybe_unused]] due to unused-but-set-parameter warning in GCC 7,8,9\n      [[maybe_unused]] basic_string_view<Char> arg_name, const T& arg) -> bool {\n    if constexpr (is_named_arg<typename std::remove_cv<T>::type>::value) {\n      if (arg_name == arg.name) {\n        out = write<Char>(out, arg.value);\n        return true;\n      }\n    }\n    return false;\n  }\n\n  template <typename OutputIt, typename... T>\n  constexpr auto format(OutputIt out, const T&... args) const -> OutputIt {\n    bool found = (try_format_argument(out, name, args) || ...);\n    if (!found) {\n      FMT_THROW(format_error(\"argument with specified name is not found\"));\n    }\n    return out;\n  }\n};\n\ntemplate <typename Char>\nstruct is_compiled_format<runtime_named_field<Char>> : std::true_type {};\n\n// A replacement field that refers to argument N and has format specifiers.\ntemplate <typename Char, typename V, int N> struct spec_field {\n  using char_type = Char;\n  formatter<V, Char> fmt;\n\n  template <typename OutputIt, typename... T>\n  constexpr FMT_INLINE auto format(OutputIt out, const T&... args) const\n      -> OutputIt {\n    const auto& vargs =\n        fmt::make_format_args<basic_format_context<OutputIt, Char>>(args...);\n    basic_format_context<OutputIt, Char> ctx(out, vargs);\n    return fmt.format(get_arg_checked<V, N>(args...), ctx);\n  }\n};\n\ntemplate <typename Char, typename T, int N>\nstruct is_compiled_format<spec_field<Char, T, N>> : std::true_type {};\n\ntemplate <typename L, typename R> struct concat {\n  L lhs;\n  R rhs;\n  using char_type = typename L::char_type;\n\n  template <typename OutputIt, typename... T>\n  constexpr auto format(OutputIt out, const T&... args) const -> OutputIt {\n    out = lhs.format(out, args...);\n    return rhs.format(out, args...);\n  }\n};\n\ntemplate <typename L, typename R>\nstruct is_compiled_format<concat<L, R>> : std::true_type {};\n\ntemplate <typename L, typename R>\nconstexpr auto make_concat(L lhs, R rhs) -> concat<L, R> {\n  return {lhs, rhs};\n}\n\nstruct unknown_format {};\n\ntemplate <typename Char>\nconstexpr auto parse_text(basic_string_view<Char> str, size_t pos) -> size_t {\n  for (size_t size = str.size(); pos != size; ++pos) {\n    if (str[pos] == '{' || str[pos] == '}') break;\n  }\n  return pos;\n}\n\ntemplate <typename Args, size_t POS, int ID, typename S>\nconstexpr auto compile_format_string(S fmt);\n\ntemplate <typename Args, size_t POS, int ID, typename T, typename S>\nconstexpr auto parse_tail(T head, S fmt) {\n  if constexpr (POS != basic_string_view<typename S::char_type>(fmt).size()) {\n    constexpr auto tail = compile_format_string<Args, POS, ID>(fmt);\n    if constexpr (std::is_same<remove_cvref_t<decltype(tail)>,\n                               unknown_format>())\n      return tail;\n    else\n      return make_concat(head, tail);\n  } else {\n    return head;\n  }\n}\n\ntemplate <typename T, typename Char> struct parse_specs_result {\n  formatter<T, Char> fmt;\n  size_t end;\n  int next_arg_id;\n};\n\nenum { manual_indexing_id = -1 };\n\ntemplate <typename T, typename Char>\nconstexpr auto parse_specs(basic_string_view<Char> str, size_t pos,\n                           int next_arg_id) -> parse_specs_result<T, Char> {\n  str.remove_prefix(pos);\n  auto ctx =\n      compile_parse_context<Char>(str, max_value<int>(), nullptr, next_arg_id);\n  auto f = formatter<T, Char>();\n  auto end = f.parse(ctx);\n  return {f, pos + fmt::detail::to_unsigned(end - str.data()),\n          next_arg_id == 0 ? manual_indexing_id : ctx.next_arg_id()};\n}\n\ntemplate <typename Char> struct arg_id_handler {\n  arg_id_kind kind;\n  arg_ref<Char> arg_id;\n\n  constexpr auto on_auto() -> int {\n    FMT_ASSERT(false, \"handler cannot be used with automatic indexing\");\n    return 0;\n  }\n  constexpr auto on_index(int id) -> int {\n    kind = arg_id_kind::index;\n    arg_id = arg_ref<Char>(id);\n    return 0;\n  }\n  constexpr auto on_name(basic_string_view<Char> id) -> int {\n    kind = arg_id_kind::name;\n    arg_id = arg_ref<Char>(id);\n    return 0;\n  }\n};\n\ntemplate <typename Char> struct parse_arg_id_result {\n  arg_id_kind kind;\n  arg_ref<Char> arg_id;\n  const Char* arg_id_end;\n};\n\ntemplate <int ID, typename Char>\nconstexpr auto parse_arg_id(const Char* begin, const Char* end) {\n  auto handler = arg_id_handler<Char>{arg_id_kind::none, arg_ref<Char>{}};\n  auto arg_id_end = parse_arg_id(begin, end, handler);\n  return parse_arg_id_result<Char>{handler.kind, handler.arg_id, arg_id_end};\n}\n\ntemplate <typename T, typename Enable = void> struct field_type {\n  using type = remove_cvref_t<T>;\n};\n\ntemplate <typename T>\nstruct field_type<T, enable_if_t<detail::is_named_arg<T>::value>> {\n  using type = remove_cvref_t<decltype(T::value)>;\n};\n\ntemplate <typename T, typename Args, size_t END_POS, int ARG_INDEX, int NEXT_ID,\n          typename S>\nconstexpr auto parse_replacement_field_then_tail(S fmt) {\n  using char_type = typename S::char_type;\n  constexpr auto str = basic_string_view<char_type>(fmt);\n  constexpr char_type c = END_POS != str.size() ? str[END_POS] : char_type();\n  if constexpr (c == '}') {\n    return parse_tail<Args, END_POS + 1, NEXT_ID>(\n        field<char_type, typename field_type<T>::type, ARG_INDEX>(), fmt);\n  } else if constexpr (c != ':') {\n    FMT_THROW(format_error(\"expected ':'\"));\n  } else {\n    constexpr auto result = parse_specs<typename field_type<T>::type>(\n        str, END_POS + 1, NEXT_ID == manual_indexing_id ? 0 : NEXT_ID);\n    if constexpr (result.end >= str.size() || str[result.end] != '}') {\n      FMT_THROW(format_error(\"expected '}'\"));\n      return 0;\n    } else {\n      return parse_tail<Args, result.end + 1, result.next_arg_id>(\n          spec_field<char_type, typename field_type<T>::type, ARG_INDEX>{\n              result.fmt},\n          fmt);\n    }\n  }\n}\n\n// Compiles a non-empty format string and returns the compiled representation\n// or unknown_format() on unrecognized input.\ntemplate <typename Args, size_t POS, int ID, typename S>\nconstexpr auto compile_format_string(S fmt) {\n  using char_type = typename S::char_type;\n  constexpr auto str = basic_string_view<char_type>(fmt);\n  if constexpr (str[POS] == '{') {\n    if constexpr (POS + 1 == str.size())\n      FMT_THROW(format_error(\"unmatched '{' in format string\"));\n    if constexpr (str[POS + 1] == '{') {\n      return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), fmt);\n    } else if constexpr (str[POS + 1] == '}' || str[POS + 1] == ':') {\n      static_assert(ID != manual_indexing_id,\n                    \"cannot switch from manual to automatic argument indexing\");\n      constexpr auto next_id =\n          ID != manual_indexing_id ? ID + 1 : manual_indexing_id;\n      return parse_replacement_field_then_tail<get_type<ID, Args>, Args,\n                                               POS + 1, ID, next_id>(fmt);\n    } else {\n      constexpr auto arg_id_result =\n          parse_arg_id<ID>(str.data() + POS + 1, str.data() + str.size());\n      constexpr auto arg_id_end_pos = arg_id_result.arg_id_end - str.data();\n      constexpr char_type c =\n          arg_id_end_pos != str.size() ? str[arg_id_end_pos] : char_type();\n      static_assert(c == '}' || c == ':', \"missing '}' in format string\");\n      if constexpr (arg_id_result.kind == arg_id_kind::index) {\n        static_assert(\n            ID == manual_indexing_id || ID == 0,\n            \"cannot switch from automatic to manual argument indexing\");\n        constexpr auto arg_index = arg_id_result.arg_id.index;\n        return parse_replacement_field_then_tail<get_type<arg_index, Args>,\n                                                 Args, arg_id_end_pos,\n                                                 arg_index, manual_indexing_id>(\n            fmt);\n      } else if constexpr (arg_id_result.kind == arg_id_kind::name) {\n        constexpr auto arg_index =\n            get_arg_index_by_name(arg_id_result.arg_id.name, Args{});\n        if constexpr (arg_index >= 0) {\n          constexpr auto next_id =\n              ID != manual_indexing_id ? ID + 1 : manual_indexing_id;\n          return parse_replacement_field_then_tail<\n              decltype(get_type<arg_index, Args>::value), Args, arg_id_end_pos,\n              arg_index, next_id>(fmt);\n        } else if constexpr (c == '}') {\n          return parse_tail<Args, arg_id_end_pos + 1, ID>(\n              runtime_named_field<char_type>{arg_id_result.arg_id.name}, fmt);\n        } else if constexpr (c == ':') {\n          return unknown_format();  // no type info for specs parsing\n        }\n      }\n    }\n  } else if constexpr (str[POS] == '}') {\n    if constexpr (POS + 1 == str.size())\n      FMT_THROW(format_error(\"unmatched '}' in format string\"));\n    return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), fmt);\n  } else {\n    constexpr auto end = parse_text(str, POS + 1);\n    if constexpr (end - POS > 1) {\n      return parse_tail<Args, end, ID>(make_text(str, POS, end - POS), fmt);\n    } else {\n      return parse_tail<Args, end, ID>(code_unit<char_type>{str[POS]}, fmt);\n    }\n  }\n}\n\ntemplate <typename... Args, typename S,\n          FMT_ENABLE_IF(is_compiled_string<S>::value)>\nconstexpr auto compile(S fmt) {\n  constexpr auto str = basic_string_view<typename S::char_type>(fmt);\n  if constexpr (str.size() == 0) {\n    return detail::make_text(str, 0, 0);\n  } else {\n    constexpr auto result =\n        detail::compile_format_string<detail::type_list<Args...>, 0, 0>(fmt);\n    return result;\n  }\n}\n#endif  // defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)\n}  // namespace detail\n\nFMT_BEGIN_EXPORT\n\n#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)\n\ntemplate <typename CompiledFormat, typename... T,\n          typename Char = typename CompiledFormat::char_type,\n          FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>\nFMT_INLINE FMT_CONSTEXPR_STRING auto format(const CompiledFormat& cf,\n                                            const T&... args)\n    -> std::basic_string<Char> {\n  auto s = std::basic_string<Char>();\n  cf.format(std::back_inserter(s), args...);\n  return s;\n}\n\ntemplate <typename OutputIt, typename CompiledFormat, typename... T,\n          FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>\nconstexpr FMT_INLINE auto format_to(OutputIt out, const CompiledFormat& cf,\n                                    const T&... args) -> OutputIt {\n  return cf.format(out, args...);\n}\n\ntemplate <typename S, typename... T,\n          FMT_ENABLE_IF(is_compiled_string<S>::value)>\nFMT_INLINE FMT_CONSTEXPR_STRING auto format(const S&, T&&... args)\n    -> std::basic_string<typename S::char_type> {\n  if constexpr (std::is_same<typename S::char_type, char>::value) {\n    constexpr auto str = basic_string_view<typename S::char_type>(S());\n    if constexpr (str.size() == 2 && str[0] == '{' && str[1] == '}') {\n      const auto& first = detail::first(args...);\n      if constexpr (detail::is_named_arg<\n                        remove_cvref_t<decltype(first)>>::value) {\n        return fmt::to_string(first.value);\n      } else {\n        return fmt::to_string(first);\n      }\n    }\n  }\n  constexpr auto compiled = detail::compile<T...>(S());\n  if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,\n                             detail::unknown_format>()) {\n    return fmt::format(\n        static_cast<basic_string_view<typename S::char_type>>(S()),\n        std::forward<T>(args)...);\n  } else {\n    return fmt::format(compiled, std::forward<T>(args)...);\n  }\n}\n\ntemplate <typename OutputIt, typename S, typename... T,\n          FMT_ENABLE_IF(is_compiled_string<S>::value)>\nFMT_CONSTEXPR auto format_to(OutputIt out, const S&, T&&... args) -> OutputIt {\n  constexpr auto compiled = detail::compile<T...>(S());\n  if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,\n                             detail::unknown_format>()) {\n    return fmt::format_to(\n        out, static_cast<basic_string_view<typename S::char_type>>(S()),\n        std::forward<T>(args)...);\n  } else {\n    return fmt::format_to(out, compiled, std::forward<T>(args)...);\n  }\n}\n#endif\n\ntemplate <typename OutputIt, typename S, typename... T,\n          FMT_ENABLE_IF(is_compiled_string<S>::value)>\nauto format_to_n(OutputIt out, size_t n, const S& fmt, T&&... args)\n    -> format_to_n_result<OutputIt> {\n  using traits = detail::fixed_buffer_traits;\n  auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n);\n  fmt::format_to(std::back_inserter(buf), fmt, std::forward<T>(args)...);\n  return {buf.out(), buf.count()};\n}\n\ntemplate <typename S, typename... T,\n          FMT_ENABLE_IF(is_compiled_string<S>::value)>\nFMT_CONSTEXPR20 auto formatted_size(const S& fmt, T&&... args) -> size_t {\n  auto buf = detail::counting_buffer<>();\n  fmt::format_to(appender(buf), fmt, std::forward<T>(args)...);\n  return buf.count();\n}\n\ntemplate <typename S, typename... T,\n          FMT_ENABLE_IF(is_compiled_string<S>::value)>\nvoid print(std::FILE* f, const S& fmt, T&&... args) {\n  auto buf = memory_buffer();\n  fmt::format_to(appender(buf), fmt, std::forward<T>(args)...);\n  detail::print(f, {buf.data(), buf.size()});\n}\n\ntemplate <typename S, typename... T,\n          FMT_ENABLE_IF(is_compiled_string<S>::value)>\nvoid print(const S& fmt, T&&... args) {\n  print(stdout, fmt, std::forward<T>(args)...);\n}\n\ntemplate <size_t N> class static_format_result {\n private:\n  char data[N];\n\n public:\n  template <typename S, typename... T,\n            FMT_ENABLE_IF(is_compiled_string<S>::value)>\n  explicit FMT_CONSTEXPR static_format_result(const S& fmt, T&&... args) {\n    *fmt::format_to(data, fmt, std::forward<T>(args)...) = '\\0';\n  }\n\n  auto str() const -> fmt::string_view { return {data, N - 1}; }\n  auto c_str() const -> const char* { return data; }\n};\n\n/**\n * Formats arguments according to the format string `fmt_str` and produces\n * a string of the exact required size at compile time. Both the format string\n * and the arguments must be compile-time expressions.\n *\n * The resulting string can be accessed as a C string via `c_str()` or as\n * a `fmt::string_view` via `str()`.\n *\n * **Example**:\n *\n *     // Produces the static string \"42\" at compile time.\n *     static constexpr auto result = FMT_STATIC_FORMAT(\"{}\", 42);\n *     const char* s = result.c_str();\n */\n#define FMT_STATIC_FORMAT(fmt_str, ...)                            \\\n  fmt::static_format_result<                                       \\\n      fmt::formatted_size(FMT_COMPILE(fmt_str), __VA_ARGS__) + 1>( \\\n      FMT_COMPILE(fmt_str), __VA_ARGS__)\n\nFMT_END_EXPORT\nFMT_END_NAMESPACE\n\n#endif  // FMT_COMPILE_H_\n"
  },
  {
    "path": "include/fmt/core.h",
    "content": "// This file is only provided for compatibility and may be removed in future\n// versions. Use fmt/base.h if you don't need fmt::format and fmt/format.h\n// otherwise.\n\n#include \"format.h\"\n"
  },
  {
    "path": "include/fmt/format-inl.h",
    "content": "// Formatting library for C++ - implementation\n//\n// Copyright (c) 2012 - 2016, Victor Zverovich\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_FORMAT_INL_H_\n#define FMT_FORMAT_INL_H_\n\n#ifndef FMT_MODULE\n#  include <algorithm>\n#  include <cerrno>  // errno\n#  include <climits>\n#  include <cmath>\n#  include <exception>\n#endif\n\n#if defined(_WIN32) && !defined(FMT_USE_WRITE_CONSOLE)\n#  include <io.h>  // _isatty\n#endif\n\n#include \"format.h\"\n\n#if FMT_USE_LOCALE && !defined(FMT_MODULE)\n#  include <locale>\n#endif\n\n#ifndef FMT_FUNC\n#  define FMT_FUNC\n#endif\n\nFMT_BEGIN_NAMESPACE\n\n#ifndef FMT_CUSTOM_ASSERT_FAIL\nFMT_FUNC void assert_fail(const char* file, int line, const char* message) {\n  // Use unchecked std::fprintf to avoid triggering another assertion when\n  // writing to stderr fails.\n  fprintf(stderr, \"%s:%d: assertion failed: %s\", file, line, message);\n  abort();\n}\n#endif\n\n#if FMT_USE_LOCALE\nnamespace detail {\nusing std::locale;\nusing std::numpunct;\nusing std::use_facet;\n}  // namespace detail\n\ntemplate <typename Locale, enable_if_t<(sizeof(Locale::collate) != 0), int>>\nlocale_ref::locale_ref(const Locale& loc) : locale_(&loc) {\n  static_assert(std::is_same<Locale, std::locale>::value, \"\");\n}\n#else\nnamespace detail {\nstruct locale {};\ntemplate <typename Char> struct numpunct {\n  auto grouping() const -> std::string { return \"\\03\"; }\n  auto thousands_sep() const -> Char { return ','; }\n  auto decimal_point() const -> Char { return '.'; }\n};\ntemplate <typename Facet> Facet use_facet(locale) { return {}; }\n}  // namespace detail\n#endif  // FMT_USE_LOCALE\n\ntemplate <typename Locale> auto locale_ref::get() const -> Locale {\n  using namespace detail;\n  static_assert(std::is_same<Locale, locale>::value, \"\");\n#if FMT_USE_LOCALE\n  if (locale_) return *static_cast<const locale*>(locale_);\n#endif\n  return locale();\n}\n\nnamespace detail {\n\nFMT_FUNC void format_error_code(detail::buffer<char>& out, int error_code,\n                                string_view message) noexcept {\n  // Report error code making sure that the output fits into\n  // inline_buffer_size to avoid dynamic memory allocation and potential\n  // bad_alloc.\n  out.try_resize(0);\n  static const char SEP[] = \": \";\n  static const char ERROR_STR[] = \"error \";\n  // Subtract 2 to account for terminating null characters in SEP and ERROR_STR.\n  size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2;\n  auto abs_value = static_cast<uint32_or_64_or_128_t<int>>(error_code);\n  if (detail::is_negative(error_code)) {\n    abs_value = 0 - abs_value;\n    ++error_code_size;\n  }\n  error_code_size += detail::to_unsigned(detail::count_digits(abs_value));\n  auto it = appender(out);\n  if (message.size() <= inline_buffer_size - error_code_size)\n    fmt::format_to(it, FMT_STRING(\"{}{}\"), message, SEP);\n  fmt::format_to(it, FMT_STRING(\"{}{}\"), ERROR_STR, error_code);\n  FMT_ASSERT(out.size() <= inline_buffer_size, \"\");\n}\n\nFMT_FUNC void do_report_error(format_func func, int error_code,\n                              const char* message) noexcept {\n  memory_buffer full_message;\n  func(full_message, error_code, message);\n  // Don't use fwrite_all because the latter may throw.\n  if (std::fwrite(full_message.data(), full_message.size(), 1, stderr) > 0)\n    std::fputc('\\n', stderr);\n}\n\n// A wrapper around fwrite that throws on error.\ninline void fwrite_all(const void* ptr, size_t count, FILE* stream) {\n  size_t written = std::fwrite(ptr, 1, count, stream);\n  if (written < count)\n    FMT_THROW(system_error(errno, FMT_STRING(\"cannot write to file\")));\n}\n\ntemplate <typename Char>\nFMT_FUNC auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result<Char> {\n  auto&& facet = use_facet<numpunct<Char>>(loc.get<locale>());\n  auto grouping = facet.grouping();\n  auto thousands_sep = grouping.empty() ? Char() : facet.thousands_sep();\n  return {std::move(grouping), thousands_sep};\n}\ntemplate <typename Char>\nFMT_FUNC auto decimal_point_impl(locale_ref loc) -> Char {\n  return use_facet<numpunct<Char>>(loc.get<locale>()).decimal_point();\n}\n\n#if FMT_USE_LOCALE\nFMT_FUNC auto write_loc(appender out, loc_value value,\n                        const format_specs& specs, locale_ref loc) -> bool {\n  auto locale = loc.get<std::locale>();\n  // We cannot use the num_put<char> facet because it may produce output in\n  // a wrong encoding.\n  using facet = format_facet<std::locale>;\n  if (std::has_facet<facet>(locale))\n    return use_facet<facet>(locale).put(out, value, specs);\n  return facet(locale).put(out, value, specs);\n}\n#endif\n}  // namespace detail\n\nFMT_FUNC void report_error(const char* message) {\n#if FMT_MSC_VERSION || defined(__NVCC__)\n  // Silence unreachable code warnings in MSVC and NVCC because these\n  // are nearly impossible to fix in a generic code.\n  volatile bool b = true;\n  if (!b) return;\n#endif\n  FMT_THROW(format_error(message));\n}\n\ntemplate <typename Locale> typename Locale::id format_facet<Locale>::id;\n\ntemplate <typename Locale> format_facet<Locale>::format_facet(Locale& loc) {\n  auto& np = detail::use_facet<detail::numpunct<char>>(loc);\n  grouping_ = np.grouping();\n  if (!grouping_.empty()) separator_ = std::string(1, np.thousands_sep());\n}\n\n#if FMT_USE_LOCALE\ntemplate <>\nFMT_API FMT_FUNC auto format_facet<std::locale>::do_put(\n    appender out, loc_value val, const format_specs& specs) const -> bool {\n  return val.visit(\n      detail::loc_writer<>{out, specs, separator_, grouping_, decimal_point_});\n}\n#endif\n\nFMT_FUNC auto vsystem_error(int error_code, string_view fmt, format_args args)\n    -> std::system_error {\n  auto ec = std::error_code(error_code, std::generic_category());\n  return std::system_error(ec, vformat(fmt, args));\n}\n\nnamespace detail {\n\ntemplate <typename F>\ninline auto operator==(basic_fp<F> x, basic_fp<F> y) -> bool {\n  return x.f == y.f && x.e == y.e;\n}\n\n// Compilers should be able to optimize this into the ror instruction.\nFMT_INLINE auto rotr(uint32_t n, uint32_t r) noexcept -> uint32_t {\n  r &= 31;\n  return (n >> r) | (n << (32 - r));\n}\nFMT_INLINE auto rotr(uint64_t n, uint32_t r) noexcept -> uint64_t {\n  r &= 63;\n  return (n >> r) | (n << (64 - r));\n}\n\n// Implementation of Dragonbox algorithm: https://github.com/jk-jeon/dragonbox.\nnamespace dragonbox {\n// Computes upper 64 bits of multiplication of a 32-bit unsigned integer and a\n// 64-bit unsigned integer.\ninline auto umul96_upper64(uint32_t x, uint64_t y) noexcept -> uint64_t {\n  return umul128_upper64(static_cast<uint64_t>(x) << 32, y);\n}\n\n// Computes lower 128 bits of multiplication of a 64-bit unsigned integer and a\n// 128-bit unsigned integer.\ninline auto umul192_lower128(uint64_t x, uint128_fallback y) noexcept\n    -> uint128_fallback {\n  uint64_t high = x * y.high();\n  uint128_fallback high_low = umul128(x, y.low());\n  return {high + high_low.high(), high_low.low()};\n}\n\n// Computes lower 64 bits of multiplication of a 32-bit unsigned integer and a\n// 64-bit unsigned integer.\ninline auto umul96_lower64(uint32_t x, uint64_t y) noexcept -> uint64_t {\n  return x * y;\n}\n\n// Various fast log computations.\ninline auto floor_log10_pow2_minus_log10_4_over_3(int e) noexcept -> int {\n  FMT_ASSERT(e <= 2936 && e >= -2985, \"too large exponent\");\n  return (e * 631305 - 261663) >> 21;\n}\n\nFMT_INLINE_VARIABLE constexpr struct div_small_pow10_infos_struct {\n  uint32_t divisor;\n  int shift_amount;\n} div_small_pow10_infos[] = {{10, 16}, {100, 16}};\n\n// Replaces n by floor(n / pow(10, N)) returning true if and only if n is\n// divisible by pow(10, N).\n// Precondition: n <= pow(10, N + 1).\ntemplate <int N>\nauto check_divisibility_and_divide_by_pow10(uint32_t& n) noexcept -> bool {\n  // The numbers below are chosen such that:\n  //   1. floor(n/d) = floor(nm / 2^k) where d=10 or d=100,\n  //   2. nm mod 2^k < m if and only if n is divisible by d,\n  // where m is magic_number, k is shift_amount\n  // and d is divisor.\n  //\n  // Item 1 is a common technique of replacing division by a constant with\n  // multiplication, see e.g. \"Division by Invariant Integers Using\n  // Multiplication\" by Granlund and Montgomery (1994). magic_number (m) is set\n  // to ceil(2^k/d) for large enough k.\n  // The idea for item 2 originates from Schubfach.\n  constexpr auto info = div_small_pow10_infos[N - 1];\n  FMT_ASSERT(n <= info.divisor * 10, \"n is too large\");\n  constexpr uint32_t magic_number =\n      (1u << info.shift_amount) / info.divisor + 1;\n  n *= magic_number;\n  const uint32_t comparison_mask = (1u << info.shift_amount) - 1;\n  bool result = (n & comparison_mask) < magic_number;\n  n >>= info.shift_amount;\n  return result;\n}\n\n// Computes floor(n / pow(10, N)) for small n and N.\n// Precondition: n <= pow(10, N + 1).\ntemplate <int N> auto small_division_by_pow10(uint32_t n) noexcept -> uint32_t {\n  constexpr auto info = div_small_pow10_infos[N - 1];\n  FMT_ASSERT(n <= info.divisor * 10, \"n is too large\");\n  constexpr uint32_t magic_number =\n      (1u << info.shift_amount) / info.divisor + 1;\n  return (n * magic_number) >> info.shift_amount;\n}\n\n// Computes floor(n / 10^(kappa + 1)) (float)\ninline auto divide_by_10_to_kappa_plus_1(uint32_t n) noexcept -> uint32_t {\n  // 1374389535 = ceil(2^37/100)\n  return static_cast<uint32_t>((static_cast<uint64_t>(n) * 1374389535) >> 37);\n}\n// Computes floor(n / 10^(kappa + 1)) (double)\ninline auto divide_by_10_to_kappa_plus_1(uint64_t n) noexcept -> uint64_t {\n  // 2361183241434822607 = ceil(2^(64+7)/1000)\n  return umul128_upper64(n, 2361183241434822607ull) >> 7;\n}\n\n// Various subroutines using pow10 cache\ntemplate <typename T> struct cache_accessor;\n\ntemplate <> struct cache_accessor<float> {\n  using carrier_uint = float_info<float>::carrier_uint;\n  using cache_entry_type = uint64_t;\n\n  static auto get_cached_power(int k) noexcept -> uint64_t {\n    FMT_ASSERT(k >= float_info<float>::min_k && k <= float_info<float>::max_k,\n               \"k is out of range\");\n    static constexpr uint64_t pow10_significands[] = {\n        0x81ceb32c4b43fcf5, 0xa2425ff75e14fc32, 0xcad2f7f5359a3b3f,\n        0xfd87b5f28300ca0e, 0x9e74d1b791e07e49, 0xc612062576589ddb,\n        0xf79687aed3eec552, 0x9abe14cd44753b53, 0xc16d9a0095928a28,\n        0xf1c90080baf72cb2, 0x971da05074da7bef, 0xbce5086492111aeb,\n        0xec1e4a7db69561a6, 0x9392ee8e921d5d08, 0xb877aa3236a4b44a,\n        0xe69594bec44de15c, 0x901d7cf73ab0acda, 0xb424dc35095cd810,\n        0xe12e13424bb40e14, 0x8cbccc096f5088cc, 0xafebff0bcb24aaff,\n        0xdbe6fecebdedd5bf, 0x89705f4136b4a598, 0xabcc77118461cefd,\n        0xd6bf94d5e57a42bd, 0x8637bd05af6c69b6, 0xa7c5ac471b478424,\n        0xd1b71758e219652c, 0x83126e978d4fdf3c, 0xa3d70a3d70a3d70b,\n        0xcccccccccccccccd, 0x8000000000000000, 0xa000000000000000,\n        0xc800000000000000, 0xfa00000000000000, 0x9c40000000000000,\n        0xc350000000000000, 0xf424000000000000, 0x9896800000000000,\n        0xbebc200000000000, 0xee6b280000000000, 0x9502f90000000000,\n        0xba43b74000000000, 0xe8d4a51000000000, 0x9184e72a00000000,\n        0xb5e620f480000000, 0xe35fa931a0000000, 0x8e1bc9bf04000000,\n        0xb1a2bc2ec5000000, 0xde0b6b3a76400000, 0x8ac7230489e80000,\n        0xad78ebc5ac620000, 0xd8d726b7177a8000, 0x878678326eac9000,\n        0xa968163f0a57b400, 0xd3c21bcecceda100, 0x84595161401484a0,\n        0xa56fa5b99019a5c8, 0xcecb8f27f4200f3a, 0x813f3978f8940985,\n        0xa18f07d736b90be6, 0xc9f2c9cd04674edf, 0xfc6f7c4045812297,\n        0x9dc5ada82b70b59e, 0xc5371912364ce306, 0xf684df56c3e01bc7,\n        0x9a130b963a6c115d, 0xc097ce7bc90715b4, 0xf0bdc21abb48db21,\n        0x96769950b50d88f5, 0xbc143fa4e250eb32, 0xeb194f8e1ae525fe,\n        0x92efd1b8d0cf37bf, 0xb7abc627050305ae, 0xe596b7b0c643c71a,\n        0x8f7e32ce7bea5c70, 0xb35dbf821ae4f38c, 0xe0352f62a19e306f};\n    return pow10_significands[k - float_info<float>::min_k];\n  }\n\n  struct compute_mul_result {\n    carrier_uint result;\n    bool is_integer;\n  };\n  struct compute_mul_parity_result {\n    bool parity;\n    bool is_integer;\n  };\n\n  static auto compute_mul(carrier_uint u,\n                          const cache_entry_type& cache) noexcept\n      -> compute_mul_result {\n    auto r = umul96_upper64(u, cache);\n    return {static_cast<carrier_uint>(r >> 32),\n            static_cast<carrier_uint>(r) == 0};\n  }\n\n  static auto compute_delta(const cache_entry_type& cache, int beta) noexcept\n      -> uint32_t {\n    return static_cast<uint32_t>(cache >> (64 - 1 - beta));\n  }\n\n  static auto compute_mul_parity(carrier_uint two_f,\n                                 const cache_entry_type& cache,\n                                 int beta) noexcept\n      -> compute_mul_parity_result {\n    FMT_ASSERT(beta >= 1, \"\");\n    FMT_ASSERT(beta < 64, \"\");\n\n    auto r = umul96_lower64(two_f, cache);\n    return {((r >> (64 - beta)) & 1) != 0,\n            static_cast<uint32_t>(r >> (32 - beta)) == 0};\n  }\n\n  static auto compute_left_endpoint_for_shorter_interval_case(\n      const cache_entry_type& cache, int beta) noexcept -> carrier_uint {\n    return static_cast<carrier_uint>(\n        (cache - (cache >> (num_significand_bits<float>() + 2))) >>\n        (64 - num_significand_bits<float>() - 1 - beta));\n  }\n\n  static auto compute_right_endpoint_for_shorter_interval_case(\n      const cache_entry_type& cache, int beta) noexcept -> carrier_uint {\n    return static_cast<carrier_uint>(\n        (cache + (cache >> (num_significand_bits<float>() + 1))) >>\n        (64 - num_significand_bits<float>() - 1 - beta));\n  }\n\n  static auto compute_round_up_for_shorter_interval_case(\n      const cache_entry_type& cache, int beta) noexcept -> carrier_uint {\n    return (static_cast<carrier_uint>(\n                cache >> (64 - num_significand_bits<float>() - 2 - beta)) +\n            1) /\n           2;\n  }\n};\n\ntemplate <> struct cache_accessor<double> {\n  using carrier_uint = float_info<double>::carrier_uint;\n  using cache_entry_type = uint128_fallback;\n\n  static auto get_cached_power(int k) noexcept -> uint128_fallback {\n    FMT_ASSERT(k >= float_info<double>::min_k && k <= float_info<double>::max_k,\n               \"k is out of range\");\n\n    static constexpr uint128_fallback pow10_significands[] = {\n#if FMT_USE_FULL_CACHE_DRAGONBOX\n      {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b},\n      {0x9faacf3df73609b1, 0x77b191618c54e9ad},\n      {0xc795830d75038c1d, 0xd59df5b9ef6a2418},\n      {0xf97ae3d0d2446f25, 0x4b0573286b44ad1e},\n      {0x9becce62836ac577, 0x4ee367f9430aec33},\n      {0xc2e801fb244576d5, 0x229c41f793cda740},\n      {0xf3a20279ed56d48a, 0x6b43527578c11110},\n      {0x9845418c345644d6, 0x830a13896b78aaaa},\n      {0xbe5691ef416bd60c, 0x23cc986bc656d554},\n      {0xedec366b11c6cb8f, 0x2cbfbe86b7ec8aa9},\n      {0x94b3a202eb1c3f39, 0x7bf7d71432f3d6aa},\n      {0xb9e08a83a5e34f07, 0xdaf5ccd93fb0cc54},\n      {0xe858ad248f5c22c9, 0xd1b3400f8f9cff69},\n      {0x91376c36d99995be, 0x23100809b9c21fa2},\n      {0xb58547448ffffb2d, 0xabd40a0c2832a78b},\n      {0xe2e69915b3fff9f9, 0x16c90c8f323f516d},\n      {0x8dd01fad907ffc3b, 0xae3da7d97f6792e4},\n      {0xb1442798f49ffb4a, 0x99cd11cfdf41779d},\n      {0xdd95317f31c7fa1d, 0x40405643d711d584},\n      {0x8a7d3eef7f1cfc52, 0x482835ea666b2573},\n      {0xad1c8eab5ee43b66, 0xda3243650005eed0},\n      {0xd863b256369d4a40, 0x90bed43e40076a83},\n      {0x873e4f75e2224e68, 0x5a7744a6e804a292},\n      {0xa90de3535aaae202, 0x711515d0a205cb37},\n      {0xd3515c2831559a83, 0x0d5a5b44ca873e04},\n      {0x8412d9991ed58091, 0xe858790afe9486c3},\n      {0xa5178fff668ae0b6, 0x626e974dbe39a873},\n      {0xce5d73ff402d98e3, 0xfb0a3d212dc81290},\n      {0x80fa687f881c7f8e, 0x7ce66634bc9d0b9a},\n      {0xa139029f6a239f72, 0x1c1fffc1ebc44e81},\n      {0xc987434744ac874e, 0xa327ffb266b56221},\n      {0xfbe9141915d7a922, 0x4bf1ff9f0062baa9},\n      {0x9d71ac8fada6c9b5, 0x6f773fc3603db4aa},\n      {0xc4ce17b399107c22, 0xcb550fb4384d21d4},\n      {0xf6019da07f549b2b, 0x7e2a53a146606a49},\n      {0x99c102844f94e0fb, 0x2eda7444cbfc426e},\n      {0xc0314325637a1939, 0xfa911155fefb5309},\n      {0xf03d93eebc589f88, 0x793555ab7eba27cb},\n      {0x96267c7535b763b5, 0x4bc1558b2f3458df},\n      {0xbbb01b9283253ca2, 0x9eb1aaedfb016f17},\n      {0xea9c227723ee8bcb, 0x465e15a979c1cadd},\n      {0x92a1958a7675175f, 0x0bfacd89ec191eca},\n      {0xb749faed14125d36, 0xcef980ec671f667c},\n      {0xe51c79a85916f484, 0x82b7e12780e7401b},\n      {0x8f31cc0937ae58d2, 0xd1b2ecb8b0908811},\n      {0xb2fe3f0b8599ef07, 0x861fa7e6dcb4aa16},\n      {0xdfbdcece67006ac9, 0x67a791e093e1d49b},\n      {0x8bd6a141006042bd, 0xe0c8bb2c5c6d24e1},\n      {0xaecc49914078536d, 0x58fae9f773886e19},\n      {0xda7f5bf590966848, 0xaf39a475506a899f},\n      {0x888f99797a5e012d, 0x6d8406c952429604},\n      {0xaab37fd7d8f58178, 0xc8e5087ba6d33b84},\n      {0xd5605fcdcf32e1d6, 0xfb1e4a9a90880a65},\n      {0x855c3be0a17fcd26, 0x5cf2eea09a550680},\n      {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f},\n      {0xd0601d8efc57b08b, 0xf13b94daf124da27},\n      {0x823c12795db6ce57, 0x76c53d08d6b70859},\n      {0xa2cb1717b52481ed, 0x54768c4b0c64ca6f},\n      {0xcb7ddcdda26da268, 0xa9942f5dcf7dfd0a},\n      {0xfe5d54150b090b02, 0xd3f93b35435d7c4d},\n      {0x9efa548d26e5a6e1, 0xc47bc5014a1a6db0},\n      {0xc6b8e9b0709f109a, 0x359ab6419ca1091c},\n      {0xf867241c8cc6d4c0, 0xc30163d203c94b63},\n      {0x9b407691d7fc44f8, 0x79e0de63425dcf1e},\n      {0xc21094364dfb5636, 0x985915fc12f542e5},\n      {0xf294b943e17a2bc4, 0x3e6f5b7b17b2939e},\n      {0x979cf3ca6cec5b5a, 0xa705992ceecf9c43},\n      {0xbd8430bd08277231, 0x50c6ff782a838354},\n      {0xece53cec4a314ebd, 0xa4f8bf5635246429},\n      {0x940f4613ae5ed136, 0x871b7795e136be9a},\n      {0xb913179899f68584, 0x28e2557b59846e40},\n      {0xe757dd7ec07426e5, 0x331aeada2fe589d0},\n      {0x9096ea6f3848984f, 0x3ff0d2c85def7622},\n      {0xb4bca50b065abe63, 0x0fed077a756b53aa},\n      {0xe1ebce4dc7f16dfb, 0xd3e8495912c62895},\n      {0x8d3360f09cf6e4bd, 0x64712dd7abbbd95d},\n      {0xb080392cc4349dec, 0xbd8d794d96aacfb4},\n      {0xdca04777f541c567, 0xecf0d7a0fc5583a1},\n      {0x89e42caaf9491b60, 0xf41686c49db57245},\n      {0xac5d37d5b79b6239, 0x311c2875c522ced6},\n      {0xd77485cb25823ac7, 0x7d633293366b828c},\n      {0x86a8d39ef77164bc, 0xae5dff9c02033198},\n      {0xa8530886b54dbdeb, 0xd9f57f830283fdfd},\n      {0xd267caa862a12d66, 0xd072df63c324fd7c},\n      {0x8380dea93da4bc60, 0x4247cb9e59f71e6e},\n      {0xa46116538d0deb78, 0x52d9be85f074e609},\n      {0xcd795be870516656, 0x67902e276c921f8c},\n      {0x806bd9714632dff6, 0x00ba1cd8a3db53b7},\n      {0xa086cfcd97bf97f3, 0x80e8a40eccd228a5},\n      {0xc8a883c0fdaf7df0, 0x6122cd128006b2ce},\n      {0xfad2a4b13d1b5d6c, 0x796b805720085f82},\n      {0x9cc3a6eec6311a63, 0xcbe3303674053bb1},\n      {0xc3f490aa77bd60fc, 0xbedbfc4411068a9d},\n      {0xf4f1b4d515acb93b, 0xee92fb5515482d45},\n      {0x991711052d8bf3c5, 0x751bdd152d4d1c4b},\n      {0xbf5cd54678eef0b6, 0xd262d45a78a0635e},\n      {0xef340a98172aace4, 0x86fb897116c87c35},\n      {0x9580869f0e7aac0e, 0xd45d35e6ae3d4da1},\n      {0xbae0a846d2195712, 0x8974836059cca10a},\n      {0xe998d258869facd7, 0x2bd1a438703fc94c},\n      {0x91ff83775423cc06, 0x7b6306a34627ddd0},\n      {0xb67f6455292cbf08, 0x1a3bc84c17b1d543},\n      {0xe41f3d6a7377eeca, 0x20caba5f1d9e4a94},\n      {0x8e938662882af53e, 0x547eb47b7282ee9d},\n      {0xb23867fb2a35b28d, 0xe99e619a4f23aa44},\n      {0xdec681f9f4c31f31, 0x6405fa00e2ec94d5},\n      {0x8b3c113c38f9f37e, 0xde83bc408dd3dd05},\n      {0xae0b158b4738705e, 0x9624ab50b148d446},\n      {0xd98ddaee19068c76, 0x3badd624dd9b0958},\n      {0x87f8a8d4cfa417c9, 0xe54ca5d70a80e5d7},\n      {0xa9f6d30a038d1dbc, 0x5e9fcf4ccd211f4d},\n      {0xd47487cc8470652b, 0x7647c32000696720},\n      {0x84c8d4dfd2c63f3b, 0x29ecd9f40041e074},\n      {0xa5fb0a17c777cf09, 0xf468107100525891},\n      {0xcf79cc9db955c2cc, 0x7182148d4066eeb5},\n      {0x81ac1fe293d599bf, 0xc6f14cd848405531},\n      {0xa21727db38cb002f, 0xb8ada00e5a506a7d},\n      {0xca9cf1d206fdc03b, 0xa6d90811f0e4851d},\n      {0xfd442e4688bd304a, 0x908f4a166d1da664},\n      {0x9e4a9cec15763e2e, 0x9a598e4e043287ff},\n      {0xc5dd44271ad3cdba, 0x40eff1e1853f29fe},\n      {0xf7549530e188c128, 0xd12bee59e68ef47d},\n      {0x9a94dd3e8cf578b9, 0x82bb74f8301958cf},\n      {0xc13a148e3032d6e7, 0xe36a52363c1faf02},\n      {0xf18899b1bc3f8ca1, 0xdc44e6c3cb279ac2},\n      {0x96f5600f15a7b7e5, 0x29ab103a5ef8c0ba},\n      {0xbcb2b812db11a5de, 0x7415d448f6b6f0e8},\n      {0xebdf661791d60f56, 0x111b495b3464ad22},\n      {0x936b9fcebb25c995, 0xcab10dd900beec35},\n      {0xb84687c269ef3bfb, 0x3d5d514f40eea743},\n      {0xe65829b3046b0afa, 0x0cb4a5a3112a5113},\n      {0x8ff71a0fe2c2e6dc, 0x47f0e785eaba72ac},\n      {0xb3f4e093db73a093, 0x59ed216765690f57},\n      {0xe0f218b8d25088b8, 0x306869c13ec3532d},\n      {0x8c974f7383725573, 0x1e414218c73a13fc},\n      {0xafbd2350644eeacf, 0xe5d1929ef90898fb},\n      {0xdbac6c247d62a583, 0xdf45f746b74abf3a},\n      {0x894bc396ce5da772, 0x6b8bba8c328eb784},\n      {0xab9eb47c81f5114f, 0x066ea92f3f326565},\n      {0xd686619ba27255a2, 0xc80a537b0efefebe},\n      {0x8613fd0145877585, 0xbd06742ce95f5f37},\n      {0xa798fc4196e952e7, 0x2c48113823b73705},\n      {0xd17f3b51fca3a7a0, 0xf75a15862ca504c6},\n      {0x82ef85133de648c4, 0x9a984d73dbe722fc},\n      {0xa3ab66580d5fdaf5, 0xc13e60d0d2e0ebbb},\n      {0xcc963fee10b7d1b3, 0x318df905079926a9},\n      {0xffbbcfe994e5c61f, 0xfdf17746497f7053},\n      {0x9fd561f1fd0f9bd3, 0xfeb6ea8bedefa634},\n      {0xc7caba6e7c5382c8, 0xfe64a52ee96b8fc1},\n      {0xf9bd690a1b68637b, 0x3dfdce7aa3c673b1},\n      {0x9c1661a651213e2d, 0x06bea10ca65c084f},\n      {0xc31bfa0fe5698db8, 0x486e494fcff30a63},\n      {0xf3e2f893dec3f126, 0x5a89dba3c3efccfb},\n      {0x986ddb5c6b3a76b7, 0xf89629465a75e01d},\n      {0xbe89523386091465, 0xf6bbb397f1135824},\n      {0xee2ba6c0678b597f, 0x746aa07ded582e2d},\n      {0x94db483840b717ef, 0xa8c2a44eb4571cdd},\n      {0xba121a4650e4ddeb, 0x92f34d62616ce414},\n      {0xe896a0d7e51e1566, 0x77b020baf9c81d18},\n      {0x915e2486ef32cd60, 0x0ace1474dc1d122f},\n      {0xb5b5ada8aaff80b8, 0x0d819992132456bb},\n      {0xe3231912d5bf60e6, 0x10e1fff697ed6c6a},\n      {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2},\n      {0xb1736b96b6fd83b3, 0xbd308ff8a6b17cb3},\n      {0xddd0467c64bce4a0, 0xac7cb3f6d05ddbdf},\n      {0x8aa22c0dbef60ee4, 0x6bcdf07a423aa96c},\n      {0xad4ab7112eb3929d, 0x86c16c98d2c953c7},\n      {0xd89d64d57a607744, 0xe871c7bf077ba8b8},\n      {0x87625f056c7c4a8b, 0x11471cd764ad4973},\n      {0xa93af6c6c79b5d2d, 0xd598e40d3dd89bd0},\n      {0xd389b47879823479, 0x4aff1d108d4ec2c4},\n      {0x843610cb4bf160cb, 0xcedf722a585139bb},\n      {0xa54394fe1eedb8fe, 0xc2974eb4ee658829},\n      {0xce947a3da6a9273e, 0x733d226229feea33},\n      {0x811ccc668829b887, 0x0806357d5a3f5260},\n      {0xa163ff802a3426a8, 0xca07c2dcb0cf26f8},\n      {0xc9bcff6034c13052, 0xfc89b393dd02f0b6},\n      {0xfc2c3f3841f17c67, 0xbbac2078d443ace3},\n      {0x9d9ba7832936edc0, 0xd54b944b84aa4c0e},\n      {0xc5029163f384a931, 0x0a9e795e65d4df12},\n      {0xf64335bcf065d37d, 0x4d4617b5ff4a16d6},\n      {0x99ea0196163fa42e, 0x504bced1bf8e4e46},\n      {0xc06481fb9bcf8d39, 0xe45ec2862f71e1d7},\n      {0xf07da27a82c37088, 0x5d767327bb4e5a4d},\n      {0x964e858c91ba2655, 0x3a6a07f8d510f870},\n      {0xbbe226efb628afea, 0x890489f70a55368c},\n      {0xeadab0aba3b2dbe5, 0x2b45ac74ccea842f},\n      {0x92c8ae6b464fc96f, 0x3b0b8bc90012929e},\n      {0xb77ada0617e3bbcb, 0x09ce6ebb40173745},\n      {0xe55990879ddcaabd, 0xcc420a6a101d0516},\n      {0x8f57fa54c2a9eab6, 0x9fa946824a12232e},\n      {0xb32df8e9f3546564, 0x47939822dc96abfa},\n      {0xdff9772470297ebd, 0x59787e2b93bc56f8},\n      {0x8bfbea76c619ef36, 0x57eb4edb3c55b65b},\n      {0xaefae51477a06b03, 0xede622920b6b23f2},\n      {0xdab99e59958885c4, 0xe95fab368e45ecee},\n      {0x88b402f7fd75539b, 0x11dbcb0218ebb415},\n      {0xaae103b5fcd2a881, 0xd652bdc29f26a11a},\n      {0xd59944a37c0752a2, 0x4be76d3346f04960},\n      {0x857fcae62d8493a5, 0x6f70a4400c562ddc},\n      {0xa6dfbd9fb8e5b88e, 0xcb4ccd500f6bb953},\n      {0xd097ad07a71f26b2, 0x7e2000a41346a7a8},\n      {0x825ecc24c873782f, 0x8ed400668c0c28c9},\n      {0xa2f67f2dfa90563b, 0x728900802f0f32fb},\n      {0xcbb41ef979346bca, 0x4f2b40a03ad2ffba},\n      {0xfea126b7d78186bc, 0xe2f610c84987bfa9},\n      {0x9f24b832e6b0f436, 0x0dd9ca7d2df4d7ca},\n      {0xc6ede63fa05d3143, 0x91503d1c79720dbc},\n      {0xf8a95fcf88747d94, 0x75a44c6397ce912b},\n      {0x9b69dbe1b548ce7c, 0xc986afbe3ee11abb},\n      {0xc24452da229b021b, 0xfbe85badce996169},\n      {0xf2d56790ab41c2a2, 0xfae27299423fb9c4},\n      {0x97c560ba6b0919a5, 0xdccd879fc967d41b},\n      {0xbdb6b8e905cb600f, 0x5400e987bbc1c921},\n      {0xed246723473e3813, 0x290123e9aab23b69},\n      {0x9436c0760c86e30b, 0xf9a0b6720aaf6522},\n      {0xb94470938fa89bce, 0xf808e40e8d5b3e6a},\n      {0xe7958cb87392c2c2, 0xb60b1d1230b20e05},\n      {0x90bd77f3483bb9b9, 0xb1c6f22b5e6f48c3},\n      {0xb4ecd5f01a4aa828, 0x1e38aeb6360b1af4},\n      {0xe2280b6c20dd5232, 0x25c6da63c38de1b1},\n      {0x8d590723948a535f, 0x579c487e5a38ad0f},\n      {0xb0af48ec79ace837, 0x2d835a9df0c6d852},\n      {0xdcdb1b2798182244, 0xf8e431456cf88e66},\n      {0x8a08f0f8bf0f156b, 0x1b8e9ecb641b5900},\n      {0xac8b2d36eed2dac5, 0xe272467e3d222f40},\n      {0xd7adf884aa879177, 0x5b0ed81dcc6abb10},\n      {0x86ccbb52ea94baea, 0x98e947129fc2b4ea},\n      {0xa87fea27a539e9a5, 0x3f2398d747b36225},\n      {0xd29fe4b18e88640e, 0x8eec7f0d19a03aae},\n      {0x83a3eeeef9153e89, 0x1953cf68300424ad},\n      {0xa48ceaaab75a8e2b, 0x5fa8c3423c052dd8},\n      {0xcdb02555653131b6, 0x3792f412cb06794e},\n      {0x808e17555f3ebf11, 0xe2bbd88bbee40bd1},\n      {0xa0b19d2ab70e6ed6, 0x5b6aceaeae9d0ec5},\n      {0xc8de047564d20a8b, 0xf245825a5a445276},\n      {0xfb158592be068d2e, 0xeed6e2f0f0d56713},\n      {0x9ced737bb6c4183d, 0x55464dd69685606c},\n      {0xc428d05aa4751e4c, 0xaa97e14c3c26b887},\n      {0xf53304714d9265df, 0xd53dd99f4b3066a9},\n      {0x993fe2c6d07b7fab, 0xe546a8038efe402a},\n      {0xbf8fdb78849a5f96, 0xde98520472bdd034},\n      {0xef73d256a5c0f77c, 0x963e66858f6d4441},\n      {0x95a8637627989aad, 0xdde7001379a44aa9},\n      {0xbb127c53b17ec159, 0x5560c018580d5d53},\n      {0xe9d71b689dde71af, 0xaab8f01e6e10b4a7},\n      {0x9226712162ab070d, 0xcab3961304ca70e9},\n      {0xb6b00d69bb55c8d1, 0x3d607b97c5fd0d23},\n      {0xe45c10c42a2b3b05, 0x8cb89a7db77c506b},\n      {0x8eb98a7a9a5b04e3, 0x77f3608e92adb243},\n      {0xb267ed1940f1c61c, 0x55f038b237591ed4},\n      {0xdf01e85f912e37a3, 0x6b6c46dec52f6689},\n      {0x8b61313bbabce2c6, 0x2323ac4b3b3da016},\n      {0xae397d8aa96c1b77, 0xabec975e0a0d081b},\n      {0xd9c7dced53c72255, 0x96e7bd358c904a22},\n      {0x881cea14545c7575, 0x7e50d64177da2e55},\n      {0xaa242499697392d2, 0xdde50bd1d5d0b9ea},\n      {0xd4ad2dbfc3d07787, 0x955e4ec64b44e865},\n      {0x84ec3c97da624ab4, 0xbd5af13bef0b113f},\n      {0xa6274bbdd0fadd61, 0xecb1ad8aeacdd58f},\n      {0xcfb11ead453994ba, 0x67de18eda5814af3},\n      {0x81ceb32c4b43fcf4, 0x80eacf948770ced8},\n      {0xa2425ff75e14fc31, 0xa1258379a94d028e},\n      {0xcad2f7f5359a3b3e, 0x096ee45813a04331},\n      {0xfd87b5f28300ca0d, 0x8bca9d6e188853fd},\n      {0x9e74d1b791e07e48, 0x775ea264cf55347e},\n      {0xc612062576589dda, 0x95364afe032a819e},\n      {0xf79687aed3eec551, 0x3a83ddbd83f52205},\n      {0x9abe14cd44753b52, 0xc4926a9672793543},\n      {0xc16d9a0095928a27, 0x75b7053c0f178294},\n      {0xf1c90080baf72cb1, 0x5324c68b12dd6339},\n      {0x971da05074da7bee, 0xd3f6fc16ebca5e04},\n      {0xbce5086492111aea, 0x88f4bb1ca6bcf585},\n      {0xec1e4a7db69561a5, 0x2b31e9e3d06c32e6},\n      {0x9392ee8e921d5d07, 0x3aff322e62439fd0},\n      {0xb877aa3236a4b449, 0x09befeb9fad487c3},\n      {0xe69594bec44de15b, 0x4c2ebe687989a9b4},\n      {0x901d7cf73ab0acd9, 0x0f9d37014bf60a11},\n      {0xb424dc35095cd80f, 0x538484c19ef38c95},\n      {0xe12e13424bb40e13, 0x2865a5f206b06fba},\n      {0x8cbccc096f5088cb, 0xf93f87b7442e45d4},\n      {0xafebff0bcb24aafe, 0xf78f69a51539d749},\n      {0xdbe6fecebdedd5be, 0xb573440e5a884d1c},\n      {0x89705f4136b4a597, 0x31680a88f8953031},\n      {0xabcc77118461cefc, 0xfdc20d2b36ba7c3e},\n      {0xd6bf94d5e57a42bc, 0x3d32907604691b4d},\n      {0x8637bd05af6c69b5, 0xa63f9a49c2c1b110},\n      {0xa7c5ac471b478423, 0x0fcf80dc33721d54},\n      {0xd1b71758e219652b, 0xd3c36113404ea4a9},\n      {0x83126e978d4fdf3b, 0x645a1cac083126ea},\n      {0xa3d70a3d70a3d70a, 0x3d70a3d70a3d70a4},\n      {0xcccccccccccccccc, 0xcccccccccccccccd},\n      {0x8000000000000000, 0x0000000000000000},\n      {0xa000000000000000, 0x0000000000000000},\n      {0xc800000000000000, 0x0000000000000000},\n      {0xfa00000000000000, 0x0000000000000000},\n      {0x9c40000000000000, 0x0000000000000000},\n      {0xc350000000000000, 0x0000000000000000},\n      {0xf424000000000000, 0x0000000000000000},\n      {0x9896800000000000, 0x0000000000000000},\n      {0xbebc200000000000, 0x0000000000000000},\n      {0xee6b280000000000, 0x0000000000000000},\n      {0x9502f90000000000, 0x0000000000000000},\n      {0xba43b74000000000, 0x0000000000000000},\n      {0xe8d4a51000000000, 0x0000000000000000},\n      {0x9184e72a00000000, 0x0000000000000000},\n      {0xb5e620f480000000, 0x0000000000000000},\n      {0xe35fa931a0000000, 0x0000000000000000},\n      {0x8e1bc9bf04000000, 0x0000000000000000},\n      {0xb1a2bc2ec5000000, 0x0000000000000000},\n      {0xde0b6b3a76400000, 0x0000000000000000},\n      {0x8ac7230489e80000, 0x0000000000000000},\n      {0xad78ebc5ac620000, 0x0000000000000000},\n      {0xd8d726b7177a8000, 0x0000000000000000},\n      {0x878678326eac9000, 0x0000000000000000},\n      {0xa968163f0a57b400, 0x0000000000000000},\n      {0xd3c21bcecceda100, 0x0000000000000000},\n      {0x84595161401484a0, 0x0000000000000000},\n      {0xa56fa5b99019a5c8, 0x0000000000000000},\n      {0xcecb8f27f4200f3a, 0x0000000000000000},\n      {0x813f3978f8940984, 0x4000000000000000},\n      {0xa18f07d736b90be5, 0x5000000000000000},\n      {0xc9f2c9cd04674ede, 0xa400000000000000},\n      {0xfc6f7c4045812296, 0x4d00000000000000},\n      {0x9dc5ada82b70b59d, 0xf020000000000000},\n      {0xc5371912364ce305, 0x6c28000000000000},\n      {0xf684df56c3e01bc6, 0xc732000000000000},\n      {0x9a130b963a6c115c, 0x3c7f400000000000},\n      {0xc097ce7bc90715b3, 0x4b9f100000000000},\n      {0xf0bdc21abb48db20, 0x1e86d40000000000},\n      {0x96769950b50d88f4, 0x1314448000000000},\n      {0xbc143fa4e250eb31, 0x17d955a000000000},\n      {0xeb194f8e1ae525fd, 0x5dcfab0800000000},\n      {0x92efd1b8d0cf37be, 0x5aa1cae500000000},\n      {0xb7abc627050305ad, 0xf14a3d9e40000000},\n      {0xe596b7b0c643c719, 0x6d9ccd05d0000000},\n      {0x8f7e32ce7bea5c6f, 0xe4820023a2000000},\n      {0xb35dbf821ae4f38b, 0xdda2802c8a800000},\n      {0xe0352f62a19e306e, 0xd50b2037ad200000},\n      {0x8c213d9da502de45, 0x4526f422cc340000},\n      {0xaf298d050e4395d6, 0x9670b12b7f410000},\n      {0xdaf3f04651d47b4c, 0x3c0cdd765f114000},\n      {0x88d8762bf324cd0f, 0xa5880a69fb6ac800},\n      {0xab0e93b6efee0053, 0x8eea0d047a457a00},\n      {0xd5d238a4abe98068, 0x72a4904598d6d880},\n      {0x85a36366eb71f041, 0x47a6da2b7f864750},\n      {0xa70c3c40a64e6c51, 0x999090b65f67d924},\n      {0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d},\n      {0x82818f1281ed449f, 0xbff8f10e7a8921a5},\n      {0xa321f2d7226895c7, 0xaff72d52192b6a0e},\n      {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764491},\n      {0xfee50b7025c36a08, 0x02f236d04753d5b5},\n      {0x9f4f2726179a2245, 0x01d762422c946591},\n      {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef6},\n      {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb3},\n      {0x9b934c3b330c8577, 0x63cc55f49f88eb30},\n      {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fc},\n      {0xf316271c7fc3908a, 0x8bef464e3945ef7b},\n      {0x97edd871cfda3a56, 0x97758bf0e3cbb5ad},\n      {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea318},\n      {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bde},\n      {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6b},\n      {0xb975d6b6ee39e436, 0xb3e2fd538e122b45},\n      {0xe7d34c64a9c85d44, 0x60dbbca87196b617},\n      {0x90e40fbeea1d3a4a, 0xbc8955e946fe31ce},\n      {0xb51d13aea4a488dd, 0x6babab6398bdbe42},\n      {0xe264589a4dcdab14, 0xc696963c7eed2dd2},\n      {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca3},\n      {0xb0de65388cc8ada8, 0x3b25a55f43294bcc},\n      {0xdd15fe86affad912, 0x49ef0eb713f39ebf},\n      {0x8a2dbf142dfcc7ab, 0x6e3569326c784338},\n      {0xacb92ed9397bf996, 0x49c2c37f07965405},\n      {0xd7e77a8f87daf7fb, 0xdc33745ec97be907},\n      {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a4},\n      {0xa8acd7c0222311bc, 0xc40832ea0d68ce0d},\n      {0xd2d80db02aabd62b, 0xf50a3fa490c30191},\n      {0x83c7088e1aab65db, 0x792667c6da79e0fb},\n      {0xa4b8cab1a1563f52, 0x577001b891185939},\n      {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87},\n      {0x80b05e5ac60b6178, 0x544f8158315b05b5},\n      {0xa0dc75f1778e39d6, 0x696361ae3db1c722},\n      {0xc913936dd571c84c, 0x03bc3a19cd1e38ea},\n      {0xfb5878494ace3a5f, 0x04ab48a04065c724},\n      {0x9d174b2dcec0e47b, 0x62eb0d64283f9c77},\n      {0xc45d1df942711d9a, 0x3ba5d0bd324f8395},\n      {0xf5746577930d6500, 0xca8f44ec7ee3647a},\n      {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecc},\n      {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67f},\n      {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101f},\n      {0x95d04aee3b80ece5, 0xbba1f1d158724a13},\n      {0xbb445da9ca61281f, 0x2a8a6e45ae8edc98},\n      {0xea1575143cf97226, 0xf52d09d71a3293be},\n      {0x924d692ca61be758, 0x593c2626705f9c57},\n      {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836d},\n      {0xe498f455c38b997a, 0x0b6dfb9c0f956448},\n      {0x8edf98b59a373fec, 0x4724bd4189bd5ead},\n      {0xb2977ee300c50fe7, 0x58edec91ec2cb658},\n      {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ee},\n      {0x8b865b215899f46c, 0xbd79e0d20082ee75},\n      {0xae67f1e9aec07187, 0xecd8590680a3aa12},\n      {0xda01ee641a708de9, 0xe80e6f4820cc9496},\n      {0x884134fe908658b2, 0x3109058d147fdcde},\n      {0xaa51823e34a7eede, 0xbd4b46f0599fd416},\n      {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91b},\n      {0x850fadc09923329e, 0x03e2cf6bc604ddb1},\n      {0xa6539930bf6bff45, 0x84db8346b786151d},\n      {0xcfe87f7cef46ff16, 0xe612641865679a64},\n      {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07f},\n      {0xa26da3999aef7749, 0xe3be5e330f38f09e},\n      {0xcb090c8001ab551c, 0x5cadf5bfd3072cc6},\n      {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f7},\n      {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afb},\n      {0xc646d63501a1511d, 0xb281e1fd541501b9},\n      {0xf7d88bc24209a565, 0x1f225a7ca91a4227},\n      {0x9ae757596946075f, 0x3375788de9b06959},\n      {0xc1a12d2fc3978937, 0x0052d6b1641c83af},\n      {0xf209787bb47d6b84, 0xc0678c5dbd23a49b},\n      {0x9745eb4d50ce6332, 0xf840b7ba963646e1},\n      {0xbd176620a501fbff, 0xb650e5a93bc3d899},\n      {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebf},\n      {0x93ba47c980e98cdf, 0xc66f336c36b10138},\n      {0xb8a8d9bbe123f017, 0xb80b0047445d4185},\n      {0xe6d3102ad96cec1d, 0xa60dc059157491e6},\n      {0x9043ea1ac7e41392, 0x87c89837ad68db30},\n      {0xb454e4a179dd1877, 0x29babe4598c311fc},\n      {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67b},\n      {0x8ce2529e2734bb1d, 0x1899e4a65f58660d},\n      {0xb01ae745b101e9e4, 0x5ec05dcff72e7f90},\n      {0xdc21a1171d42645d, 0x76707543f4fa1f74},\n      {0x899504ae72497eba, 0x6a06494a791c53a9},\n      {0xabfa45da0edbde69, 0x0487db9d17636893},\n      {0xd6f8d7509292d603, 0x45a9d2845d3c42b7},\n      {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3},\n      {0xa7f26836f282b732, 0x8e6cac7768d7141f},\n      {0xd1ef0244af2364ff, 0x3207d795430cd927},\n      {0x8335616aed761f1f, 0x7f44e6bd49e807b9},\n      {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a7},\n      {0xcd036837130890a1, 0x36dba887c37a8c10},\n      {0x802221226be55a64, 0xc2494954da2c978a},\n      {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6d},\n      {0xc83553c5c8965d3d, 0x6f92829494e5acc8},\n      {0xfa42a8b73abbf48c, 0xcb772339ba1f17fa},\n      {0x9c69a97284b578d7, 0xff2a760414536efc},\n      {0xc38413cf25e2d70d, 0xfef5138519684abb},\n      {0xf46518c2ef5b8cd1, 0x7eb258665fc25d6a},\n      {0x98bf2f79d5993802, 0xef2f773ffbd97a62},\n      {0xbeeefb584aff8603, 0xaafb550ffacfd8fb},\n      {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf39},\n      {0x952ab45cfa97a0b2, 0xdd945a747bf26184},\n      {0xba756174393d88df, 0x94f971119aeef9e5},\n      {0xe912b9d1478ceb17, 0x7a37cd5601aab85e},\n      {0x91abb422ccb812ee, 0xac62e055c10ab33b},\n      {0xb616a12b7fe617aa, 0x577b986b314d600a},\n      {0xe39c49765fdf9d94, 0xed5a7e85fda0b80c},\n      {0x8e41ade9fbebc27d, 0x14588f13be847308},\n      {0xb1d219647ae6b31c, 0x596eb2d8ae258fc9},\n      {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bc},\n      {0x8aec23d680043bee, 0x25de7bb9480d5855},\n      {0xada72ccc20054ae9, 0xaf561aa79a10ae6b},\n      {0xd910f7ff28069da4, 0x1b2ba1518094da05},\n      {0x87aa9aff79042286, 0x90fb44d2f05d0843},\n      {0xa99541bf57452b28, 0x353a1607ac744a54},\n      {0xd3fa922f2d1675f2, 0x42889b8997915ce9},\n      {0x847c9b5d7c2e09b7, 0x69956135febada12},\n      {0xa59bc234db398c25, 0x43fab9837e699096},\n      {0xcf02b2c21207ef2e, 0x94f967e45e03f4bc},\n      {0x8161afb94b44f57d, 0x1d1be0eebac278f6},\n      {0xa1ba1ba79e1632dc, 0x6462d92a69731733},\n      {0xca28a291859bbf93, 0x7d7b8f7503cfdcff},\n      {0xfcb2cb35e702af78, 0x5cda735244c3d43f},\n      {0x9defbf01b061adab, 0x3a0888136afa64a8},\n      {0xc56baec21c7a1916, 0x088aaa1845b8fdd1},\n      {0xf6c69a72a3989f5b, 0x8aad549e57273d46},\n      {0x9a3c2087a63f6399, 0x36ac54e2f678864c},\n      {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7de},\n      {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d6},\n      {0x969eb7c47859e743, 0x9f644ae5a4b1b326},\n      {0xbc4665b596706114, 0x873d5d9f0dde1fef},\n      {0xeb57ff22fc0c7959, 0xa90cb506d155a7eb},\n      {0x9316ff75dd87cbd8, 0x09a7f12442d588f3},\n      {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb30},\n      {0xe5d3ef282a242e81, 0x8f1668c8a86da5fb},\n      {0x8fa475791a569d10, 0xf96e017d694487bd},\n      {0xb38d92d760ec4455, 0x37c981dcc395a9ad},\n      {0xe070f78d3927556a, 0x85bbe253f47b1418},\n      {0x8c469ab843b89562, 0x93956d7478ccec8f},\n      {0xaf58416654a6babb, 0x387ac8d1970027b3},\n      {0xdb2e51bfe9d0696a, 0x06997b05fcc0319f},\n      {0x88fcf317f22241e2, 0x441fece3bdf81f04},\n      {0xab3c2fddeeaad25a, 0xd527e81cad7626c4},\n      {0xd60b3bd56a5586f1, 0x8a71e223d8d3b075},\n      {0x85c7056562757456, 0xf6872d5667844e4a},\n      {0xa738c6bebb12d16c, 0xb428f8ac016561dc},\n      {0xd106f86e69d785c7, 0xe13336d701beba53},\n      {0x82a45b450226b39c, 0xecc0024661173474},\n      {0xa34d721642b06084, 0x27f002d7f95d0191},\n      {0xcc20ce9bd35c78a5, 0x31ec038df7b441f5},\n      {0xff290242c83396ce, 0x7e67047175a15272},\n      {0x9f79a169bd203e41, 0x0f0062c6e984d387},\n      {0xc75809c42c684dd1, 0x52c07b78a3e60869},\n      {0xf92e0c3537826145, 0xa7709a56ccdf8a83},\n      {0x9bbcc7a142b17ccb, 0x88a66076400bb692},\n      {0xc2abf989935ddbfe, 0x6acff893d00ea436},\n      {0xf356f7ebf83552fe, 0x0583f6b8c4124d44},\n      {0x98165af37b2153de, 0xc3727a337a8b704b},\n      {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5d},\n      {0xeda2ee1c7064130c, 0x1162def06f79df74},\n      {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba9},\n      {0xb9a74a0637ce2ee1, 0x6d953e2bd7173693},\n      {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0438},\n      {0x910ab1d4db9914a0, 0x1d9c9892400a22a3},\n      {0xb54d5e4a127f59c8, 0x2503beb6d00cab4c},\n      {0xe2a0b5dc971f303a, 0x2e44ae64840fd61e},\n      {0x8da471a9de737e24, 0x5ceaecfed289e5d3},\n      {0xb10d8e1456105dad, 0x7425a83e872c5f48},\n      {0xdd50f1996b947518, 0xd12f124e28f7771a},\n      {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa70},\n      {0xace73cbfdc0bfb7b, 0x636cc64d1001550c},\n      {0xd8210befd30efa5a, 0x3c47f7e05401aa4f},\n      {0x8714a775e3e95c78, 0x65acfaec34810a72},\n      {0xa8d9d1535ce3b396, 0x7f1839a741a14d0e},\n      {0xd31045a8341ca07c, 0x1ede48111209a051},\n      {0x83ea2b892091e44d, 0x934aed0aab460433},\n      {0xa4e4b66b68b65d60, 0xf81da84d56178540},\n      {0xce1de40642e3f4b9, 0x36251260ab9d668f},\n      {0x80d2ae83e9ce78f3, 0xc1d72b7c6b42601a},\n      {0xa1075a24e4421730, 0xb24cf65b8612f820},\n      {0xc94930ae1d529cfc, 0xdee033f26797b628},\n      {0xfb9b7cd9a4a7443c, 0x169840ef017da3b2},\n      {0x9d412e0806e88aa5, 0x8e1f289560ee864f},\n      {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e3},\n      {0xf5b5d7ec8acb58a2, 0xae10af696774b1dc},\n      {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef2a},\n      {0xbff610b0cc6edd3f, 0x17fd090a58d32af4},\n      {0xeff394dcff8a948e, 0xddfc4b4cef07f5b1},\n      {0x95f83d0a1fb69cd9, 0x4abdaf101564f98f},\n      {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f2},\n      {0xea53df5fd18d5513, 0x84c86189216dc5ee},\n      {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb5},\n      {0xb7118682dbb66a77, 0x3fbc8c33221dc2a2},\n      {0xe4d5e82392a40515, 0x0fabaf3feaa5334b},\n      {0x8f05b1163ba6832d, 0x29cb4d87f2a7400f},\n      {0xb2c71d5bca9023f8, 0x743e20e9ef511013},\n      {0xdf78e4b2bd342cf6, 0x914da9246b255417},\n      {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548f},\n      {0xae9672aba3d0c320, 0xa184ac2473b529b2},\n      {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741f},\n      {0x8865899617fb1871, 0x7e2fa67c7a658893},\n      {0xaa7eebfb9df9de8d, 0xddbb901b98feeab8},\n      {0xd51ea6fa85785631, 0x552a74227f3ea566},\n      {0x8533285c936b35de, 0xd53a88958f872760},\n      {0xa67ff273b8460356, 0x8a892abaf368f138},\n      {0xd01fef10a657842c, 0x2d2b7569b0432d86},\n      {0x8213f56a67f6b29b, 0x9c3b29620e29fc74},\n      {0xa298f2c501f45f42, 0x8349f3ba91b47b90},\n      {0xcb3f2f7642717713, 0x241c70a936219a74},\n      {0xfe0efb53d30dd4d7, 0xed238cd383aa0111},\n      {0x9ec95d1463e8a506, 0xf4363804324a40ab},\n      {0xc67bb4597ce2ce48, 0xb143c6053edcd0d6},\n      {0xf81aa16fdc1b81da, 0xdd94b7868e94050b},\n      {0x9b10a4e5e9913128, 0xca7cf2b4191c8327},\n      {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f1},\n      {0xf24a01a73cf2dccf, 0xbc633b39673c8ced},\n      {0x976e41088617ca01, 0xd5be0503e085d814},\n      {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e19},\n      {0xec9c459d51852ba2, 0xddf8e7d60ed1219f},\n      {0x93e1ab8252f33b45, 0xcabb90e5c942b504},\n      {0xb8da1662e7b00a17, 0x3d6a751f3b936244},\n      {0xe7109bfba19c0c9d, 0x0cc512670a783ad5},\n      {0x906a617d450187e2, 0x27fb2b80668b24c6},\n      {0xb484f9dc9641e9da, 0xb1f9f660802dedf7},\n      {0xe1a63853bbd26451, 0x5e7873f8a0396974},\n      {0x8d07e33455637eb2, 0xdb0b487b6423e1e9},\n      {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda63},\n      {0xdc5c5301c56b75f7, 0x7641a140cc7810fc},\n      {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9e},\n      {0xac2820d9623bf429, 0x546345fa9fbdcd45},\n      {0xd732290fbacaf133, 0xa97c177947ad4096},\n      {0x867f59a9d4bed6c0, 0x49ed8eabcccc485e},\n      {0xa81f301449ee8c70, 0x5c68f256bfff5a75},\n      {0xd226fc195c6a2f8c, 0x73832eec6fff3112},\n      {0x83585d8fd9c25db7, 0xc831fd53c5ff7eac},\n      {0xa42e74f3d032f525, 0xba3e7ca8b77f5e56},\n      {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35ec},\n      {0x80444b5e7aa7cf85, 0x7980d163cf5b81b4},\n      {0xa0555e361951c366, 0xd7e105bcc3326220},\n      {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa8},\n      {0xfa856334878fc150, 0xb14f98f6f0feb952},\n      {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d4},\n      {0xc3b8358109e84f07, 0x0a862f80ec4700c9},\n      {0xf4a642e14c6262c8, 0xcd27bb612758c0fb},\n      {0x98e7e9cccfbd7dbd, 0x8038d51cb897789d},\n      {0xbf21e44003acdd2c, 0xe0470a63e6bd56c4},\n      {0xeeea5d5004981478, 0x1858ccfce06cac75},\n      {0x95527a5202df0ccb, 0x0f37801e0c43ebc9},\n      {0xbaa718e68396cffd, 0xd30560258f54e6bb},\n      {0xe950df20247c83fd, 0x47c6b82ef32a206a},\n      {0x91d28b7416cdd27e, 0x4cdc331d57fa5442},\n      {0xb6472e511c81471d, 0xe0133fe4adf8e953},\n      {0xe3d8f9e563a198e5, 0x58180fddd97723a7},\n      {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7649},\n      {0xb201833b35d63f73, 0x2cd2cc6551e513db},\n      {0xde81e40a034bcf4f, 0xf8077f7ea65e58d2},\n      {0x8b112e86420f6191, 0xfb04afaf27faf783},\n      {0xadd57a27d29339f6, 0x79c5db9af1f9b564},\n      {0xd94ad8b1c7380874, 0x18375281ae7822bd},\n      {0x87cec76f1c830548, 0x8f2293910d0b15b6},\n      {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb23},\n      {0xd433179d9c8cb841, 0x5fa60692a46151ec},\n      {0x849feec281d7f328, 0xdbc7c41ba6bcd334},\n      {0xa5c7ea73224deff3, 0x12b9b522906c0801},\n      {0xcf39e50feae16bef, 0xd768226b34870a01},\n      {0x81842f29f2cce375, 0xe6a1158300d46641},\n      {0xa1e53af46f801c53, 0x60495ae3c1097fd1},\n      {0xca5e89b18b602368, 0x385bb19cb14bdfc5},\n      {0xfcf62c1dee382c42, 0x46729e03dd9ed7b6},\n      {0x9e19db92b4e31ba9, 0x6c07a2c26a8346d2},\n      {0xc5a05277621be293, 0xc7098b7305241886},\n      {0xf70867153aa2db38, 0xb8cbee4fc66d1ea8},\n      {0x9a65406d44a5c903, 0x737f74f1dc043329},\n      {0xc0fe908895cf3b44, 0x505f522e53053ff3},\n      {0xf13e34aabb430a15, 0x647726b9e7c68ff0},\n      {0x96c6e0eab509e64d, 0x5eca783430dc19f6},\n      {0xbc789925624c5fe0, 0xb67d16413d132073},\n      {0xeb96bf6ebadf77d8, 0xe41c5bd18c57e890},\n      {0x933e37a534cbaae7, 0x8e91b962f7b6f15a},\n      {0xb80dc58e81fe95a1, 0x723627bbb5a4adb1},\n      {0xe61136f2227e3b09, 0xcec3b1aaa30dd91d},\n      {0x8fcac257558ee4e6, 0x213a4f0aa5e8a7b2},\n      {0xb3bd72ed2af29e1f, 0xa988e2cd4f62d19e},\n      {0xe0accfa875af45a7, 0x93eb1b80a33b8606},\n      {0x8c6c01c9498d8b88, 0xbc72f130660533c4},\n      {0xaf87023b9bf0ee6a, 0xeb8fad7c7f8680b5},\n      {0xdb68c2ca82ed2a05, 0xa67398db9f6820e2},\n#else\n      {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b},\n      {0xce5d73ff402d98e3, 0xfb0a3d212dc81290},\n      {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f},\n      {0x86a8d39ef77164bc, 0xae5dff9c02033198},\n      {0xd98ddaee19068c76, 0x3badd624dd9b0958},\n      {0xafbd2350644eeacf, 0xe5d1929ef90898fb},\n      {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2},\n      {0xe55990879ddcaabd, 0xcc420a6a101d0516},\n      {0xb94470938fa89bce, 0xf808e40e8d5b3e6a},\n      {0x95a8637627989aad, 0xdde7001379a44aa9},\n      {0xf1c90080baf72cb1, 0x5324c68b12dd6339},\n      {0xc350000000000000, 0x0000000000000000},\n      {0x9dc5ada82b70b59d, 0xf020000000000000},\n      {0xfee50b7025c36a08, 0x02f236d04753d5b5},\n      {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87},\n      {0xa6539930bf6bff45, 0x84db8346b786151d},\n      {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3},\n      {0xd910f7ff28069da4, 0x1b2ba1518094da05},\n      {0xaf58416654a6babb, 0x387ac8d1970027b3},\n      {0x8da471a9de737e24, 0x5ceaecfed289e5d3},\n      {0xe4d5e82392a40515, 0x0fabaf3feaa5334b},\n      {0xb8da1662e7b00a17, 0x3d6a751f3b936244},\n      {0x95527a5202df0ccb, 0x0f37801e0c43ebc9},\n      {0xf13e34aabb430a15, 0x647726b9e7c68ff0}\n#endif\n    };\n\n#if FMT_USE_FULL_CACHE_DRAGONBOX\n    return pow10_significands[k - float_info<double>::min_k];\n#else\n    static constexpr uint64_t powers_of_5_64[] = {\n        0x0000000000000001, 0x0000000000000005, 0x0000000000000019,\n        0x000000000000007d, 0x0000000000000271, 0x0000000000000c35,\n        0x0000000000003d09, 0x000000000001312d, 0x000000000005f5e1,\n        0x00000000001dcd65, 0x00000000009502f9, 0x0000000002e90edd,\n        0x000000000e8d4a51, 0x0000000048c27395, 0x000000016bcc41e9,\n        0x000000071afd498d, 0x0000002386f26fc1, 0x000000b1a2bc2ec5,\n        0x000003782dace9d9, 0x00001158e460913d, 0x000056bc75e2d631,\n        0x0001b1ae4d6e2ef5, 0x000878678326eac9, 0x002a5a058fc295ed,\n        0x00d3c21bcecceda1, 0x0422ca8b0a00a425, 0x14adf4b7320334b9};\n\n    static const int compression_ratio = 27;\n\n    // Compute base index.\n    int cache_index = (k - float_info<double>::min_k) / compression_ratio;\n    int kb = cache_index * compression_ratio + float_info<double>::min_k;\n    int offset = k - kb;\n\n    // Get base cache.\n    uint128_fallback base_cache = pow10_significands[cache_index];\n    if (offset == 0) return base_cache;\n\n    // Compute the required amount of bit-shift.\n    int alpha = floor_log2_pow10(kb + offset) - floor_log2_pow10(kb) - offset;\n    FMT_ASSERT(alpha > 0 && alpha < 64, \"shifting error detected\");\n\n    // Try to recover the real cache.\n    uint64_t pow5 = powers_of_5_64[offset];\n    uint128_fallback recovered_cache = umul128(base_cache.high(), pow5);\n    uint128_fallback middle_low = umul128(base_cache.low(), pow5);\n\n    recovered_cache += middle_low.high();\n\n    uint64_t high_to_middle = recovered_cache.high() << (64 - alpha);\n    uint64_t middle_to_low = recovered_cache.low() << (64 - alpha);\n\n    recovered_cache =\n        uint128_fallback{(recovered_cache.low() >> alpha) | high_to_middle,\n                         ((middle_low.low() >> alpha) | middle_to_low)};\n    FMT_ASSERT(recovered_cache.low() + 1 != 0, \"\");\n    return {recovered_cache.high(), recovered_cache.low() + 1};\n#endif\n  }\n\n  struct compute_mul_result {\n    carrier_uint result;\n    bool is_integer;\n  };\n  struct compute_mul_parity_result {\n    bool parity;\n    bool is_integer;\n  };\n\n  static auto compute_mul(carrier_uint u,\n                          const cache_entry_type& cache) noexcept\n      -> compute_mul_result {\n    auto r = umul192_upper128(u, cache);\n    return {r.high(), r.low() == 0};\n  }\n\n  static auto compute_delta(const cache_entry_type& cache, int beta) noexcept\n      -> uint32_t {\n    return static_cast<uint32_t>(cache.high() >> (64 - 1 - beta));\n  }\n\n  static auto compute_mul_parity(carrier_uint two_f,\n                                 const cache_entry_type& cache,\n                                 int beta) noexcept\n      -> compute_mul_parity_result {\n    FMT_ASSERT(beta >= 1, \"\");\n    FMT_ASSERT(beta < 64, \"\");\n\n    auto r = umul192_lower128(two_f, cache);\n    return {((r.high() >> (64 - beta)) & 1) != 0,\n            ((r.high() << beta) | (r.low() >> (64 - beta))) == 0};\n  }\n\n  static auto compute_left_endpoint_for_shorter_interval_case(\n      const cache_entry_type& cache, int beta) noexcept -> carrier_uint {\n    return (cache.high() -\n            (cache.high() >> (num_significand_bits<double>() + 2))) >>\n           (64 - num_significand_bits<double>() - 1 - beta);\n  }\n\n  static auto compute_right_endpoint_for_shorter_interval_case(\n      const cache_entry_type& cache, int beta) noexcept -> carrier_uint {\n    return (cache.high() +\n            (cache.high() >> (num_significand_bits<double>() + 1))) >>\n           (64 - num_significand_bits<double>() - 1 - beta);\n  }\n\n  static auto compute_round_up_for_shorter_interval_case(\n      const cache_entry_type& cache, int beta) noexcept -> carrier_uint {\n    return ((cache.high() >> (64 - num_significand_bits<double>() - 2 - beta)) +\n            1) /\n           2;\n  }\n};\n\nFMT_FUNC auto get_cached_power(int k) noexcept -> uint128_fallback {\n  return cache_accessor<double>::get_cached_power(k);\n}\n\n// Various integer checks\ntemplate <typename T>\nauto is_left_endpoint_integer_shorter_interval(int exponent) noexcept -> bool {\n  const int case_shorter_interval_left_endpoint_lower_threshold = 2;\n  const int case_shorter_interval_left_endpoint_upper_threshold = 3;\n  return exponent >= case_shorter_interval_left_endpoint_lower_threshold &&\n         exponent <= case_shorter_interval_left_endpoint_upper_threshold;\n}\n\n// Remove trailing zeros from n and return the number of zeros removed (float).\nFMT_INLINE auto remove_trailing_zeros(uint32_t& n, int s = 0) noexcept -> int {\n  FMT_ASSERT(n != 0, \"\");\n  // Modular inverse of 5 (mod 2^32): (mod_inv_5 * 5) mod 2^32 = 1.\n  constexpr uint32_t mod_inv_5 = 0xcccccccd;\n  constexpr uint32_t mod_inv_25 = 0xc28f5c29;  // = mod_inv_5 * mod_inv_5\n\n  while (true) {\n    auto q = rotr(n * mod_inv_25, 2);\n    if (q > max_value<uint32_t>() / 100) break;\n    n = q;\n    s += 2;\n  }\n  auto q = rotr(n * mod_inv_5, 1);\n  if (q <= max_value<uint32_t>() / 10) {\n    n = q;\n    s |= 1;\n  }\n  return s;\n}\n\n// Removes trailing zeros and returns the number of zeros removed (double).\nFMT_INLINE auto remove_trailing_zeros(uint64_t& n) noexcept -> int {\n  FMT_ASSERT(n != 0, \"\");\n\n  // Is n is divisible by 10^8?\n  constexpr uint32_t ten_pow_8 = 100000000u;\n  if ((n % ten_pow_8) == 0) {\n    // If yes, work with the quotient...\n    auto n32 = static_cast<uint32_t>(n / ten_pow_8);\n    // ... and use the 32 bit variant of the function\n    int num_zeros = remove_trailing_zeros(n32, 8);\n    n = n32;\n    return num_zeros;\n  }\n\n  // If n is not divisible by 10^8, work with n itself.\n  constexpr uint64_t mod_inv_5 = 0xcccccccccccccccd;\n  constexpr uint64_t mod_inv_25 = 0x8f5c28f5c28f5c29;  // mod_inv_5 * mod_inv_5\n\n  int s = 0;\n  while (true) {\n    auto q = rotr(n * mod_inv_25, 2);\n    if (q > max_value<uint64_t>() / 100) break;\n    n = q;\n    s += 2;\n  }\n  auto q = rotr(n * mod_inv_5, 1);\n  if (q <= max_value<uint64_t>() / 10) {\n    n = q;\n    s |= 1;\n  }\n\n  return s;\n}\n\n// The main algorithm for shorter interval case\ntemplate <typename T>\nFMT_INLINE auto shorter_interval_case(int exponent) noexcept -> decimal_fp<T> {\n  decimal_fp<T> ret_value;\n  // Compute k and beta\n  const int minus_k = floor_log10_pow2_minus_log10_4_over_3(exponent);\n  const int beta = exponent + floor_log2_pow10(-minus_k);\n\n  // Compute xi and zi\n  using cache_entry_type = typename cache_accessor<T>::cache_entry_type;\n  const cache_entry_type cache = cache_accessor<T>::get_cached_power(-minus_k);\n\n  auto xi = cache_accessor<T>::compute_left_endpoint_for_shorter_interval_case(\n      cache, beta);\n  auto zi = cache_accessor<T>::compute_right_endpoint_for_shorter_interval_case(\n      cache, beta);\n\n  // If the left endpoint is not an integer, increase it\n  if (!is_left_endpoint_integer_shorter_interval<T>(exponent)) ++xi;\n\n  // Try bigger divisor\n  ret_value.significand = zi / 10;\n\n  // If succeed, remove trailing zeros if necessary and return\n  if (ret_value.significand * 10 >= xi) {\n    ret_value.exponent = minus_k + 1;\n    ret_value.exponent += remove_trailing_zeros(ret_value.significand);\n    return ret_value;\n  }\n\n  // Otherwise, compute the round-up of y\n  ret_value.significand =\n      cache_accessor<T>::compute_round_up_for_shorter_interval_case(cache,\n                                                                    beta);\n  ret_value.exponent = minus_k;\n\n  // When tie occurs, choose one of them according to the rule\n  if (exponent >= float_info<T>::shorter_interval_tie_lower_threshold &&\n      exponent <= float_info<T>::shorter_interval_tie_upper_threshold) {\n    ret_value.significand = ret_value.significand % 2 == 0\n                                ? ret_value.significand\n                                : ret_value.significand - 1;\n  } else if (ret_value.significand < xi) {\n    ++ret_value.significand;\n  }\n  return ret_value;\n}\n\ntemplate <typename T> auto to_decimal(T x) noexcept -> decimal_fp<T> {\n  // Step 1: integer promotion & Schubfach multiplier calculation.\n\n  using carrier_uint = typename float_info<T>::carrier_uint;\n  using cache_entry_type = typename cache_accessor<T>::cache_entry_type;\n  auto br = bit_cast<carrier_uint>(x);\n\n  // Extract significand bits and exponent bits.\n  const carrier_uint significand_mask =\n      (static_cast<carrier_uint>(1) << num_significand_bits<T>()) - 1;\n  carrier_uint significand = (br & significand_mask);\n  int exponent =\n      static_cast<int>((br & exponent_mask<T>()) >> num_significand_bits<T>());\n\n  if (exponent != 0) {  // Check if normal.\n    exponent -= exponent_bias<T>() + num_significand_bits<T>();\n\n    // Shorter interval case; proceed like Schubfach.\n    // In fact, when exponent == 1 and significand == 0, the interval is\n    // regular. However, it can be shown that the end-results are anyway same.\n    if (significand == 0) return shorter_interval_case<T>(exponent);\n\n    significand |= (static_cast<carrier_uint>(1) << num_significand_bits<T>());\n  } else {\n    // Subnormal case; the interval is always regular.\n    if (significand == 0) return {0, 0};\n    exponent =\n        std::numeric_limits<T>::min_exponent - num_significand_bits<T>() - 1;\n  }\n\n  const bool include_left_endpoint = (significand % 2 == 0);\n  const bool include_right_endpoint = include_left_endpoint;\n\n  // Compute k and beta.\n  const int minus_k = floor_log10_pow2(exponent) - float_info<T>::kappa;\n  const cache_entry_type cache = cache_accessor<T>::get_cached_power(-minus_k);\n  const int beta = exponent + floor_log2_pow10(-minus_k);\n\n  // Compute zi and deltai.\n  // 10^kappa <= deltai < 10^(kappa + 1)\n  const uint32_t deltai = cache_accessor<T>::compute_delta(cache, beta);\n  const carrier_uint two_fc = significand << 1;\n\n  // For the case of binary32, the result of integer check is not correct for\n  // 29711844 * 2^-82\n  // = 6.1442653300000000008655037797566933477355632930994033813476... * 10^-18\n  // and 29711844 * 2^-81\n  // = 1.2288530660000000001731007559513386695471126586198806762695... * 10^-17,\n  // and they are the unique counterexamples. However, since 29711844 is even,\n  // this does not cause any problem for the endpoints calculations; it can only\n  // cause a problem when we need to perform integer check for the center.\n  // Fortunately, with these inputs, that branch is never executed, so we are\n  // fine.\n  const typename cache_accessor<T>::compute_mul_result z_mul =\n      cache_accessor<T>::compute_mul((two_fc | 1) << beta, cache);\n\n  // Step 2: Try larger divisor; remove trailing zeros if necessary.\n\n  // Using an upper bound on zi, we might be able to optimize the division\n  // better than the compiler; we are computing zi / big_divisor here.\n  decimal_fp<T> ret_value;\n  ret_value.significand = divide_by_10_to_kappa_plus_1(z_mul.result);\n  uint32_t r = static_cast<uint32_t>(z_mul.result - float_info<T>::big_divisor *\n                                                        ret_value.significand);\n\n  if (r < deltai) {\n    // Exclude the right endpoint if necessary.\n    if (r == 0 && (z_mul.is_integer & !include_right_endpoint)) {\n      --ret_value.significand;\n      r = float_info<T>::big_divisor;\n      goto small_divisor_case_label;\n    }\n  } else if (r > deltai) {\n    goto small_divisor_case_label;\n  } else {\n    // r == deltai; compare fractional parts.\n    const typename cache_accessor<T>::compute_mul_parity_result x_mul =\n        cache_accessor<T>::compute_mul_parity(two_fc - 1, cache, beta);\n\n    if (!(x_mul.parity | (x_mul.is_integer & include_left_endpoint)))\n      goto small_divisor_case_label;\n  }\n  ret_value.exponent = minus_k + float_info<T>::kappa + 1;\n\n  // We may need to remove trailing zeros.\n  ret_value.exponent += remove_trailing_zeros(ret_value.significand);\n  return ret_value;\n\n  // Step 3: Find the significand with the smaller divisor.\n\nsmall_divisor_case_label:\n  ret_value.significand *= 10;\n  ret_value.exponent = minus_k + float_info<T>::kappa;\n\n  uint32_t dist = r - (deltai / 2) + (float_info<T>::small_divisor / 2);\n  const bool approx_y_parity =\n      ((dist ^ (float_info<T>::small_divisor / 2)) & 1) != 0;\n\n  // Is dist divisible by 10^kappa?\n  const bool divisible_by_small_divisor =\n      check_divisibility_and_divide_by_pow10<float_info<T>::kappa>(dist);\n\n  // Add dist / 10^kappa to the significand.\n  ret_value.significand += dist;\n\n  if (!divisible_by_small_divisor) return ret_value;\n\n  // Check z^(f) >= epsilon^(f).\n  // We have either yi == zi - epsiloni or yi == (zi - epsiloni) - 1,\n  // where yi == zi - epsiloni if and only if z^(f) >= epsilon^(f).\n  // Since there are only 2 possibilities, we only need to care about the\n  // parity. Also, zi and r should have the same parity since the divisor\n  // is an even number.\n  const auto y_mul = cache_accessor<T>::compute_mul_parity(two_fc, cache, beta);\n\n  // If z^(f) >= epsilon^(f), we might have a tie when z^(f) == epsilon^(f),\n  // or equivalently, when y is an integer.\n  if (y_mul.parity != approx_y_parity)\n    --ret_value.significand;\n  else if (y_mul.is_integer & (ret_value.significand % 2 != 0))\n    --ret_value.significand;\n  return ret_value;\n}\n}  // namespace dragonbox\n}  // namespace detail\n\ntemplate <> struct formatter<detail::bigint> {\n  FMT_CONSTEXPR auto parse(format_parse_context& ctx)\n      -> format_parse_context::iterator {\n    return ctx.begin();\n  }\n\n  auto format(const detail::bigint& n, format_context& ctx) const\n      -> format_context::iterator {\n    auto out = ctx.out();\n    bool first = true;\n    for (auto i = n.bigits_.size(); i > 0; --i) {\n      auto value = n.bigits_[i - 1u];\n      if (first) {\n        out = fmt::format_to(out, FMT_STRING(\"{:x}\"), value);\n        first = false;\n        continue;\n      }\n      out = fmt::format_to(out, FMT_STRING(\"{:08x}\"), value);\n    }\n    if (n.exp_ > 0)\n      out = fmt::format_to(out, FMT_STRING(\"p{}\"),\n                           n.exp_ * detail::bigint::bigit_bits);\n    return out;\n  }\n};\n\nFMT_FUNC detail::utf8_to_utf16::utf8_to_utf16(string_view s) {\n  for_each_codepoint(s, [this](uint32_t cp, string_view) {\n    if (cp == invalid_code_point) FMT_THROW(std::runtime_error(\"invalid utf8\"));\n    if (cp <= 0xFFFF) {\n      buffer_.push_back(static_cast<wchar_t>(cp));\n    } else {\n      cp -= 0x10000;\n      buffer_.push_back(static_cast<wchar_t>(0xD800 + (cp >> 10)));\n      buffer_.push_back(static_cast<wchar_t>(0xDC00 + (cp & 0x3FF)));\n    }\n    return true;\n  });\n  buffer_.push_back(0);\n}\n\nFMT_FUNC void format_system_error(detail::buffer<char>& out, int error_code,\n                                  const char* message) noexcept {\n  FMT_TRY {\n    auto ec = std::error_code(error_code, std::generic_category());\n    detail::write(appender(out), std::system_error(ec, message).what());\n    return;\n  }\n  FMT_CATCH(...) {}\n  format_error_code(out, error_code, message);\n}\n\nFMT_FUNC void report_system_error(int error_code,\n                                  const char* message) noexcept {\n  do_report_error(format_system_error, error_code, message);\n}\n\nFMT_FUNC auto vformat(string_view fmt, format_args args) -> std::string {\n  // Don't optimize the \"{}\" case to keep the binary size small and because it\n  // can be better optimized in fmt::format anyway.\n  auto buffer = memory_buffer();\n  detail::vformat_to(buffer, fmt, args);\n  return to_string(buffer);\n}\n\nnamespace detail {\n\nFMT_FUNC void vformat_to(buffer<char>& buf, string_view fmt, format_args args,\n                         locale_ref loc) {\n  auto out = appender(buf);\n  if (fmt.size() == 2 && equal2(fmt.data(), \"{}\"))\n    return args.get(0).visit(default_arg_formatter<char>{out});\n  parse_format_string(fmt,\n                      format_handler<>{parse_context<>(fmt), {out, args, loc}});\n}\n\ntemplate <typename T> struct span {\n  T* data;\n  size_t size;\n};\n\ntemplate <typename F> auto flockfile(F* f) -> decltype(_lock_file(f)) {\n  _lock_file(f);\n}\ntemplate <typename F> auto funlockfile(F* f) -> decltype(_unlock_file(f)) {\n  _unlock_file(f);\n}\n\n#ifndef getc_unlocked\ntemplate <typename F> auto getc_unlocked(F* f) -> decltype(_fgetc_nolock(f)) {\n  return _fgetc_nolock(f);\n}\n#endif\n\ntemplate <typename F = FILE, typename Enable = void>\nstruct has_flockfile : std::false_type {};\n\ntemplate <typename F>\nstruct has_flockfile<F, void_t<decltype(flockfile(&std::declval<F&>()))>>\n    : std::true_type {};\n\n// A FILE wrapper. F is FILE defined as a template parameter to make system API\n// detection work.\ntemplate <typename F> class file_base {\n public:\n  F* file_;\n\n public:\n  file_base(F* file) : file_(file) {}\n  operator F*() const { return file_; }\n\n  // Reads a code unit from the stream.\n  auto get() -> int {\n    int result = getc_unlocked(file_);\n    if (result == EOF && ferror(file_) != 0)\n      FMT_THROW(system_error(errno, FMT_STRING(\"getc failed\")));\n    return result;\n  }\n\n  // Puts the code unit back into the stream buffer.\n  void unget(char c) {\n    if (ungetc(c, file_) == EOF)\n      FMT_THROW(system_error(errno, FMT_STRING(\"ungetc failed\")));\n  }\n\n  void flush() { fflush(this->file_); }\n};\n\n// A FILE wrapper for glibc.\ntemplate <typename F> class glibc_file : public file_base<F> {\n private:\n  enum {\n    line_buffered = 0x200,  // _IO_LINE_BUF\n    unbuffered = 2          // _IO_UNBUFFERED\n  };\n\n public:\n  using file_base<F>::file_base;\n\n  auto is_buffered() const -> bool {\n    return (this->file_->_flags & unbuffered) == 0;\n  }\n\n  void init_buffer() {\n    if (this->file_->_IO_write_ptr < this->file_->_IO_write_end) return;\n    // Force buffer initialization by placing and removing a char in a buffer.\n    putc_unlocked(0, this->file_);\n    --this->file_->_IO_write_ptr;\n  }\n\n  // Returns the file's read buffer.\n  auto get_read_buffer() const -> span<const char> {\n    auto ptr = this->file_->_IO_read_ptr;\n    return {ptr, to_unsigned(this->file_->_IO_read_end - ptr)};\n  }\n\n  // Returns the file's write buffer.\n  auto get_write_buffer() const -> span<char> {\n    auto ptr = this->file_->_IO_write_ptr;\n    return {ptr, to_unsigned(this->file_->_IO_buf_end - ptr)};\n  }\n\n  void advance_write_buffer(size_t size) { this->file_->_IO_write_ptr += size; }\n\n  auto needs_flush() const -> bool {\n    if ((this->file_->_flags & line_buffered) == 0) return false;\n    char* end = this->file_->_IO_write_end;\n    auto size = max_of<ptrdiff_t>(this->file_->_IO_write_ptr - end, 0);\n    return memchr(end, '\\n', static_cast<size_t>(size));\n  }\n\n  void flush() { fflush_unlocked(this->file_); }\n};\n\n// A FILE wrapper for Apple's libc.\ntemplate <typename F> class apple_file : public file_base<F> {\n private:\n  enum {\n    line_buffered = 1,  // __SNBF\n    unbuffered = 2      // __SLBF\n  };\n\n public:\n  using file_base<F>::file_base;\n\n  auto is_buffered() const -> bool {\n    return (this->file_->_flags & unbuffered) == 0;\n  }\n\n  void init_buffer() {\n    if (this->file_->_p) return;\n    // Force buffer initialization by placing and removing a char in a buffer.\n    if (!FMT_CLANG_ANALYZER) putc_unlocked(0, this->file_);\n    --this->file_->_p;\n    ++this->file_->_w;\n  }\n\n  auto get_read_buffer() const -> span<const char> {\n    return {reinterpret_cast<char*>(this->file_->_p),\n            to_unsigned(this->file_->_r)};\n  }\n\n  auto get_write_buffer() const -> span<char> {\n    return {reinterpret_cast<char*>(this->file_->_p),\n            to_unsigned(this->file_->_bf._base + this->file_->_bf._size -\n                        this->file_->_p)};\n  }\n\n  void advance_write_buffer(size_t size) {\n    this->file_->_p += size;\n    this->file_->_w -= size;\n  }\n\n  auto needs_flush() const -> bool {\n    if ((this->file_->_flags & line_buffered) == 0) return false;\n    return memchr(this->file_->_p + this->file_->_w, '\\n',\n                  to_unsigned(-this->file_->_w));\n  }\n};\n\n// A fallback FILE wrapper.\ntemplate <typename F> class fallback_file : public file_base<F> {\n private:\n  char next_;  // The next unconsumed character in the buffer.\n  bool has_next_ = false;\n\n public:\n  using file_base<F>::file_base;\n\n  auto is_buffered() const -> bool { return false; }\n  auto needs_flush() const -> bool { return false; }\n  void init_buffer() {}\n\n  auto get_read_buffer() const -> span<const char> {\n    return {&next_, has_next_ ? 1u : 0u};\n  }\n\n  auto get_write_buffer() const -> span<char> { return {nullptr, 0}; }\n\n  void advance_write_buffer(size_t) {}\n\n  auto get() -> int {\n    has_next_ = false;\n    return file_base<F>::get();\n  }\n\n  void unget(char c) {\n    file_base<F>::unget(c);\n    next_ = c;\n    has_next_ = true;\n  }\n};\n\n#ifndef FMT_USE_FALLBACK_FILE\n#  define FMT_USE_FALLBACK_FILE 0\n#endif\n\ntemplate <typename F,\n          FMT_ENABLE_IF(sizeof(F::_p) != 0 && !FMT_USE_FALLBACK_FILE)>\nauto get_file(F* f, int) -> apple_file<F> {\n  return f;\n}\ntemplate <typename F,\n          FMT_ENABLE_IF(sizeof(F::_IO_read_ptr) != 0 && !FMT_USE_FALLBACK_FILE)>\ninline auto get_file(F* f, int) -> glibc_file<F> {\n  return f;\n}\n\ninline auto get_file(FILE* f, ...) -> fallback_file<FILE> { return f; }\n\nusing file_ref = decltype(get_file(static_cast<FILE*>(nullptr), 0));\n\ntemplate <typename F = FILE, typename Enable = void>\nclass file_print_buffer : public buffer<char> {\n public:\n  explicit file_print_buffer(F*) : buffer(nullptr, size_t()) {}\n};\n\ntemplate <typename F>\nclass file_print_buffer<F, enable_if_t<has_flockfile<F>::value>>\n    : public buffer<char> {\n private:\n  file_ref file_;\n\n  static void grow(buffer<char>& base, size_t) {\n    auto& self = static_cast<file_print_buffer&>(base);\n    self.file_.advance_write_buffer(self.size());\n    if (self.file_.get_write_buffer().size == 0) self.file_.flush();\n    auto buf = self.file_.get_write_buffer();\n    FMT_ASSERT(buf.size > 0, \"\");\n    self.set(buf.data, buf.size);\n    self.clear();\n  }\n\n public:\n  explicit file_print_buffer(F* f) : buffer(grow, size_t()), file_(f) {\n    flockfile(f);\n    file_.init_buffer();\n    auto buf = file_.get_write_buffer();\n    set(buf.data, buf.size);\n  }\n  ~file_print_buffer() {\n    file_.advance_write_buffer(size());\n    bool flush = file_.needs_flush();\n    F* f = file_;    // Make funlockfile depend on the template parameter F\n    funlockfile(f);  // for the system API detection to work.\n    if (flush) fflush(file_);\n  }\n};\n\n#if !defined(_WIN32) || defined(FMT_USE_WRITE_CONSOLE)\nFMT_FUNC auto write_console(int, string_view) -> bool { return false; }\n#else\nusing dword = conditional_t<sizeof(long) == 4, unsigned long, unsigned>;\nextern \"C\" __declspec(dllimport) int __stdcall WriteConsoleW(  //\n    void*, const void*, dword, dword*, void*);\n\nFMT_FUNC bool write_console(int fd, string_view text) {\n  auto u16 = utf8_to_utf16(text);\n  return WriteConsoleW(reinterpret_cast<void*>(_get_osfhandle(fd)), u16.c_str(),\n                       static_cast<dword>(u16.size()), nullptr, nullptr) != 0;\n}\n#endif\n\n#ifdef _WIN32\n// Print assuming legacy (non-Unicode) encoding.\nFMT_FUNC void vprint_mojibake(std::FILE* f, string_view fmt, format_args args,\n                              bool newline) {\n  auto buffer = memory_buffer();\n  detail::vformat_to(buffer, fmt, args);\n  if (newline) buffer.push_back('\\n');\n  fwrite_all(buffer.data(), buffer.size(), f);\n}\n#endif\n\nFMT_FUNC void print(std::FILE* f, string_view text) {\n#if defined(_WIN32) && !defined(FMT_USE_WRITE_CONSOLE)\n  int fd = _fileno(f);\n  if (_isatty(fd)) {\n    std::fflush(f);\n    if (write_console(fd, text)) return;\n  }\n#endif\n  fwrite_all(text.data(), text.size(), f);\n}\n}  // namespace detail\n\nFMT_FUNC void vprint_buffered(std::FILE* f, string_view fmt, format_args args) {\n  auto buffer = memory_buffer();\n  detail::vformat_to(buffer, fmt, args);\n  detail::print(f, {buffer.data(), buffer.size()});\n}\n\nFMT_FUNC void vprint(std::FILE* f, string_view fmt, format_args args) {\n  if (!detail::file_ref(f).is_buffered() || !detail::has_flockfile<>())\n    return vprint_buffered(f, fmt, args);\n  auto&& buffer = detail::file_print_buffer<>(f);\n  return detail::vformat_to(buffer, fmt, args);\n}\n\nFMT_FUNC void vprintln(std::FILE* f, string_view fmt, format_args args) {\n  auto buffer = memory_buffer();\n  detail::vformat_to(buffer, fmt, args);\n  buffer.push_back('\\n');\n  detail::print(f, {buffer.data(), buffer.size()});\n}\n\nFMT_FUNC void vprint(string_view fmt, format_args args) {\n  vprint(stdout, fmt, args);\n}\n\nnamespace detail {\n\nstruct singleton {\n  unsigned char upper;\n  unsigned char lower_count;\n};\n\ninline auto is_printable(uint16_t x, const singleton* singletons,\n                         size_t singletons_size,\n                         const unsigned char* singleton_lowers,\n                         const unsigned char* normal, size_t normal_size)\n    -> bool {\n  auto upper = x >> 8;\n  auto lower_start = 0;\n  for (size_t i = 0; i < singletons_size; ++i) {\n    auto s = singletons[i];\n    auto lower_end = lower_start + s.lower_count;\n    if (upper < s.upper) break;\n    if (upper == s.upper) {\n      for (auto j = lower_start; j < lower_end; ++j) {\n        if (singleton_lowers[j] == (x & 0xff)) return false;\n      }\n    }\n    lower_start = lower_end;\n  }\n\n  auto xsigned = static_cast<int>(x);\n  auto current = true;\n  for (size_t i = 0; i < normal_size; ++i) {\n    auto v = static_cast<int>(normal[i]);\n    auto len = (v & 0x80) != 0 ? (v & 0x7f) << 8 | normal[++i] : v;\n    xsigned -= len;\n    if (xsigned < 0) break;\n    current = !current;\n  }\n  return current;\n}\n\n// This code is generated by support/printable.py.\nFMT_FUNC auto is_printable(uint32_t cp) -> bool {\n  static constexpr singleton singletons0[] = {\n      {0x00, 1},  {0x03, 5},  {0x05, 6},  {0x06, 3},  {0x07, 6},  {0x08, 8},\n      {0x09, 17}, {0x0a, 28}, {0x0b, 25}, {0x0c, 20}, {0x0d, 16}, {0x0e, 13},\n      {0x0f, 4},  {0x10, 3},  {0x12, 18}, {0x13, 9},  {0x16, 1},  {0x17, 5},\n      {0x18, 2},  {0x19, 3},  {0x1a, 7},  {0x1c, 2},  {0x1d, 1},  {0x1f, 22},\n      {0x20, 3},  {0x2b, 3},  {0x2c, 2},  {0x2d, 11}, {0x2e, 1},  {0x30, 3},\n      {0x31, 2},  {0x32, 1},  {0xa7, 2},  {0xa9, 2},  {0xaa, 4},  {0xab, 8},\n      {0xfa, 2},  {0xfb, 5},  {0xfd, 4},  {0xfe, 3},  {0xff, 9},\n  };\n  static constexpr unsigned char singletons0_lower[] = {\n      0xad, 0x78, 0x79, 0x8b, 0x8d, 0xa2, 0x30, 0x57, 0x58, 0x8b, 0x8c, 0x90,\n      0x1c, 0x1d, 0xdd, 0x0e, 0x0f, 0x4b, 0x4c, 0xfb, 0xfc, 0x2e, 0x2f, 0x3f,\n      0x5c, 0x5d, 0x5f, 0xb5, 0xe2, 0x84, 0x8d, 0x8e, 0x91, 0x92, 0xa9, 0xb1,\n      0xba, 0xbb, 0xc5, 0xc6, 0xc9, 0xca, 0xde, 0xe4, 0xe5, 0xff, 0x00, 0x04,\n      0x11, 0x12, 0x29, 0x31, 0x34, 0x37, 0x3a, 0x3b, 0x3d, 0x49, 0x4a, 0x5d,\n      0x84, 0x8e, 0x92, 0xa9, 0xb1, 0xb4, 0xba, 0xbb, 0xc6, 0xca, 0xce, 0xcf,\n      0xe4, 0xe5, 0x00, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a,\n      0x3b, 0x45, 0x46, 0x49, 0x4a, 0x5e, 0x64, 0x65, 0x84, 0x91, 0x9b, 0x9d,\n      0xc9, 0xce, 0xcf, 0x0d, 0x11, 0x29, 0x45, 0x49, 0x57, 0x64, 0x65, 0x8d,\n      0x91, 0xa9, 0xb4, 0xba, 0xbb, 0xc5, 0xc9, 0xdf, 0xe4, 0xe5, 0xf0, 0x0d,\n      0x11, 0x45, 0x49, 0x64, 0x65, 0x80, 0x84, 0xb2, 0xbc, 0xbe, 0xbf, 0xd5,\n      0xd7, 0xf0, 0xf1, 0x83, 0x85, 0x8b, 0xa4, 0xa6, 0xbe, 0xbf, 0xc5, 0xc7,\n      0xce, 0xcf, 0xda, 0xdb, 0x48, 0x98, 0xbd, 0xcd, 0xc6, 0xce, 0xcf, 0x49,\n      0x4e, 0x4f, 0x57, 0x59, 0x5e, 0x5f, 0x89, 0x8e, 0x8f, 0xb1, 0xb6, 0xb7,\n      0xbf, 0xc1, 0xc6, 0xc7, 0xd7, 0x11, 0x16, 0x17, 0x5b, 0x5c, 0xf6, 0xf7,\n      0xfe, 0xff, 0x80, 0x0d, 0x6d, 0x71, 0xde, 0xdf, 0x0e, 0x0f, 0x1f, 0x6e,\n      0x6f, 0x1c, 0x1d, 0x5f, 0x7d, 0x7e, 0xae, 0xaf, 0xbb, 0xbc, 0xfa, 0x16,\n      0x17, 0x1e, 0x1f, 0x46, 0x47, 0x4e, 0x4f, 0x58, 0x5a, 0x5c, 0x5e, 0x7e,\n      0x7f, 0xb5, 0xc5, 0xd4, 0xd5, 0xdc, 0xf0, 0xf1, 0xf5, 0x72, 0x73, 0x8f,\n      0x74, 0x75, 0x96, 0x2f, 0x5f, 0x26, 0x2e, 0x2f, 0xa7, 0xaf, 0xb7, 0xbf,\n      0xc7, 0xcf, 0xd7, 0xdf, 0x9a, 0x40, 0x97, 0x98, 0x30, 0x8f, 0x1f, 0xc0,\n      0xc1, 0xce, 0xff, 0x4e, 0x4f, 0x5a, 0x5b, 0x07, 0x08, 0x0f, 0x10, 0x27,\n      0x2f, 0xee, 0xef, 0x6e, 0x6f, 0x37, 0x3d, 0x3f, 0x42, 0x45, 0x90, 0x91,\n      0xfe, 0xff, 0x53, 0x67, 0x75, 0xc8, 0xc9, 0xd0, 0xd1, 0xd8, 0xd9, 0xe7,\n      0xfe, 0xff,\n  };\n  static constexpr singleton singletons1[] = {\n      {0x00, 6},  {0x01, 1}, {0x03, 1},  {0x04, 2}, {0x08, 8},  {0x09, 2},\n      {0x0a, 5},  {0x0b, 2}, {0x0e, 4},  {0x10, 1}, {0x11, 2},  {0x12, 5},\n      {0x13, 17}, {0x14, 1}, {0x15, 2},  {0x17, 2}, {0x19, 13}, {0x1c, 5},\n      {0x1d, 8},  {0x24, 1}, {0x6a, 3},  {0x6b, 2}, {0xbc, 2},  {0xd1, 2},\n      {0xd4, 12}, {0xd5, 9}, {0xd6, 2},  {0xd7, 2}, {0xda, 1},  {0xe0, 5},\n      {0xe1, 2},  {0xe8, 2}, {0xee, 32}, {0xf0, 4}, {0xf8, 2},  {0xf9, 2},\n      {0xfa, 2},  {0xfb, 1},\n  };\n  static constexpr unsigned char singletons1_lower[] = {\n      0x0c, 0x27, 0x3b, 0x3e, 0x4e, 0x4f, 0x8f, 0x9e, 0x9e, 0x9f, 0x06, 0x07,\n      0x09, 0x36, 0x3d, 0x3e, 0x56, 0xf3, 0xd0, 0xd1, 0x04, 0x14, 0x18, 0x36,\n      0x37, 0x56, 0x57, 0x7f, 0xaa, 0xae, 0xaf, 0xbd, 0x35, 0xe0, 0x12, 0x87,\n      0x89, 0x8e, 0x9e, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a,\n      0x45, 0x46, 0x49, 0x4a, 0x4e, 0x4f, 0x64, 0x65, 0x5c, 0xb6, 0xb7, 0x1b,\n      0x1c, 0x07, 0x08, 0x0a, 0x0b, 0x14, 0x17, 0x36, 0x39, 0x3a, 0xa8, 0xa9,\n      0xd8, 0xd9, 0x09, 0x37, 0x90, 0x91, 0xa8, 0x07, 0x0a, 0x3b, 0x3e, 0x66,\n      0x69, 0x8f, 0x92, 0x6f, 0x5f, 0xee, 0xef, 0x5a, 0x62, 0x9a, 0x9b, 0x27,\n      0x28, 0x55, 0x9d, 0xa0, 0xa1, 0xa3, 0xa4, 0xa7, 0xa8, 0xad, 0xba, 0xbc,\n      0xc4, 0x06, 0x0b, 0x0c, 0x15, 0x1d, 0x3a, 0x3f, 0x45, 0x51, 0xa6, 0xa7,\n      0xcc, 0xcd, 0xa0, 0x07, 0x19, 0x1a, 0x22, 0x25, 0x3e, 0x3f, 0xc5, 0xc6,\n      0x04, 0x20, 0x23, 0x25, 0x26, 0x28, 0x33, 0x38, 0x3a, 0x48, 0x4a, 0x4c,\n      0x50, 0x53, 0x55, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x63, 0x65, 0x66,\n      0x6b, 0x73, 0x78, 0x7d, 0x7f, 0x8a, 0xa4, 0xaa, 0xaf, 0xb0, 0xc0, 0xd0,\n      0xae, 0xaf, 0x79, 0xcc, 0x6e, 0x6f, 0x93,\n  };\n  static constexpr unsigned char normal0[] = {\n      0x00, 0x20, 0x5f, 0x22, 0x82, 0xdf, 0x04, 0x82, 0x44, 0x08, 0x1b, 0x04,\n      0x06, 0x11, 0x81, 0xac, 0x0e, 0x80, 0xab, 0x35, 0x28, 0x0b, 0x80, 0xe0,\n      0x03, 0x19, 0x08, 0x01, 0x04, 0x2f, 0x04, 0x34, 0x04, 0x07, 0x03, 0x01,\n      0x07, 0x06, 0x07, 0x11, 0x0a, 0x50, 0x0f, 0x12, 0x07, 0x55, 0x07, 0x03,\n      0x04, 0x1c, 0x0a, 0x09, 0x03, 0x08, 0x03, 0x07, 0x03, 0x02, 0x03, 0x03,\n      0x03, 0x0c, 0x04, 0x05, 0x03, 0x0b, 0x06, 0x01, 0x0e, 0x15, 0x05, 0x3a,\n      0x03, 0x11, 0x07, 0x06, 0x05, 0x10, 0x07, 0x57, 0x07, 0x02, 0x07, 0x15,\n      0x0d, 0x50, 0x04, 0x43, 0x03, 0x2d, 0x03, 0x01, 0x04, 0x11, 0x06, 0x0f,\n      0x0c, 0x3a, 0x04, 0x1d, 0x25, 0x5f, 0x20, 0x6d, 0x04, 0x6a, 0x25, 0x80,\n      0xc8, 0x05, 0x82, 0xb0, 0x03, 0x1a, 0x06, 0x82, 0xfd, 0x03, 0x59, 0x07,\n      0x15, 0x0b, 0x17, 0x09, 0x14, 0x0c, 0x14, 0x0c, 0x6a, 0x06, 0x0a, 0x06,\n      0x1a, 0x06, 0x59, 0x07, 0x2b, 0x05, 0x46, 0x0a, 0x2c, 0x04, 0x0c, 0x04,\n      0x01, 0x03, 0x31, 0x0b, 0x2c, 0x04, 0x1a, 0x06, 0x0b, 0x03, 0x80, 0xac,\n      0x06, 0x0a, 0x06, 0x21, 0x3f, 0x4c, 0x04, 0x2d, 0x03, 0x74, 0x08, 0x3c,\n      0x03, 0x0f, 0x03, 0x3c, 0x07, 0x38, 0x08, 0x2b, 0x05, 0x82, 0xff, 0x11,\n      0x18, 0x08, 0x2f, 0x11, 0x2d, 0x03, 0x20, 0x10, 0x21, 0x0f, 0x80, 0x8c,\n      0x04, 0x82, 0x97, 0x19, 0x0b, 0x15, 0x88, 0x94, 0x05, 0x2f, 0x05, 0x3b,\n      0x07, 0x02, 0x0e, 0x18, 0x09, 0x80, 0xb3, 0x2d, 0x74, 0x0c, 0x80, 0xd6,\n      0x1a, 0x0c, 0x05, 0x80, 0xff, 0x05, 0x80, 0xdf, 0x0c, 0xee, 0x0d, 0x03,\n      0x84, 0x8d, 0x03, 0x37, 0x09, 0x81, 0x5c, 0x14, 0x80, 0xb8, 0x08, 0x80,\n      0xcb, 0x2a, 0x38, 0x03, 0x0a, 0x06, 0x38, 0x08, 0x46, 0x08, 0x0c, 0x06,\n      0x74, 0x0b, 0x1e, 0x03, 0x5a, 0x04, 0x59, 0x09, 0x80, 0x83, 0x18, 0x1c,\n      0x0a, 0x16, 0x09, 0x4c, 0x04, 0x80, 0x8a, 0x06, 0xab, 0xa4, 0x0c, 0x17,\n      0x04, 0x31, 0xa1, 0x04, 0x81, 0xda, 0x26, 0x07, 0x0c, 0x05, 0x05, 0x80,\n      0xa5, 0x11, 0x81, 0x6d, 0x10, 0x78, 0x28, 0x2a, 0x06, 0x4c, 0x04, 0x80,\n      0x8d, 0x04, 0x80, 0xbe, 0x03, 0x1b, 0x03, 0x0f, 0x0d,\n  };\n  static constexpr unsigned char normal1[] = {\n      0x5e, 0x22, 0x7b, 0x05, 0x03, 0x04, 0x2d, 0x03, 0x66, 0x03, 0x01, 0x2f,\n      0x2e, 0x80, 0x82, 0x1d, 0x03, 0x31, 0x0f, 0x1c, 0x04, 0x24, 0x09, 0x1e,\n      0x05, 0x2b, 0x05, 0x44, 0x04, 0x0e, 0x2a, 0x80, 0xaa, 0x06, 0x24, 0x04,\n      0x24, 0x04, 0x28, 0x08, 0x34, 0x0b, 0x01, 0x80, 0x90, 0x81, 0x37, 0x09,\n      0x16, 0x0a, 0x08, 0x80, 0x98, 0x39, 0x03, 0x63, 0x08, 0x09, 0x30, 0x16,\n      0x05, 0x21, 0x03, 0x1b, 0x05, 0x01, 0x40, 0x38, 0x04, 0x4b, 0x05, 0x2f,\n      0x04, 0x0a, 0x07, 0x09, 0x07, 0x40, 0x20, 0x27, 0x04, 0x0c, 0x09, 0x36,\n      0x03, 0x3a, 0x05, 0x1a, 0x07, 0x04, 0x0c, 0x07, 0x50, 0x49, 0x37, 0x33,\n      0x0d, 0x33, 0x07, 0x2e, 0x08, 0x0a, 0x81, 0x26, 0x52, 0x4e, 0x28, 0x08,\n      0x2a, 0x56, 0x1c, 0x14, 0x17, 0x09, 0x4e, 0x04, 0x1e, 0x0f, 0x43, 0x0e,\n      0x19, 0x07, 0x0a, 0x06, 0x48, 0x08, 0x27, 0x09, 0x75, 0x0b, 0x3f, 0x41,\n      0x2a, 0x06, 0x3b, 0x05, 0x0a, 0x06, 0x51, 0x06, 0x01, 0x05, 0x10, 0x03,\n      0x05, 0x80, 0x8b, 0x62, 0x1e, 0x48, 0x08, 0x0a, 0x80, 0xa6, 0x5e, 0x22,\n      0x45, 0x0b, 0x0a, 0x06, 0x0d, 0x13, 0x39, 0x07, 0x0a, 0x36, 0x2c, 0x04,\n      0x10, 0x80, 0xc0, 0x3c, 0x64, 0x53, 0x0c, 0x48, 0x09, 0x0a, 0x46, 0x45,\n      0x1b, 0x48, 0x08, 0x53, 0x1d, 0x39, 0x81, 0x07, 0x46, 0x0a, 0x1d, 0x03,\n      0x47, 0x49, 0x37, 0x03, 0x0e, 0x08, 0x0a, 0x06, 0x39, 0x07, 0x0a, 0x81,\n      0x36, 0x19, 0x80, 0xb7, 0x01, 0x0f, 0x32, 0x0d, 0x83, 0x9b, 0x66, 0x75,\n      0x0b, 0x80, 0xc4, 0x8a, 0xbc, 0x84, 0x2f, 0x8f, 0xd1, 0x82, 0x47, 0xa1,\n      0xb9, 0x82, 0x39, 0x07, 0x2a, 0x04, 0x02, 0x60, 0x26, 0x0a, 0x46, 0x0a,\n      0x28, 0x05, 0x13, 0x82, 0xb0, 0x5b, 0x65, 0x4b, 0x04, 0x39, 0x07, 0x11,\n      0x40, 0x05, 0x0b, 0x02, 0x0e, 0x97, 0xf8, 0x08, 0x84, 0xd6, 0x2a, 0x09,\n      0xa2, 0xf7, 0x81, 0x1f, 0x31, 0x03, 0x11, 0x04, 0x08, 0x81, 0x8c, 0x89,\n      0x04, 0x6b, 0x05, 0x0d, 0x03, 0x09, 0x07, 0x10, 0x93, 0x60, 0x80, 0xf6,\n      0x0a, 0x73, 0x08, 0x6e, 0x17, 0x46, 0x80, 0x9a, 0x14, 0x0c, 0x57, 0x09,\n      0x19, 0x80, 0x87, 0x81, 0x47, 0x03, 0x85, 0x42, 0x0f, 0x15, 0x85, 0x50,\n      0x2b, 0x80, 0xd5, 0x2d, 0x03, 0x1a, 0x04, 0x02, 0x81, 0x70, 0x3a, 0x05,\n      0x01, 0x85, 0x00, 0x80, 0xd7, 0x29, 0x4c, 0x04, 0x0a, 0x04, 0x02, 0x83,\n      0x11, 0x44, 0x4c, 0x3d, 0x80, 0xc2, 0x3c, 0x06, 0x01, 0x04, 0x55, 0x05,\n      0x1b, 0x34, 0x02, 0x81, 0x0e, 0x2c, 0x04, 0x64, 0x0c, 0x56, 0x0a, 0x80,\n      0xae, 0x38, 0x1d, 0x0d, 0x2c, 0x04, 0x09, 0x07, 0x02, 0x0e, 0x06, 0x80,\n      0x9a, 0x83, 0xd8, 0x08, 0x0d, 0x03, 0x0d, 0x03, 0x74, 0x0c, 0x59, 0x07,\n      0x0c, 0x14, 0x0c, 0x04, 0x38, 0x08, 0x0a, 0x06, 0x28, 0x08, 0x22, 0x4e,\n      0x81, 0x54, 0x0c, 0x15, 0x03, 0x03, 0x05, 0x07, 0x09, 0x19, 0x07, 0x07,\n      0x09, 0x03, 0x0d, 0x07, 0x29, 0x80, 0xcb, 0x25, 0x0a, 0x84, 0x06,\n  };\n  auto lower = static_cast<uint16_t>(cp);\n  if (cp < 0x10000) {\n    return is_printable(lower, singletons0,\n                        sizeof(singletons0) / sizeof(*singletons0),\n                        singletons0_lower, normal0, sizeof(normal0));\n  }\n  if (cp < 0x20000) {\n    return is_printable(lower, singletons1,\n                        sizeof(singletons1) / sizeof(*singletons1),\n                        singletons1_lower, normal1, sizeof(normal1));\n  }\n  if (0x2a6de <= cp && cp < 0x2a700) return false;\n  if (0x2b735 <= cp && cp < 0x2b740) return false;\n  if (0x2b81e <= cp && cp < 0x2b820) return false;\n  if (0x2cea2 <= cp && cp < 0x2ceb0) return false;\n  if (0x2ebe1 <= cp && cp < 0x2f800) return false;\n  if (0x2fa1e <= cp && cp < 0x30000) return false;\n  if (0x3134b <= cp && cp < 0xe0100) return false;\n  if (0xe01f0 <= cp && cp < 0x110000) return false;\n  return cp < 0x110000;\n}\n\n}  // namespace detail\n\nFMT_END_NAMESPACE\n\n#endif  // FMT_FORMAT_INL_H_\n"
  },
  {
    "path": "include/fmt/format.h",
    "content": "/*\n  Formatting library for C++\n\n  Copyright (c) 2012 - present, Victor Zverovich\n\n  Permission is hereby granted, free of charge, to any person obtaining\n  a copy of this software and associated documentation files (the\n  \"Software\"), to deal in the Software without restriction, including\n  without limitation the rights to use, copy, modify, merge, publish,\n  distribute, sublicense, and/or sell copies of the Software, and to\n  permit persons to whom the Software is furnished to do so, subject to\n  the following conditions:\n\n  The above copyright notice and this permission notice shall be\n  included in all copies or substantial portions of the Software.\n\n  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n  --- Optional exception to the license ---\n\n  As an exception, if, as a result of your compiling your source code, portions\n  of this Software are embedded into a machine-executable object form of such\n  source code, you may redistribute such embedded portions in such object form\n  without including the above copyright and permission notices.\n */\n\n#ifndef FMT_FORMAT_H_\n#define FMT_FORMAT_H_\n\n#ifndef _LIBCPP_REMOVE_TRANSITIVE_INCLUDES\n#  define _LIBCPP_REMOVE_TRANSITIVE_INCLUDES\n#  define FMT_REMOVE_TRANSITIVE_INCLUDES\n#endif\n\n#include \"base.h\"\n\n#ifndef FMT_MODULE\n#  include <cmath>    // std::signbit\n#  include <cstddef>  // std::byte\n#  include <cstdint>  // uint32_t\n#  include <cstdlib>  // std::malloc, std::free\n#  include <cstring>  // std::memcpy\n#  include <limits>   // std::numeric_limits\n#  include <new>      // std::bad_alloc\n#  if defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI)\n// Workaround for pre gcc 5 libstdc++.\n#    include <memory>  // std::allocator_traits\n#  endif\n#  include <stdexcept>     // std::runtime_error\n#  include <string>        // std::string\n#  include <system_error>  // std::system_error\n\n// Check FMT_CPLUSPLUS to avoid a warning in MSVC.\n#  if FMT_HAS_INCLUDE(<bit>) && FMT_CPLUSPLUS > 201703L\n#    include <bit>  // std::bit_cast\n#  endif\n\n// libc++ supports string_view in pre-c++17.\n#  if FMT_HAS_INCLUDE(<string_view>) && \\\n      (FMT_CPLUSPLUS >= 201703L || defined(_LIBCPP_VERSION))\n#    include <string_view>\n#    define FMT_USE_STRING_VIEW\n#  endif\n\n#  if FMT_MSC_VERSION\n#    include <intrin.h>  // _BitScanReverse[64], _umul128\n#  endif\n#endif  // FMT_MODULE\n\n#if defined(FMT_USE_NONTYPE_TEMPLATE_ARGS)\n// Use the provided definition.\n#elif defined(__NVCOMPILER)\n#  define FMT_USE_NONTYPE_TEMPLATE_ARGS 0\n#elif FMT_GCC_VERSION >= 903 && FMT_CPLUSPLUS >= 201709L\n#  define FMT_USE_NONTYPE_TEMPLATE_ARGS 1\n#elif defined(__cpp_nontype_template_args) && \\\n    __cpp_nontype_template_args >= 201911L\n#  define FMT_USE_NONTYPE_TEMPLATE_ARGS 1\n#elif FMT_CLANG_VERSION >= 1200 && FMT_CPLUSPLUS >= 202002L\n#  define FMT_USE_NONTYPE_TEMPLATE_ARGS 1\n#else\n#  define FMT_USE_NONTYPE_TEMPLATE_ARGS 0\n#endif\n\n#if defined __cpp_inline_variables && __cpp_inline_variables >= 201606L\n#  define FMT_INLINE_VARIABLE inline\n#else\n#  define FMT_INLINE_VARIABLE\n#endif\n\n// Check if RTTI is disabled.\n#ifdef FMT_USE_RTTI\n// Use the provided definition.\n#elif defined(__GXX_RTTI) || FMT_HAS_FEATURE(cxx_rtti) || defined(_CPPRTTI) || \\\n    defined(__INTEL_RTTI__) || defined(__RTTI)\n// __RTTI is for EDG compilers. _CPPRTTI is for MSVC.\n#  define FMT_USE_RTTI 1\n#else\n#  define FMT_USE_RTTI 0\n#endif\n\n// Visibility when compiled as a shared library/object.\n#if defined(FMT_LIB_EXPORT) || defined(FMT_SHARED)\n#  define FMT_SO_VISIBILITY(value) FMT_VISIBILITY(value)\n#else\n#  define FMT_SO_VISIBILITY(value)\n#endif\n\n#if FMT_GCC_VERSION || FMT_CLANG_VERSION\n#  define FMT_NOINLINE __attribute__((noinline))\n#else\n#  define FMT_NOINLINE\n#endif\n\n#ifdef FMT_DEPRECATED\n// Use the provided definition.\n#elif FMT_HAS_CPP14_ATTRIBUTE(deprecated)\n#  define FMT_DEPRECATED [[deprecated]]\n#else\n#  define FMT_DEPRECATED /* deprecated */\n#endif\n\n// Detect constexpr std::string.\n#if !FMT_USE_CONSTEVAL\n#  define FMT_USE_CONSTEXPR_STRING 0\n#elif defined(__cpp_lib_constexpr_string) && \\\n    __cpp_lib_constexpr_string >= 201907L\n#  if FMT_CLANG_VERSION && FMT_GLIBCXX_RELEASE\n// clang + libstdc++ are able to work only starting with gcc13.3\n// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113294\n#    if FMT_GLIBCXX_RELEASE < 13\n#      define FMT_USE_CONSTEXPR_STRING 0\n#    elif FMT_GLIBCXX_RELEASE == 13 && __GLIBCXX__ < 20240521\n#      define FMT_USE_CONSTEXPR_STRING 0\n#    else\n#      define FMT_USE_CONSTEXPR_STRING 1\n#    endif\n#  else\n#    define FMT_USE_CONSTEXPR_STRING 1\n#  endif\n#else\n#  define FMT_USE_CONSTEXPR_STRING 0\n#endif\n#if FMT_USE_CONSTEXPR_STRING\n#  define FMT_CONSTEXPR_STRING constexpr\n#else\n#  define FMT_CONSTEXPR_STRING\n#endif\n\n// GCC 4.9 doesn't support qualified names in specializations.\nnamespace std {\ntemplate <typename T> struct iterator_traits<fmt::basic_appender<T>> {\n  using iterator_category = output_iterator_tag;\n  using value_type = T;\n  using difference_type =\n      decltype(static_cast<int*>(nullptr) - static_cast<int*>(nullptr));\n  using pointer = void;\n  using reference = void;\n};\n}  // namespace std\n\n#ifdef FMT_THROW\n// Use the provided definition.\n#elif FMT_USE_EXCEPTIONS\n#  define FMT_THROW(x) throw x\n#else\n#  define FMT_THROW(x) ::fmt::assert_fail(__FILE__, __LINE__, (x).what())\n#endif\n\n#ifdef __clang_analyzer__\n#  define FMT_CLANG_ANALYZER 1\n#else\n#  define FMT_CLANG_ANALYZER 0\n#endif\n\n// Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of\n// integer formatter template instantiations to just one by only using the\n// largest integer type. This results in a reduction in binary size but will\n// cause a decrease in integer formatting performance.\n#if !defined(FMT_REDUCE_INT_INSTANTIATIONS)\n#  define FMT_REDUCE_INT_INSTANTIATIONS 0\n#endif\n\nFMT_BEGIN_NAMESPACE\n\ntemplate <typename Char, typename Traits, typename Allocator>\nstruct is_contiguous<std::basic_string<Char, Traits, Allocator>>\n    : std::true_type {};\n\nnamespace detail {\n\n// __builtin_clz is broken in clang with Microsoft codegen:\n// https://github.com/fmtlib/fmt/issues/519.\n#if !FMT_MSC_VERSION\n#  if FMT_HAS_BUILTIN(__builtin_clz) || FMT_GCC_VERSION || FMT_ICC_VERSION\n#    define FMT_BUILTIN_CLZ(n) __builtin_clz(n)\n#  endif\n#  if FMT_HAS_BUILTIN(__builtin_clzll) || FMT_GCC_VERSION || FMT_ICC_VERSION\n#    define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n)\n#  endif\n#endif\n\n// Some compilers masquerade as both MSVC and GCC but otherwise support\n// __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the\n// MSVC intrinsics if the clz and clzll builtins are not available.\n#if FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL)\n// Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning.\n#  ifndef __clang__\n#    pragma intrinsic(_BitScanReverse)\n#    ifdef _WIN64\n#      pragma intrinsic(_BitScanReverse64)\n#    endif\n#  endif\n\ninline auto clz(uint32_t x) -> int {\n  FMT_ASSERT(x != 0, \"\");\n  FMT_MSC_WARNING(suppress : 6102)  // Suppress a bogus static analysis warning.\n  unsigned long r = 0;\n  _BitScanReverse(&r, x);\n  return 31 ^ static_cast<int>(r);\n}\n#  define FMT_BUILTIN_CLZ(n) detail::clz(n)\n\ninline auto clzll(uint64_t x) -> int {\n  FMT_ASSERT(x != 0, \"\");\n  FMT_MSC_WARNING(suppress : 6102)  // Suppress a bogus static analysis warning.\n  unsigned long r = 0;\n#  ifdef _WIN64\n  _BitScanReverse64(&r, x);\n#  else\n  // Scan the high 32 bits.\n  if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32)))\n    return 63 ^ static_cast<int>(r + 32);\n  // Scan the low 32 bits.\n  _BitScanReverse(&r, static_cast<uint32_t>(x));\n#  endif\n  return 63 ^ static_cast<int>(r);\n}\n#  define FMT_BUILTIN_CLZLL(n) detail::clzll(n)\n#endif  // FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL)\n\nFMT_CONSTEXPR inline void abort_fuzzing_if(bool condition) {\n  ignore_unused(condition);\n#ifdef FMT_FUZZ\n  if (condition) throw std::runtime_error(\"fuzzing limit reached\");\n#endif\n}\n\n#if defined(FMT_USE_STRING_VIEW)\ntemplate <typename Char> using std_string_view = std::basic_string_view<Char>;\n#else\ntemplate <typename Char> struct std_string_view {\n  operator basic_string_view<Char>() const;\n};\n#endif\n\ntemplate <typename Char, Char... C> struct string_literal {\n  static constexpr Char value[sizeof...(C)] = {C...};\n  constexpr operator basic_string_view<Char>() const {\n    return {value, sizeof...(C)};\n  }\n};\n#if FMT_CPLUSPLUS < 201703L\ntemplate <typename Char, Char... C>\nconstexpr Char string_literal<Char, C...>::value[sizeof...(C)];\n#endif\n\n// Implementation of std::bit_cast for pre-C++20.\ntemplate <typename To, typename From, FMT_ENABLE_IF(sizeof(To) == sizeof(From))>\nFMT_CONSTEXPR20 auto bit_cast(const From& from) -> To {\n#ifdef __cpp_lib_bit_cast\n  if (is_constant_evaluated()) return std::bit_cast<To>(from);\n#endif\n  auto to = To();\n  // The cast suppresses a bogus -Wclass-memaccess on GCC.\n  std::memcpy(static_cast<void*>(&to), &from, sizeof(to));\n  return to;\n}\n\ninline auto is_big_endian() -> bool {\n#ifdef _WIN32\n  return false;\n#elif defined(__BIG_ENDIAN__)\n  return true;\n#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__)\n  return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__;\n#else\n  struct bytes {\n    char data[sizeof(int)];\n  };\n  return bit_cast<bytes>(1).data[0] == 0;\n#endif\n}\n\nclass uint128_fallback {\n private:\n  uint64_t lo_, hi_;\n\n public:\n  constexpr uint128_fallback(uint64_t hi, uint64_t lo) : lo_(lo), hi_(hi) {}\n  constexpr uint128_fallback(uint64_t value = 0) : lo_(value), hi_(0) {}\n\n  constexpr auto high() const noexcept -> uint64_t { return hi_; }\n  constexpr auto low() const noexcept -> uint64_t { return lo_; }\n\n  template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>\n  constexpr explicit operator T() const {\n    return static_cast<T>(lo_);\n  }\n\n  friend constexpr auto operator==(const uint128_fallback& lhs,\n                                   const uint128_fallback& rhs) -> bool {\n    return lhs.hi_ == rhs.hi_ && lhs.lo_ == rhs.lo_;\n  }\n  friend constexpr auto operator!=(const uint128_fallback& lhs,\n                                   const uint128_fallback& rhs) -> bool {\n    return !(lhs == rhs);\n  }\n  friend constexpr auto operator>(const uint128_fallback& lhs,\n                                  const uint128_fallback& rhs) -> bool {\n    return lhs.hi_ != rhs.hi_ ? lhs.hi_ > rhs.hi_ : lhs.lo_ > rhs.lo_;\n  }\n  friend constexpr auto operator|(const uint128_fallback& lhs,\n                                  const uint128_fallback& rhs)\n      -> uint128_fallback {\n    return {lhs.hi_ | rhs.hi_, lhs.lo_ | rhs.lo_};\n  }\n  friend constexpr auto operator&(const uint128_fallback& lhs,\n                                  const uint128_fallback& rhs)\n      -> uint128_fallback {\n    return {lhs.hi_ & rhs.hi_, lhs.lo_ & rhs.lo_};\n  }\n  friend constexpr auto operator~(const uint128_fallback& n)\n      -> uint128_fallback {\n    return {~n.hi_, ~n.lo_};\n  }\n  friend FMT_CONSTEXPR auto operator+(const uint128_fallback& lhs,\n                                      const uint128_fallback& rhs)\n      -> uint128_fallback {\n    auto result = uint128_fallback(lhs);\n    result += rhs;\n    return result;\n  }\n  friend FMT_CONSTEXPR auto operator*(const uint128_fallback& lhs, uint32_t rhs)\n      -> uint128_fallback {\n    FMT_ASSERT(lhs.hi_ == 0, \"\");\n    uint64_t hi = (lhs.lo_ >> 32) * rhs;\n    uint64_t lo = (lhs.lo_ & ~uint32_t()) * rhs;\n    uint64_t new_lo = (hi << 32) + lo;\n    return {(hi >> 32) + (new_lo < lo ? 1 : 0), new_lo};\n  }\n  friend constexpr auto operator-(const uint128_fallback& lhs, uint64_t rhs)\n      -> uint128_fallback {\n    return {lhs.hi_ - (lhs.lo_ < rhs ? 1 : 0), lhs.lo_ - rhs};\n  }\n  FMT_CONSTEXPR auto operator>>(int shift) const -> uint128_fallback {\n    if (shift == 64) return {0, hi_};\n    if (shift > 64) return uint128_fallback(0, hi_) >> (shift - 64);\n    return {hi_ >> shift, (hi_ << (64 - shift)) | (lo_ >> shift)};\n  }\n  FMT_CONSTEXPR auto operator<<(int shift) const -> uint128_fallback {\n    if (shift == 64) return {lo_, 0};\n    if (shift > 64) return uint128_fallback(lo_, 0) << (shift - 64);\n    return {hi_ << shift | (lo_ >> (64 - shift)), (lo_ << shift)};\n  }\n  FMT_CONSTEXPR auto operator>>=(int shift) -> uint128_fallback& {\n    return *this = *this >> shift;\n  }\n  FMT_CONSTEXPR void operator+=(uint128_fallback n) {\n    uint64_t new_lo = lo_ + n.lo_;\n    uint64_t new_hi = hi_ + n.hi_ + (new_lo < lo_ ? 1 : 0);\n    FMT_ASSERT(new_hi >= hi_, \"\");\n    lo_ = new_lo;\n    hi_ = new_hi;\n  }\n  FMT_CONSTEXPR void operator&=(uint128_fallback n) {\n    lo_ &= n.lo_;\n    hi_ &= n.hi_;\n  }\n\n  FMT_CONSTEXPR20 auto operator+=(uint64_t n) noexcept -> uint128_fallback& {\n    if (is_constant_evaluated()) {\n      lo_ += n;\n      hi_ += (lo_ < n ? 1 : 0);\n      return *this;\n    }\n#if FMT_HAS_BUILTIN(__builtin_addcll) && !defined(__ibmxl__)\n    unsigned long long carry;\n    lo_ = __builtin_addcll(lo_, n, 0, &carry);\n    hi_ += carry;\n#elif FMT_HAS_BUILTIN(__builtin_ia32_addcarryx_u64) && !defined(__ibmxl__)\n    unsigned long long result;\n    auto carry = __builtin_ia32_addcarryx_u64(0, lo_, n, &result);\n    lo_ = result;\n    hi_ += carry;\n#elif defined(_MSC_VER) && defined(_M_X64)\n    auto carry = _addcarry_u64(0, lo_, n, &lo_);\n    _addcarry_u64(carry, hi_, 0, &hi_);\n#else\n    lo_ += n;\n    hi_ += (lo_ < n ? 1 : 0);\n#endif\n    return *this;\n  }\n};\n\nusing uint128_t = conditional_t<FMT_USE_INT128, uint128_opt, uint128_fallback>;\n\n#ifdef UINTPTR_MAX\nusing uintptr_t = ::uintptr_t;\n#else\nusing uintptr_t = uint128_t;\n#endif\n\n// Returns the largest possible value for type T. Same as\n// std::numeric_limits<T>::max() but shorter and not affected by the max macro.\ntemplate <typename T> constexpr auto max_value() -> T {\n  return (std::numeric_limits<T>::max)();\n}\ntemplate <typename T> constexpr auto num_bits() -> int {\n  return std::numeric_limits<T>::digits;\n}\n// std::numeric_limits<T>::digits may return 0 for 128-bit ints.\ntemplate <> constexpr auto num_bits<int128_opt>() -> int { return 128; }\ntemplate <> constexpr auto num_bits<uint128_opt>() -> int { return 128; }\ntemplate <> constexpr auto num_bits<uint128_fallback>() -> int { return 128; }\n\n// A heterogeneous bit_cast used for converting 96-bit long double to uint128_t\n// and 128-bit pointers to uint128_fallback.\ntemplate <typename To, typename From, FMT_ENABLE_IF(sizeof(To) > sizeof(From))>\ninline auto bit_cast(const From& from) -> To {\n  constexpr auto size = static_cast<int>(sizeof(From) / sizeof(unsigned short));\n  struct data_t {\n    unsigned short value[static_cast<unsigned>(size)];\n  } data = bit_cast<data_t>(from);\n  auto result = To();\n  if (const_check(is_big_endian())) {\n    for (int i = 0; i < size; ++i)\n      result = (result << num_bits<unsigned short>()) | data.value[i];\n  } else {\n    for (int i = size - 1; i >= 0; --i)\n      result = (result << num_bits<unsigned short>()) | data.value[i];\n  }\n  return result;\n}\n\ntemplate <typename UInt>\nFMT_CONSTEXPR20 inline auto countl_zero_fallback(UInt n) -> int {\n  int lz = 0;\n  constexpr UInt msb_mask = static_cast<UInt>(1) << (num_bits<UInt>() - 1);\n  for (; (n & msb_mask) == 0; n <<= 1) lz++;\n  return lz;\n}\n\nFMT_CONSTEXPR20 inline auto countl_zero(uint32_t n) -> int {\n#ifdef FMT_BUILTIN_CLZ\n  if (!is_constant_evaluated()) return FMT_BUILTIN_CLZ(n);\n#endif\n  return countl_zero_fallback(n);\n}\n\nFMT_CONSTEXPR20 inline auto countl_zero(uint64_t n) -> int {\n#ifdef FMT_BUILTIN_CLZLL\n  if (!is_constant_evaluated()) return FMT_BUILTIN_CLZLL(n);\n#endif\n  return countl_zero_fallback(n);\n}\n\nFMT_INLINE void assume(bool condition) {\n  (void)condition;\n#if FMT_HAS_BUILTIN(__builtin_assume) && !FMT_ICC_VERSION\n  __builtin_assume(condition);\n#elif FMT_GCC_VERSION\n  if (!condition) __builtin_unreachable();\n#endif\n}\n\n// Attempts to reserve space for n extra characters in the output range.\n// Returns a pointer to the reserved range or a reference to it.\ntemplate <typename OutputIt,\n          FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value&&\n                            is_contiguous<typename OutputIt::container>::value)>\n#if FMT_CLANG_VERSION >= 307 && !FMT_ICC_VERSION\n__attribute__((no_sanitize(\"undefined\")))\n#endif\nFMT_CONSTEXPR20 inline auto\nreserve(OutputIt it, size_t n) -> typename OutputIt::value_type* {\n  auto& c = get_container(it);\n  size_t size = c.size();\n  c.resize(size + n);\n  return &c[size];\n}\n\ntemplate <typename T>\nFMT_CONSTEXPR20 inline auto reserve(basic_appender<T> it, size_t n)\n    -> basic_appender<T> {\n  buffer<T>& buf = get_container(it);\n  buf.try_reserve(buf.size() + n);\n  return it;\n}\n\ntemplate <typename Iterator>\nconstexpr auto reserve(Iterator& it, size_t) -> Iterator& {\n  return it;\n}\n\ntemplate <typename OutputIt>\nusing reserve_iterator =\n    remove_reference_t<decltype(reserve(std::declval<OutputIt&>(), 0))>;\n\ntemplate <typename T, typename OutputIt>\nconstexpr auto to_pointer(OutputIt, size_t) -> T* {\n  return nullptr;\n}\ntemplate <typename T> FMT_CONSTEXPR auto to_pointer(T*& ptr, size_t n) -> T* {\n  T* begin = ptr;\n  ptr += n;\n  return begin;\n}\ntemplate <typename T>\nFMT_CONSTEXPR20 auto to_pointer(basic_appender<T> it, size_t n) -> T* {\n  buffer<T>& buf = get_container(it);\n  buf.try_reserve(buf.size() + n);\n  auto size = buf.size();\n  if (buf.capacity() < size + n) return nullptr;\n  buf.try_resize(size + n);\n  return buf.data() + size;\n}\n\ntemplate <typename OutputIt,\n          FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value&&\n                            is_contiguous<typename OutputIt::container>::value)>\ninline auto base_iterator(OutputIt it,\n                          typename OutputIt::container_type::value_type*)\n    -> OutputIt {\n  return it;\n}\n\ntemplate <typename Iterator>\nconstexpr auto base_iterator(Iterator, Iterator it) -> Iterator {\n  return it;\n}\n\n// <algorithm> is spectacularly slow to compile in C++20 so use a simple fill_n\n// instead (#1998).\ntemplate <typename OutputIt, typename Size, typename T>\nFMT_CONSTEXPR auto fill_n(OutputIt out, Size count, const T& value)\n    -> OutputIt {\n  for (Size i = 0; i < count; ++i) *out++ = value;\n  return out;\n}\ntemplate <typename T, typename Size>\nFMT_CONSTEXPR20 auto fill_n(T* out, Size count, char value) -> T* {\n  if (is_constant_evaluated()) return fill_n<T*, Size, T>(out, count, value);\n  static_assert(sizeof(T) == 1,\n                \"sizeof(T) must be 1 to use char for initialization\");\n  std::memset(out, value, to_unsigned(count));\n  return out + count;\n}\n\ntemplate <typename OutChar, typename InputIt, typename OutputIt>\nFMT_CONSTEXPR FMT_NOINLINE auto copy_noinline(InputIt begin, InputIt end,\n                                              OutputIt out) -> OutputIt {\n  return copy<OutChar>(begin, end, out);\n}\n\n// A public domain branchless UTF-8 decoder by Christopher Wellons:\n// https://github.com/skeeto/branchless-utf8\n/* Decode the next character, c, from s, reporting errors in e.\n *\n * Since this is a branchless decoder, four bytes will be read from the\n * buffer regardless of the actual length of the next character. This\n * means the buffer _must_ have at least three bytes of zero padding\n * following the end of the data stream.\n *\n * Errors are reported in e, which will be non-zero if the parsed\n * character was somehow invalid: invalid byte sequence, non-canonical\n * encoding, or a surrogate half.\n *\n * The function returns a pointer to the next character. When an error\n * occurs, this pointer will be a guess that depends on the particular\n * error, but it will always advance at least one byte.\n */\nFMT_CONSTEXPR inline auto utf8_decode(const char* s, uint32_t* c, int* e)\n    -> const char* {\n  constexpr int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07};\n  constexpr uint32_t mins[] = {4194304, 0, 128, 2048, 65536};\n  constexpr int shiftc[] = {0, 18, 12, 6, 0};\n  constexpr int shifte[] = {0, 6, 4, 2, 0};\n\n  int len = \"\\1\\1\\1\\1\\1\\1\\1\\1\\1\\1\\1\\1\\1\\1\\1\\1\\0\\0\\0\\0\\0\\0\\0\\0\\2\\2\\2\\2\\3\\3\\4\"\n      [static_cast<unsigned char>(*s) >> 3];\n  // Compute the pointer to the next character early so that the next\n  // iteration can start working on the next character. Neither Clang\n  // nor GCC figure out this reordering on their own.\n  const char* next = s + len + !len;\n\n  using uchar = unsigned char;\n\n  // Assume a four-byte character and load four bytes. Unused bits are\n  // shifted out.\n  *c = uint32_t(uchar(s[0]) & masks[len]) << 18;\n  *c |= uint32_t(uchar(s[1]) & 0x3f) << 12;\n  *c |= uint32_t(uchar(s[2]) & 0x3f) << 6;\n  *c |= uint32_t(uchar(s[3]) & 0x3f) << 0;\n  *c >>= shiftc[len];\n\n  // Accumulate the various error conditions.\n  *e = (*c < mins[len]) << 6;       // non-canonical encoding\n  *e |= ((*c >> 11) == 0x1b) << 7;  // surrogate half?\n  *e |= (*c > 0x10FFFF) << 8;       // out of range?\n  *e |= (uchar(s[1]) & 0xc0) >> 2;\n  *e |= (uchar(s[2]) & 0xc0) >> 4;\n  *e |= uchar(s[3]) >> 6;\n  *e ^= 0x2a;  // top two bits of each tail byte correct?\n  *e >>= shifte[len];\n\n  return next;\n}\n\nconstexpr FMT_INLINE_VARIABLE uint32_t invalid_code_point = ~uint32_t();\n\n// Invokes f(cp, sv) for every code point cp in s with sv being the string view\n// corresponding to the code point. cp is invalid_code_point on error.\ntemplate <typename F>\nFMT_CONSTEXPR void for_each_codepoint(string_view s, F f) {\n  auto decode = [f](const char* buf_ptr, const char* ptr) {\n    auto cp = uint32_t();\n    auto error = 0;\n    auto end = utf8_decode(buf_ptr, &cp, &error);\n    bool result = f(error ? invalid_code_point : cp,\n                    string_view(ptr, error ? 1 : to_unsigned(end - buf_ptr)));\n    return result ? (error ? buf_ptr + 1 : end) : nullptr;\n  };\n\n  auto p = s.data();\n  const size_t block_size = 4;  // utf8_decode always reads blocks of 4 chars.\n  if (s.size() >= block_size) {\n    for (auto end = p + s.size() - block_size + 1; p < end;) {\n      p = decode(p, p);\n      if (!p) return;\n    }\n  }\n  auto num_chars_left = to_unsigned(s.data() + s.size() - p);\n  if (num_chars_left == 0) return;\n\n  // Suppress bogus -Wstringop-overflow.\n  if (FMT_GCC_VERSION) num_chars_left &= 3;\n  char buf[2 * block_size - 1] = {};\n  copy<char>(p, p + num_chars_left, buf);\n  const char* buf_ptr = buf;\n  do {\n    auto end = decode(buf_ptr, p);\n    if (!end) return;\n    p += end - buf_ptr;\n    buf_ptr = end;\n  } while (buf_ptr < buf + num_chars_left);\n}\n\nFMT_CONSTEXPR inline auto display_width_of(uint32_t cp) noexcept -> size_t {\n  return to_unsigned(\n      1 + (cp >= 0x1100 &&\n           (cp <= 0x115f ||  // Hangul Jamo init. consonants\n            cp == 0x2329 ||  // LEFT-POINTING ANGLE BRACKET\n            cp == 0x232a ||  // RIGHT-POINTING ANGLE BRACKET\n            // CJK ... Yi except IDEOGRAPHIC HALF FILL SPACE:\n            (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) ||\n            (cp >= 0xac00 && cp <= 0xd7a3) ||    // Hangul Syllables\n            (cp >= 0xf900 && cp <= 0xfaff) ||    // CJK Compatibility Ideographs\n            (cp >= 0xfe10 && cp <= 0xfe19) ||    // Vertical Forms\n            (cp >= 0xfe30 && cp <= 0xfe6f) ||    // CJK Compatibility Forms\n            (cp >= 0xff00 && cp <= 0xff60) ||    // Fullwidth Forms\n            (cp >= 0xffe0 && cp <= 0xffe6) ||    // Fullwidth Forms\n            (cp >= 0x20000 && cp <= 0x2fffd) ||  // CJK\n            (cp >= 0x30000 && cp <= 0x3fffd) ||\n            // Miscellaneous Symbols and Pictographs + Emoticons:\n            (cp >= 0x1f300 && cp <= 0x1f64f) ||\n            // Supplemental Symbols and Pictographs:\n            (cp >= 0x1f900 && cp <= 0x1f9ff))));\n}\n\ntemplate <typename T> struct is_integral : std::is_integral<T> {};\ntemplate <> struct is_integral<int128_opt> : std::true_type {};\ntemplate <> struct is_integral<uint128_t> : std::true_type {};\n\ntemplate <typename T>\nusing is_signed =\n    std::integral_constant<bool, std::numeric_limits<T>::is_signed ||\n                                     std::is_same<T, int128_opt>::value>;\n\ntemplate <typename T>\nusing is_integer =\n    bool_constant<is_integral<T>::value && !std::is_same<T, bool>::value &&\n                  !std::is_same<T, char>::value &&\n                  !std::is_same<T, wchar_t>::value>;\n\n#if defined(FMT_USE_FLOAT128)\n// Use the provided definition.\n#elif FMT_CLANG_VERSION >= 309 && FMT_HAS_INCLUDE(<quadmath.h>)\n#  define FMT_USE_FLOAT128 1\n#elif FMT_GCC_VERSION && defined(_GLIBCXX_USE_FLOAT128) && \\\n    !defined(__STRICT_ANSI__)\n#  define FMT_USE_FLOAT128 1\n#else\n#  define FMT_USE_FLOAT128 0\n#endif\n#if FMT_USE_FLOAT128\nusing float128 = __float128;\n#else\nstruct float128 {};\n#endif\n\ntemplate <typename T> using is_float128 = std::is_same<T, float128>;\n\ntemplate <typename T> struct is_floating_point : std::is_floating_point<T> {};\ntemplate <> struct is_floating_point<float128> : std::true_type {};\n\ntemplate <typename T, bool = is_floating_point<T>::value>\nstruct is_fast_float : bool_constant<std::numeric_limits<T>::is_iec559 &&\n                                     sizeof(T) <= sizeof(double)> {};\ntemplate <typename T> struct is_fast_float<T, false> : std::false_type {};\n\ntemplate <typename T>\nusing fast_float_t = conditional_t<sizeof(T) == sizeof(double), double, float>;\n\ntemplate <typename T>\nusing is_double_double = bool_constant<std::numeric_limits<T>::digits == 106>;\n\n#ifndef FMT_USE_FULL_CACHE_DRAGONBOX\n#  define FMT_USE_FULL_CACHE_DRAGONBOX 0\n#endif\n\n// An allocator that uses malloc/free to allow removing dependency on the C++\n// standard libary runtime. std::decay is used for back_inserter to be found by\n// ADL when applied to memory_buffer.\ntemplate <typename T> struct allocator : private std::decay<void> {\n  using value_type = T;\n\n  auto allocate(size_t n) -> T* {\n    FMT_ASSERT(n <= max_value<size_t>() / sizeof(T), \"\");\n    T* p = static_cast<T*>(std::malloc(n * sizeof(T)));\n    if (!p) FMT_THROW(std::bad_alloc());\n    return p;\n  }\n\n  void deallocate(T* p, size_t) { std::free(p); }\n\n  constexpr friend auto operator==(allocator, allocator) noexcept -> bool {\n    return true;  // All instances of this allocator are equivalent.\n  }\n  constexpr friend auto operator!=(allocator, allocator) noexcept -> bool {\n    return false;\n  }\n};\n\n}  // namespace detail\n\nFMT_BEGIN_EXPORT\n\n// The number of characters to store in the basic_memory_buffer object itself\n// to avoid dynamic memory allocation.\nenum { inline_buffer_size = 500 };\n\n/**\n * A dynamically growing memory buffer for trivially copyable/constructible\n * types with the first `SIZE` elements stored in the object itself. Most\n * commonly used via the `memory_buffer` alias for `char`.\n *\n * **Example**:\n *\n *     auto out = fmt::memory_buffer();\n *     fmt::format_to(std::back_inserter(out), \"The answer is {}.\", 42);\n *\n * This will append \"The answer is 42.\" to `out`. The buffer content can be\n * converted to `std::string` with `to_string(out)`.\n */\ntemplate <typename T, size_t SIZE = inline_buffer_size,\n          typename Allocator = detail::allocator<T>>\nclass basic_memory_buffer : public detail::buffer<T> {\n private:\n  T store_[SIZE];\n\n  // Don't inherit from Allocator to avoid generating type_info for it.\n  FMT_NO_UNIQUE_ADDRESS Allocator alloc_;\n\n  // Deallocate memory allocated by the buffer.\n  FMT_CONSTEXPR20 void deallocate() {\n    T* data = this->data();\n    if (data != store_) alloc_.deallocate(data, this->capacity());\n  }\n\n  static FMT_CONSTEXPR20 void grow(detail::buffer<T>& buf, size_t size) {\n    detail::abort_fuzzing_if(size > 5000);\n    auto& self = static_cast<basic_memory_buffer&>(buf);\n    const size_t max_size =\n        std::allocator_traits<Allocator>::max_size(self.alloc_);\n    size_t old_capacity = buf.capacity();\n    size_t new_capacity = old_capacity + old_capacity / 2;\n    if (size > new_capacity)\n      new_capacity = size;\n    else if (new_capacity > max_size)\n      new_capacity = max_of(size, max_size);\n    T* old_data = buf.data();\n    T* new_data = self.alloc_.allocate(new_capacity);\n    // Suppress a bogus -Wstringop-overflow in gcc 13.1 (#3481).\n    detail::assume(buf.size() <= new_capacity);\n    // The following code doesn't throw, so the raw pointer above doesn't leak.\n    memcpy(new_data, old_data, buf.size() * sizeof(T));\n    self.set(new_data, new_capacity);\n    // deallocate must not throw according to the standard, but even if it does,\n    // the buffer already uses the new storage and will deallocate it in\n    // destructor.\n    if (old_data != self.store_) self.alloc_.deallocate(old_data, old_capacity);\n  }\n\n public:\n  using value_type = T;\n  using const_reference = const T&;\n\n  FMT_CONSTEXPR explicit basic_memory_buffer(\n      const Allocator& alloc = Allocator())\n      : detail::buffer<T>(grow), alloc_(alloc) {\n    this->set(store_, SIZE);\n    if (detail::is_constant_evaluated()) detail::fill_n(store_, SIZE, T());\n  }\n  FMT_CONSTEXPR20 ~basic_memory_buffer() { deallocate(); }\n\n private:\n  template <typename Alloc = Allocator,\n            FMT_ENABLE_IF(std::allocator_traits<Alloc>::\n                              propagate_on_container_move_assignment::value)>\n  FMT_CONSTEXPR20 auto move_alloc(basic_memory_buffer& other) -> bool {\n    alloc_ = std::move(other.alloc_);\n    return true;\n  }\n  // If the allocator does not propagate then copy the data from other.\n  template <typename Alloc = Allocator,\n            FMT_ENABLE_IF(!std::allocator_traits<Alloc>::\n                              propagate_on_container_move_assignment::value)>\n  FMT_CONSTEXPR20 auto move_alloc(basic_memory_buffer& other) -> bool {\n    T* data = other.data();\n    if (alloc_ == other.alloc_ || data == other.store_) return true;\n    size_t size = other.size();\n    // Perform copy operation, allocators are different.\n    this->resize(size);\n    detail::copy<T>(data, data + size, this->data());\n    return false;\n  }\n\n  // Move data from other to this buffer.\n  FMT_CONSTEXPR20 void move(basic_memory_buffer& other) {\n    T* data = other.data();\n    size_t size = other.size(), capacity = other.capacity();\n    if (!move_alloc(other)) return;\n    if (data == other.store_) {\n      this->set(store_, capacity);\n      detail::copy<T>(other.store_, other.store_ + size, store_);\n    } else {\n      this->set(data, capacity);\n      // Set pointer to the inline array so that delete is not called\n      // when deallocating.\n      other.set(other.store_, 0);\n      other.clear();\n    }\n    this->resize(size);\n  }\n\n public:\n  /// Constructs a `basic_memory_buffer` object moving the content of the other\n  /// object to it.\n  FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other) noexcept\n      : detail::buffer<T>(grow) {\n    move(other);\n  }\n\n  /// Moves the content of the other `basic_memory_buffer` object to this one.\n  auto operator=(basic_memory_buffer&& other) noexcept -> basic_memory_buffer& {\n    FMT_ASSERT(this != &other, \"\");\n    deallocate();\n    move(other);\n    return *this;\n  }\n\n  // Returns a copy of the allocator associated with this buffer.\n  auto get_allocator() const -> Allocator { return alloc_; }\n\n  /// Resizes the buffer to contain `count` elements. If T is a POD type new\n  /// elements may not be initialized.\n  FMT_CONSTEXPR void resize(size_t count) { this->try_resize(count); }\n\n  /// Increases the buffer capacity to `new_capacity`.\n  void reserve(size_t new_capacity) { this->try_reserve(new_capacity); }\n\n  using detail::buffer<T>::append;\n  template <typename ContiguousRange>\n  FMT_CONSTEXPR20 void append(const ContiguousRange& range) {\n    append(range.data(), range.data() + range.size());\n  }\n};\n\nusing memory_buffer = basic_memory_buffer<char>;\n\ntemplate <size_t SIZE>\nFMT_NODISCARD auto to_string(const basic_memory_buffer<char, SIZE>& buf)\n    -> std::string {\n  auto size = buf.size();\n  detail::assume(size < std::string().max_size());\n  return {buf.data(), size};\n}\n\n// A writer to a buffered stream. It doesn't own the underlying stream.\nclass writer {\n private:\n  detail::buffer<char>* buf_;\n\n  // We cannot create a file buffer in advance because any write to a FILE may\n  // invalidate it.\n  FILE* file_;\n\n public:\n  inline writer(FILE* f) : buf_(nullptr), file_(f) {}\n  inline writer(detail::buffer<char>& buf) : buf_(&buf) {}\n\n  /// Formats `args` according to specifications in `fmt` and writes the\n  /// output to the file.\n  template <typename... T> void print(format_string<T...> fmt, T&&... args) {\n    if (buf_)\n      fmt::format_to(appender(*buf_), fmt, std::forward<T>(args)...);\n    else\n      fmt::print(file_, fmt, std::forward<T>(args)...);\n  }\n};\n\nclass string_buffer {\n private:\n  std::string str_;\n  detail::container_buffer<std::string> buf_;\n\n public:\n  inline string_buffer() : buf_(str_) {}\n\n  inline operator writer() { return buf_; }\n  inline auto str() -> std::string& { return str_; }\n};\n\ntemplate <typename T, size_t SIZE, typename Allocator>\nstruct is_contiguous<basic_memory_buffer<T, SIZE, Allocator>> : std::true_type {\n};\n\n// Suppress a misleading warning in older versions of clang.\nFMT_PRAGMA_CLANG(diagnostic ignored \"-Wweak-vtables\")\n\n/// An error reported from a formatting function.\nclass FMT_SO_VISIBILITY(\"default\") format_error : public std::runtime_error {\n public:\n  using std::runtime_error::runtime_error;\n};\n\nclass loc_value;\n\nFMT_END_EXPORT\nnamespace detail {\nFMT_API auto write_console(int fd, string_view text) -> bool;\nFMT_API void print(FILE*, string_view);\n}  // namespace detail\n\nnamespace detail {\ntemplate <typename Char, size_t N> struct fixed_string {\n  FMT_CONSTEXPR20 fixed_string(const Char (&s)[N]) {\n    detail::copy<Char, const Char*, Char*>(static_cast<const Char*>(s), s + N,\n                                           data);\n  }\n  Char data[N] = {};\n};\n\n// Converts a compile-time string to basic_string_view.\nFMT_EXPORT template <typename Char, size_t N>\nconstexpr auto compile_string_to_view(const Char (&s)[N])\n    -> basic_string_view<Char> {\n  // Remove trailing NUL character if needed. Won't be present if this is used\n  // with a raw character array (i.e. not defined as a string).\n  return {s, N - (std::char_traits<Char>::to_int_type(s[N - 1]) == 0 ? 1 : 0)};\n}\nFMT_EXPORT template <typename Char>\nconstexpr auto compile_string_to_view(basic_string_view<Char> s)\n    -> basic_string_view<Char> {\n  return s;\n}\n\n// Returns true if value is negative, false otherwise.\n// Same as `value < 0` but doesn't produce warnings if T is an unsigned type.\ntemplate <typename T, FMT_ENABLE_IF(is_signed<T>::value)>\nconstexpr auto is_negative(T value) -> bool {\n  return value < 0;\n}\ntemplate <typename T, FMT_ENABLE_IF(!is_signed<T>::value)>\nconstexpr auto is_negative(T) -> bool {\n  return false;\n}\n\n// Smallest of uint32_t, uint64_t, uint128_t that is large enough to\n// represent all values of an integral type T.\ntemplate <typename T>\nusing uint32_or_64_or_128_t =\n    conditional_t<num_bits<T>() <= 32 && !FMT_REDUCE_INT_INSTANTIATIONS,\n                  uint32_t,\n                  conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>>;\ntemplate <typename T>\nusing uint64_or_128_t = conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>;\n\n#define FMT_POWERS_OF_10(factor)                                  \\\n  factor * 10, (factor) * 100, (factor) * 1000, (factor) * 10000, \\\n      (factor) * 100000, (factor) * 1000000, (factor) * 10000000, \\\n      (factor) * 100000000, (factor) * 1000000000\n\n// Converts value in the range [0, 100) to a string.\n// GCC generates slightly better code when value is pointer-size.\ninline auto digits2(size_t value) -> const char* {\n  // Align data since unaligned access may be slower when crossing a\n  // hardware-specific boundary.\n  alignas(2) static const char data[] =\n      \"0001020304050607080910111213141516171819\"\n      \"2021222324252627282930313233343536373839\"\n      \"4041424344454647484950515253545556575859\"\n      \"6061626364656667686970717273747576777879\"\n      \"8081828384858687888990919293949596979899\";\n  return &data[value * 2];\n}\n\ntemplate <typename Char> constexpr auto getsign(sign s) -> Char {\n  return static_cast<char>(((' ' << 24) | ('+' << 16) | ('-' << 8)) >>\n                           (static_cast<int>(s) * 8));\n}\n\ntemplate <typename T> FMT_CONSTEXPR auto count_digits_fallback(T n) -> int {\n  int count = 1;\n  for (;;) {\n    // Integer division is slow so do it for a group of four digits instead\n    // of for every digit. The idea comes from the talk by Alexandrescu\n    // \"Three Optimization Tips for C++\". See speed-test for a comparison.\n    if (n < 10) return count;\n    if (n < 100) return count + 1;\n    if (n < 1000) return count + 2;\n    if (n < 10000) return count + 3;\n    n /= 10000u;\n    count += 4;\n  }\n}\n#if FMT_USE_INT128\nFMT_CONSTEXPR inline auto count_digits(uint128_opt n) -> int {\n  return count_digits_fallback(n);\n}\n#endif\n\n#ifdef FMT_BUILTIN_CLZLL\n// It is a separate function rather than a part of count_digits to workaround\n// the lack of static constexpr in constexpr functions.\ninline auto do_count_digits(uint64_t n) -> int {\n  // This has comparable performance to the version by Kendall Willets\n  // (https://github.com/fmtlib/format-benchmark/blob/master/digits10)\n  // but uses smaller tables.\n  // Maps bsr(n) to ceil(log10(pow(2, bsr(n) + 1) - 1)).\n  static constexpr uint8_t bsr2log10[] = {\n      1,  1,  1,  2,  2,  2,  3,  3,  3,  4,  4,  4,  4,  5,  5,  5,\n      6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  9,  9,  9,  10, 10, 10,\n      10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 15,\n      15, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20};\n  auto t = bsr2log10[FMT_BUILTIN_CLZLL(n | 1) ^ 63];\n  static constexpr uint64_t zero_or_powers_of_10[] = {\n      0, 0, FMT_POWERS_OF_10(1U), FMT_POWERS_OF_10(1000000000ULL),\n      10000000000000000000ULL};\n  return t - (n < zero_or_powers_of_10[t]);\n}\n#endif\n\n// Returns the number of decimal digits in n. Leading zeros are not counted\n// except for n == 0 in which case count_digits returns 1.\nFMT_CONSTEXPR20 inline auto count_digits(uint64_t n) -> int {\n#ifdef FMT_BUILTIN_CLZLL\n  if (!is_constant_evaluated() && !FMT_OPTIMIZE_SIZE) return do_count_digits(n);\n#endif\n  return count_digits_fallback(n);\n}\n\n// Counts the number of digits in n. BITS = log2(radix).\ntemplate <int BITS, typename UInt>\nFMT_CONSTEXPR auto count_digits(UInt n) -> int {\n#ifdef FMT_BUILTIN_CLZ\n  if (!is_constant_evaluated() && num_bits<UInt>() == 32)\n    return (FMT_BUILTIN_CLZ(static_cast<uint32_t>(n) | 1) ^ 31) / BITS + 1;\n#endif\n  // Lambda avoids unreachable code warnings from NVHPC.\n  return [](UInt m) {\n    int num_digits = 0;\n    do {\n      ++num_digits;\n    } while ((m >>= BITS) != 0);\n    return num_digits;\n  }(n);\n}\n\n#ifdef FMT_BUILTIN_CLZ\n// It is a separate function rather than a part of count_digits to workaround\n// the lack of static constexpr in constexpr functions.\nFMT_INLINE auto do_count_digits(uint32_t n) -> int {\n// An optimization by Kendall Willets from https://bit.ly/3uOIQrB.\n// This increments the upper 32 bits (log10(T) - 1) when >= T is added.\n#  define FMT_INC(T) (((sizeof(#T) - 1ull) << 32) - T)\n  static constexpr uint64_t table[] = {\n      FMT_INC(0),          FMT_INC(0),          FMT_INC(0),           // 8\n      FMT_INC(10),         FMT_INC(10),         FMT_INC(10),          // 64\n      FMT_INC(100),        FMT_INC(100),        FMT_INC(100),         // 512\n      FMT_INC(1000),       FMT_INC(1000),       FMT_INC(1000),        // 4096\n      FMT_INC(10000),      FMT_INC(10000),      FMT_INC(10000),       // 32k\n      FMT_INC(100000),     FMT_INC(100000),     FMT_INC(100000),      // 256k\n      FMT_INC(1000000),    FMT_INC(1000000),    FMT_INC(1000000),     // 2048k\n      FMT_INC(10000000),   FMT_INC(10000000),   FMT_INC(10000000),    // 16M\n      FMT_INC(100000000),  FMT_INC(100000000),  FMT_INC(100000000),   // 128M\n      FMT_INC(1000000000), FMT_INC(1000000000), FMT_INC(1000000000),  // 1024M\n      FMT_INC(1000000000), FMT_INC(1000000000)                        // 4B\n  };\n  auto inc = table[FMT_BUILTIN_CLZ(n | 1) ^ 31];\n  return static_cast<int>((n + inc) >> 32);\n}\n#endif\n\n// Optional version of count_digits for better performance on 32-bit platforms.\nFMT_CONSTEXPR20 inline auto count_digits(uint32_t n) -> int {\n#ifdef FMT_BUILTIN_CLZ\n  if (!is_constant_evaluated() && !FMT_OPTIMIZE_SIZE) return do_count_digits(n);\n#endif\n  return count_digits_fallback(n);\n}\n\ntemplate <typename Int> constexpr auto digits10() noexcept -> int {\n  return std::numeric_limits<Int>::digits10;\n}\ntemplate <> constexpr auto digits10<int128_opt>() noexcept -> int { return 38; }\ntemplate <> constexpr auto digits10<uint128_t>() noexcept -> int { return 38; }\n\ntemplate <typename Char> struct thousands_sep_result {\n  std::string grouping;\n  Char thousands_sep;\n};\n\ntemplate <typename Char>\nFMT_API auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result<Char>;\ntemplate <typename Char>\ninline auto thousands_sep(locale_ref loc) -> thousands_sep_result<Char> {\n  auto result = thousands_sep_impl<char>(loc);\n  return {result.grouping, Char(result.thousands_sep)};\n}\ntemplate <>\ninline auto thousands_sep(locale_ref loc) -> thousands_sep_result<wchar_t> {\n  return thousands_sep_impl<wchar_t>(loc);\n}\n\ntemplate <typename Char>\nFMT_API auto decimal_point_impl(locale_ref loc) -> Char;\ntemplate <typename Char> inline auto decimal_point(locale_ref loc) -> Char {\n  return Char(decimal_point_impl<char>(loc));\n}\ntemplate <> inline auto decimal_point(locale_ref loc) -> wchar_t {\n  return decimal_point_impl<wchar_t>(loc);\n}\n\n#ifndef FMT_HEADER_ONLY\nFMT_BEGIN_EXPORT\nextern template FMT_API auto thousands_sep_impl<char>(locale_ref)\n    -> thousands_sep_result<char>;\nextern template FMT_API auto thousands_sep_impl<wchar_t>(locale_ref)\n    -> thousands_sep_result<wchar_t>;\nextern template FMT_API auto decimal_point_impl(locale_ref) -> char;\nextern template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t;\nFMT_END_EXPORT\n#endif  // FMT_HEADER_ONLY\n\n// Compares two characters for equality.\ntemplate <typename Char> auto equal2(const Char* lhs, const char* rhs) -> bool {\n  return lhs[0] == Char(rhs[0]) && lhs[1] == Char(rhs[1]);\n}\ninline auto equal2(const char* lhs, const char* rhs) -> bool {\n  return memcmp(lhs, rhs, 2) == 0;\n}\n\n// Writes a two-digit value to out.\ntemplate <typename Char>\nFMT_CONSTEXPR20 FMT_INLINE void write2digits(Char* out, size_t value) {\n  if (!is_constant_evaluated() && std::is_same<Char, char>::value &&\n      !FMT_OPTIMIZE_SIZE) {\n    memcpy(out, digits2(value), 2);\n    return;\n  }\n  *out++ = static_cast<Char>('0' + value / 10);\n  *out = static_cast<Char>('0' + value % 10);\n}\n\n// Formats a decimal unsigned integer value writing to out pointing to a buffer\n// of specified size. The caller must ensure that the buffer is large enough.\ntemplate <typename Char, typename UInt>\nFMT_CONSTEXPR20 auto do_format_decimal(Char* out, UInt value, int size)\n    -> Char* {\n  FMT_ASSERT(size >= count_digits(value), \"invalid digit count\");\n  unsigned n = to_unsigned(size);\n  while (value >= 100) {\n    // Integer division is slow so do it for a group of two digits instead\n    // of for every digit. The idea comes from the talk by Alexandrescu\n    // \"Three Optimization Tips for C++\". See speed-test for a comparison.\n    n -= 2;\n    write2digits(out + n, static_cast<unsigned>(value % 100));\n    value /= 100;\n  }\n  if (value >= 10) {\n    n -= 2;\n    write2digits(out + n, static_cast<unsigned>(value));\n  } else {\n    out[--n] = static_cast<Char>('0' + value);\n  }\n  return out + n;\n}\n\ntemplate <typename Char, typename UInt>\nFMT_CONSTEXPR FMT_INLINE auto format_decimal(Char* out, UInt value,\n                                             int num_digits) -> Char* {\n  do_format_decimal(out, value, num_digits);\n  return out + num_digits;\n}\n\ntemplate <typename Char, typename UInt, typename OutputIt,\n          FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<OutputIt>>::value)>\nFMT_CONSTEXPR auto format_decimal(OutputIt out, UInt value, int num_digits)\n    -> OutputIt {\n  if (auto ptr = to_pointer<Char>(out, to_unsigned(num_digits))) {\n    do_format_decimal(ptr, value, num_digits);\n    return out;\n  }\n  // Buffer is large enough to hold all digits (digits10 + 1).\n  char buffer[digits10<UInt>() + 1];\n  if (is_constant_evaluated()) fill_n(buffer, sizeof(buffer), '\\0');\n  do_format_decimal(buffer, value, num_digits);\n  return copy_noinline<Char>(buffer, buffer + num_digits, out);\n}\n\ntemplate <typename Char, typename UInt>\nFMT_CONSTEXPR auto do_format_base2e(int base_bits, Char* out, UInt value,\n                                    int size, bool upper = false) -> Char* {\n  out += size;\n  do {\n    const char* digits = upper ? \"0123456789ABCDEF\" : \"0123456789abcdef\";\n    unsigned digit = static_cast<unsigned>(value & ((1u << base_bits) - 1));\n    *--out = static_cast<Char>(base_bits < 4 ? static_cast<char>('0' + digit)\n                                             : digits[digit]);\n  } while ((value >>= base_bits) != 0);\n  return out;\n}\n\n// Formats an unsigned integer in the power of two base (binary, octal, hex).\ntemplate <typename Char, typename UInt>\nFMT_CONSTEXPR auto format_base2e(int base_bits, Char* out, UInt value,\n                                 int num_digits, bool upper = false) -> Char* {\n  do_format_base2e(base_bits, out, value, num_digits, upper);\n  return out + num_digits;\n}\n\ntemplate <typename Char, typename OutputIt, typename UInt,\n          FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value)>\nFMT_CONSTEXPR inline auto format_base2e(int base_bits, OutputIt out, UInt value,\n                                        int num_digits, bool upper = false)\n    -> OutputIt {\n  if (auto ptr = to_pointer<Char>(out, to_unsigned(num_digits))) {\n    format_base2e(base_bits, ptr, value, num_digits, upper);\n    return out;\n  }\n  // Make buffer large enough for any base.\n  char buffer[num_bits<UInt>()];\n  if (is_constant_evaluated()) fill_n(buffer, sizeof(buffer), '\\0');\n  format_base2e(base_bits, buffer, value, num_digits, upper);\n  return detail::copy_noinline<Char>(buffer, buffer + num_digits, out);\n}\n\n// A converter from UTF-8 to UTF-16.\nclass utf8_to_utf16 {\n private:\n  basic_memory_buffer<wchar_t> buffer_;\n\n public:\n  FMT_API explicit utf8_to_utf16(string_view s);\n  inline operator basic_string_view<wchar_t>() const {\n    return {&buffer_[0], size()};\n  }\n  inline auto size() const -> size_t { return buffer_.size() - 1; }\n  inline auto c_str() const -> const wchar_t* { return &buffer_[0]; }\n  inline auto str() const -> std::wstring { return {&buffer_[0], size()}; }\n};\n\nenum class to_utf8_error_policy { abort, replace };\n\n// A converter from UTF-16/UTF-32 (host endian) to UTF-8.\ntemplate <typename WChar, typename Buffer = memory_buffer> class to_utf8 {\n private:\n  Buffer buffer_;\n\n public:\n  to_utf8() {}\n  explicit to_utf8(basic_string_view<WChar> s,\n                   to_utf8_error_policy policy = to_utf8_error_policy::abort) {\n    static_assert(sizeof(WChar) == 2 || sizeof(WChar) == 4,\n                  \"expected utf16 or utf32\");\n    if (!convert(s, policy)) {\n      FMT_THROW(std::runtime_error(sizeof(WChar) == 2 ? \"invalid utf16\"\n                                                      : \"invalid utf32\"));\n    }\n  }\n  operator string_view() const { return string_view(&buffer_[0], size()); }\n  auto size() const -> size_t { return buffer_.size() - 1; }\n  auto c_str() const -> const char* { return &buffer_[0]; }\n  auto str() const -> std::string { return std::string(&buffer_[0], size()); }\n\n  // Performs conversion returning a bool instead of throwing exception on\n  // conversion error. This method may still throw in case of memory allocation\n  // error.\n  auto convert(basic_string_view<WChar> s,\n               to_utf8_error_policy policy = to_utf8_error_policy::abort)\n      -> bool {\n    if (!convert(buffer_, s, policy)) return false;\n    buffer_.push_back(0);\n    return true;\n  }\n  static auto convert(Buffer& buf, basic_string_view<WChar> s,\n                      to_utf8_error_policy policy = to_utf8_error_policy::abort)\n      -> bool {\n    for (auto p = s.begin(); p != s.end(); ++p) {\n      uint32_t c = static_cast<uint32_t>(*p);\n      if (sizeof(WChar) == 2 && c >= 0xd800 && c <= 0xdfff) {\n        // Handle a surrogate pair.\n        ++p;\n        if (p == s.end() || (c & 0xfc00) != 0xd800 || (*p & 0xfc00) != 0xdc00) {\n          if (policy == to_utf8_error_policy::abort) return false;\n          buf.append(string_view(\"\\xEF\\xBF\\xBD\"));\n          --p;\n          continue;\n        }\n        c = (c << 10) + static_cast<uint32_t>(*p) - 0x35fdc00;\n      }\n      if (c < 0x80) {\n        buf.push_back(static_cast<char>(c));\n      } else if (c < 0x800) {\n        buf.push_back(static_cast<char>(0xc0 | (c >> 6)));\n        buf.push_back(static_cast<char>(0x80 | (c & 0x3f)));\n      } else if ((c >= 0x800 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xffff)) {\n        buf.push_back(static_cast<char>(0xe0 | (c >> 12)));\n        buf.push_back(static_cast<char>(0x80 | ((c & 0xfff) >> 6)));\n        buf.push_back(static_cast<char>(0x80 | (c & 0x3f)));\n      } else if (c >= 0x10000 && c <= 0x10ffff) {\n        buf.push_back(static_cast<char>(0xf0 | (c >> 18)));\n        buf.push_back(static_cast<char>(0x80 | ((c & 0x3ffff) >> 12)));\n        buf.push_back(static_cast<char>(0x80 | ((c & 0xfff) >> 6)));\n        buf.push_back(static_cast<char>(0x80 | (c & 0x3f)));\n      } else {\n        return false;\n      }\n    }\n    return true;\n  }\n};\n\n// Computes 128-bit result of multiplication of two 64-bit unsigned integers.\nFMT_INLINE auto umul128(uint64_t x, uint64_t y) noexcept -> uint128_fallback {\n#if FMT_USE_INT128\n  auto p = static_cast<uint128_opt>(x) * static_cast<uint128_opt>(y);\n  return {static_cast<uint64_t>(p >> 64), static_cast<uint64_t>(p)};\n#elif defined(_MSC_VER) && defined(_M_X64)\n  auto hi = uint64_t();\n  auto lo = _umul128(x, y, &hi);\n  return {hi, lo};\n#else\n  const uint64_t mask = static_cast<uint64_t>(max_value<uint32_t>());\n\n  uint64_t a = x >> 32;\n  uint64_t b = x & mask;\n  uint64_t c = y >> 32;\n  uint64_t d = y & mask;\n\n  uint64_t ac = a * c;\n  uint64_t bc = b * c;\n  uint64_t ad = a * d;\n  uint64_t bd = b * d;\n\n  uint64_t intermediate = (bd >> 32) + (ad & mask) + (bc & mask);\n\n  return {ac + (intermediate >> 32) + (ad >> 32) + (bc >> 32),\n          (intermediate << 32) + (bd & mask)};\n#endif\n}\n\nnamespace dragonbox {\n// Computes floor(log10(pow(2, e))) for e in [-2620, 2620] using the method from\n// https://fmt.dev/papers/Dragonbox.pdf#page=28, section 6.1.\ninline auto floor_log10_pow2(int e) noexcept -> int {\n  FMT_ASSERT(e <= 2620 && e >= -2620, \"too large exponent\");\n  static_assert((-1 >> 1) == -1, \"right shift is not arithmetic\");\n  return (e * 315653) >> 20;\n}\n\ninline auto floor_log2_pow10(int e) noexcept -> int {\n  FMT_ASSERT(e <= 1233 && e >= -1233, \"too large exponent\");\n  return (e * 1741647) >> 19;\n}\n\n// Computes upper 64 bits of multiplication of two 64-bit unsigned integers.\ninline auto umul128_upper64(uint64_t x, uint64_t y) noexcept -> uint64_t {\n#if FMT_USE_INT128\n  auto p = static_cast<uint128_opt>(x) * static_cast<uint128_opt>(y);\n  return static_cast<uint64_t>(p >> 64);\n#elif defined(_MSC_VER) && defined(_M_X64)\n  return __umulh(x, y);\n#else\n  return umul128(x, y).high();\n#endif\n}\n\n// Computes upper 128 bits of multiplication of a 64-bit unsigned integer and a\n// 128-bit unsigned integer.\ninline auto umul192_upper128(uint64_t x, uint128_fallback y) noexcept\n    -> uint128_fallback {\n  uint128_fallback r = umul128(x, y.high());\n  r += umul128_upper64(x, y.low());\n  return r;\n}\n\nFMT_API auto get_cached_power(int k) noexcept -> uint128_fallback;\n\n// Type-specific information that Dragonbox uses.\ntemplate <typename T, typename Enable = void> struct float_info;\n\ntemplate <> struct float_info<float> {\n  using carrier_uint = uint32_t;\n  static const int exponent_bits = 8;\n  static const int kappa = 1;\n  static const int big_divisor = 100;\n  static const int small_divisor = 10;\n  static const int min_k = -31;\n  static const int max_k = 46;\n  static const int shorter_interval_tie_lower_threshold = -35;\n  static const int shorter_interval_tie_upper_threshold = -35;\n};\n\ntemplate <> struct float_info<double> {\n  using carrier_uint = uint64_t;\n  static const int exponent_bits = 11;\n  static const int kappa = 2;\n  static const int big_divisor = 1000;\n  static const int small_divisor = 100;\n  static const int min_k = -292;\n  static const int max_k = 341;\n  static const int shorter_interval_tie_lower_threshold = -77;\n  static const int shorter_interval_tie_upper_threshold = -77;\n};\n\n// An 80- or 128-bit floating point number.\ntemplate <typename T>\nstruct float_info<T, enable_if_t<std::numeric_limits<T>::digits == 64 ||\n                                 std::numeric_limits<T>::digits == 113 ||\n                                 is_float128<T>::value>> {\n  using carrier_uint = detail::uint128_t;\n  static const int exponent_bits = 15;\n};\n\n// A double-double floating point number.\ntemplate <typename T>\nstruct float_info<T, enable_if_t<is_double_double<T>::value>> {\n  using carrier_uint = detail::uint128_t;\n};\n\ntemplate <typename T> struct decimal_fp {\n  using significand_type = typename float_info<T>::carrier_uint;\n  significand_type significand;\n  int exponent;\n};\n\ntemplate <typename T> FMT_API auto to_decimal(T x) noexcept -> decimal_fp<T>;\n}  // namespace dragonbox\n\n// Returns true iff Float has the implicit bit which is not stored.\ntemplate <typename Float> constexpr auto has_implicit_bit() -> bool {\n  // An 80-bit FP number has a 64-bit significand an no implicit bit.\n  return std::numeric_limits<Float>::digits != 64;\n}\n\n// Returns the number of significand bits stored in Float. The implicit bit is\n// not counted since it is not stored.\ntemplate <typename Float> constexpr auto num_significand_bits() -> int {\n  // std::numeric_limits may not support __float128.\n  return is_float128<Float>() ? 112\n                              : (std::numeric_limits<Float>::digits -\n                                 (has_implicit_bit<Float>() ? 1 : 0));\n}\n\ntemplate <typename Float>\nconstexpr auto exponent_mask() ->\n    typename dragonbox::float_info<Float>::carrier_uint {\n  using float_uint = typename dragonbox::float_info<Float>::carrier_uint;\n  return ((float_uint(1) << dragonbox::float_info<Float>::exponent_bits) - 1)\n         << num_significand_bits<Float>();\n}\ntemplate <typename Float> constexpr auto exponent_bias() -> int {\n  // std::numeric_limits may not support __float128.\n  return is_float128<Float>() ? 16383\n                              : std::numeric_limits<Float>::max_exponent - 1;\n}\n\nFMT_CONSTEXPR inline auto compute_exp_size(int exp) -> int {\n  auto prefix_size = 2;  // sign + 'e'\n  auto abs_exp = exp >= 0 ? exp : -exp;\n  if (abs_exp < 100) return prefix_size + 2;\n  return prefix_size + (abs_exp >= 1000 ? 4 : 3);\n}\n\n// Writes the exponent exp in the form \"[+-]d{2,3}\" to buffer.\ntemplate <typename Char, typename OutputIt>\nFMT_CONSTEXPR auto write_exponent(int exp, OutputIt out) -> OutputIt {\n  FMT_ASSERT(-10000 < exp && exp < 10000, \"exponent out of range\");\n  if (exp < 0) {\n    *out++ = static_cast<Char>('-');\n    exp = -exp;\n  } else {\n    *out++ = static_cast<Char>('+');\n  }\n  auto uexp = static_cast<uint32_t>(exp);\n  if (is_constant_evaluated()) {\n    if (uexp < 10) *out++ = '0';\n    return format_decimal<Char>(out, uexp, count_digits(uexp));\n  }\n  if (uexp >= 100u) {\n    const char* top = digits2(uexp / 100);\n    if (uexp >= 1000u) *out++ = static_cast<Char>(top[0]);\n    *out++ = static_cast<Char>(top[1]);\n    uexp %= 100;\n  }\n  const char* d = digits2(uexp);\n  *out++ = static_cast<Char>(d[0]);\n  *out++ = static_cast<Char>(d[1]);\n  return out;\n}\n\n// A floating-point number f * pow(2, e) where F is an unsigned type.\ntemplate <typename F> struct basic_fp {\n  F f;\n  int e;\n\n  static constexpr int num_significand_bits =\n      static_cast<int>(sizeof(F) * num_bits<unsigned char>());\n\n  constexpr basic_fp() : f(0), e(0) {}\n  constexpr basic_fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {}\n\n  // Constructs fp from an IEEE754 floating-point number.\n  template <typename Float> FMT_CONSTEXPR basic_fp(Float n) { assign(n); }\n\n  // Assigns n to this and return true iff predecessor is closer than successor.\n  template <typename Float, FMT_ENABLE_IF(!is_double_double<Float>::value)>\n  FMT_CONSTEXPR auto assign(Float n) -> bool {\n    static_assert(std::numeric_limits<Float>::digits <= 113, \"unsupported FP\");\n    // Assume Float is in the format [sign][exponent][significand].\n    using carrier_uint = typename dragonbox::float_info<Float>::carrier_uint;\n    const auto num_float_significand_bits =\n        detail::num_significand_bits<Float>();\n    const auto implicit_bit = carrier_uint(1) << num_float_significand_bits;\n    const auto significand_mask = implicit_bit - 1;\n    auto u = bit_cast<carrier_uint>(n);\n    f = static_cast<F>(u & significand_mask);\n    auto biased_e = static_cast<int>((u & exponent_mask<Float>()) >>\n                                     num_float_significand_bits);\n    // The predecessor is closer if n is a normalized power of 2 (f == 0)\n    // other than the smallest normalized number (biased_e > 1).\n    auto is_predecessor_closer = f == 0 && biased_e > 1;\n    if (biased_e == 0)\n      biased_e = 1;  // Subnormals use biased exponent 1 (min exponent).\n    else if (has_implicit_bit<Float>())\n      f += static_cast<F>(implicit_bit);\n    e = biased_e - exponent_bias<Float>() - num_float_significand_bits;\n    if (!has_implicit_bit<Float>()) ++e;\n    return is_predecessor_closer;\n  }\n\n  template <typename Float, FMT_ENABLE_IF(is_double_double<Float>::value)>\n  FMT_CONSTEXPR auto assign(Float n) -> bool {\n    static_assert(std::numeric_limits<double>::is_iec559, \"unsupported FP\");\n    return assign(static_cast<double>(n));\n  }\n};\n\nusing fp = basic_fp<unsigned long long>;\n\n// Normalizes the value converted from double and multiplied by (1 << SHIFT).\ntemplate <int SHIFT = 0, typename F>\nFMT_CONSTEXPR auto normalize(basic_fp<F> value) -> basic_fp<F> {\n  // Handle subnormals.\n  const auto implicit_bit = F(1) << num_significand_bits<double>();\n  const auto shifted_implicit_bit = implicit_bit << SHIFT;\n  while ((value.f & shifted_implicit_bit) == 0) {\n    value.f <<= 1;\n    --value.e;\n  }\n  // Subtract 1 to account for hidden bit.\n  const auto offset = basic_fp<F>::num_significand_bits -\n                      num_significand_bits<double>() - SHIFT - 1;\n  value.f <<= offset;\n  value.e -= offset;\n  return value;\n}\n\n// Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking.\nFMT_CONSTEXPR inline auto multiply(uint64_t lhs, uint64_t rhs) -> uint64_t {\n#if FMT_USE_INT128\n  auto product = static_cast<__uint128_t>(lhs) * rhs;\n  auto f = static_cast<uint64_t>(product >> 64);\n  return (static_cast<uint64_t>(product) & (1ULL << 63)) != 0 ? f + 1 : f;\n#else\n  // Multiply 32-bit parts of significands.\n  uint64_t mask = (1ULL << 32) - 1;\n  uint64_t a = lhs >> 32, b = lhs & mask;\n  uint64_t c = rhs >> 32, d = rhs & mask;\n  uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d;\n  // Compute mid 64-bit of result and round.\n  uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31);\n  return ac + (ad >> 32) + (bc >> 32) + (mid >> 32);\n#endif\n}\n\nFMT_CONSTEXPR inline auto operator*(fp x, fp y) -> fp {\n  return {multiply(x.f, y.f), x.e + y.e + 64};\n}\n\ntemplate <typename T, bool doublish = num_bits<T>() == num_bits<double>()>\nusing convert_float_result =\n    conditional_t<std::is_same<T, float>::value || doublish, double, T>;\n\ntemplate <typename T>\nconstexpr auto convert_float(T value) -> convert_float_result<T> {\n  return static_cast<convert_float_result<T>>(value);\n}\n\ntemplate <bool C, typename T, typename F, FMT_ENABLE_IF(C)>\nauto select(T true_value, F) -> T {\n  return true_value;\n}\ntemplate <bool C, typename T, typename F, FMT_ENABLE_IF(!C)>\nauto select(T, F false_value) -> F {\n  return false_value;\n}\n\ntemplate <typename Char, typename OutputIt>\nFMT_CONSTEXPR FMT_NOINLINE auto fill(OutputIt it, size_t n,\n                                     const basic_specs& specs) -> OutputIt {\n  auto fill_size = specs.fill_size();\n  if (fill_size == 1) return detail::fill_n(it, n, specs.fill_unit<Char>());\n  if (const Char* data = specs.fill<Char>()) {\n    for (size_t i = 0; i < n; ++i) it = copy<Char>(data, data + fill_size, it);\n  }\n  return it;\n}\n\n// Writes the output of f, padded according to format specifications in specs.\n// size: output size in code units.\n// width: output display width in (terminal) column positions.\ntemplate <typename Char, align default_align = align::left, typename OutputIt,\n          typename F>\nFMT_CONSTEXPR auto write_padded(OutputIt out, const format_specs& specs,\n                                size_t size, size_t width, F&& f) -> OutputIt {\n  static_assert(default_align == align::left || default_align == align::right,\n                \"\");\n  unsigned spec_width = to_unsigned(specs.width);\n  size_t padding = spec_width > width ? spec_width - width : 0;\n  // Shifts are encoded as string literals because static constexpr is not\n  // supported in constexpr functions.\n  auto* shifts =\n      default_align == align::left ? \"\\x1f\\x1f\\x00\\x01\" : \"\\x00\\x1f\\x00\\x01\";\n  size_t left_padding = padding >> shifts[static_cast<int>(specs.align())];\n  size_t right_padding = padding - left_padding;\n  auto it = reserve(out, size + padding * specs.fill_size());\n  if (left_padding != 0) it = fill<Char>(it, left_padding, specs);\n  it = f(it);\n  if (right_padding != 0) it = fill<Char>(it, right_padding, specs);\n  return base_iterator(out, it);\n}\n\ntemplate <typename Char, align default_align = align::left, typename OutputIt,\n          typename F>\nconstexpr auto write_padded(OutputIt out, const format_specs& specs,\n                            size_t size, F&& f) -> OutputIt {\n  return write_padded<Char, default_align>(out, specs, size, size, f);\n}\n\ntemplate <typename Char, align default_align = align::left, typename OutputIt>\nFMT_CONSTEXPR auto write_bytes(OutputIt out, string_view bytes,\n                               const format_specs& specs = {}) -> OutputIt {\n  return write_padded<Char, default_align>(\n      out, specs, bytes.size(), [bytes](reserve_iterator<OutputIt> it) {\n        const char* data = bytes.data();\n        return copy<Char>(data, data + bytes.size(), it);\n      });\n}\n\ntemplate <typename Char, typename OutputIt, typename UIntPtr>\nauto write_ptr(OutputIt out, UIntPtr value, const format_specs* specs)\n    -> OutputIt {\n  int num_digits = count_digits<4>(value);\n  auto size = to_unsigned(num_digits) + size_t(2);\n  auto write = [=](reserve_iterator<OutputIt> it) {\n    *it++ = static_cast<Char>('0');\n    *it++ = static_cast<Char>('x');\n    return format_base2e<Char>(4, it, value, num_digits);\n  };\n  return specs ? write_padded<Char, align::right>(out, *specs, size, write)\n               : base_iterator(out, write(reserve(out, size)));\n}\n\n// Returns true iff the code point cp is printable.\nFMT_API auto is_printable(uint32_t cp) -> bool;\n\ninline auto needs_escape(uint32_t cp) -> bool {\n  if (cp < 0x20 || cp == 0x7f || cp == '\"' || cp == '\\\\') return true;\n  if (const_check(FMT_OPTIMIZE_SIZE > 1)) return false;\n  return !is_printable(cp);\n}\n\ntemplate <typename Char> struct find_escape_result {\n  const Char* begin;\n  const Char* end;\n  uint32_t cp;\n};\n\ntemplate <typename Char>\nauto find_escape(const Char* begin, const Char* end)\n    -> find_escape_result<Char> {\n  for (; begin != end; ++begin) {\n    uint32_t cp = static_cast<unsigned_char<Char>>(*begin);\n    if (const_check(sizeof(Char) == 1) && cp >= 0x80) continue;\n    if (needs_escape(cp)) return {begin, begin + 1, cp};\n  }\n  return {begin, nullptr, 0};\n}\n\ninline auto find_escape(const char* begin, const char* end)\n    -> find_escape_result<char> {\n  if (const_check(!use_utf8)) return find_escape<char>(begin, end);\n  auto result = find_escape_result<char>{end, nullptr, 0};\n  for_each_codepoint(string_view(begin, to_unsigned(end - begin)),\n                     [&](uint32_t cp, string_view sv) {\n                       if (needs_escape(cp)) {\n                         result = {sv.begin(), sv.end(), cp};\n                         return false;\n                       }\n                       return true;\n                     });\n  return result;\n}\n\ntemplate <size_t width, typename Char, typename OutputIt>\nauto write_codepoint(OutputIt out, char prefix, uint32_t cp) -> OutputIt {\n  *out++ = static_cast<Char>('\\\\');\n  *out++ = static_cast<Char>(prefix);\n  Char buf[width];\n  fill_n(buf, width, static_cast<Char>('0'));\n  format_base2e(4, buf, cp, width);\n  return copy<Char>(buf, buf + width, out);\n}\n\ntemplate <typename OutputIt, typename Char>\nauto write_escaped_cp(OutputIt out, const find_escape_result<Char>& escape)\n    -> OutputIt {\n  auto c = static_cast<Char>(escape.cp);\n  switch (escape.cp) {\n  case '\\n':\n    *out++ = static_cast<Char>('\\\\');\n    c = static_cast<Char>('n');\n    break;\n  case '\\r':\n    *out++ = static_cast<Char>('\\\\');\n    c = static_cast<Char>('r');\n    break;\n  case '\\t':\n    *out++ = static_cast<Char>('\\\\');\n    c = static_cast<Char>('t');\n    break;\n  case '\"':  FMT_FALLTHROUGH;\n  case '\\'': FMT_FALLTHROUGH;\n  case '\\\\': *out++ = static_cast<Char>('\\\\'); break;\n  default:\n    if (escape.cp < 0x100) return write_codepoint<2, Char>(out, 'x', escape.cp);\n    if (escape.cp < 0x10000)\n      return write_codepoint<4, Char>(out, 'u', escape.cp);\n    if (escape.cp < 0x110000)\n      return write_codepoint<8, Char>(out, 'U', escape.cp);\n    for (Char escape_char : basic_string_view<Char>(\n             escape.begin, to_unsigned(escape.end - escape.begin))) {\n      out = write_codepoint<2, Char>(out, 'x',\n                                     static_cast<uint32_t>(escape_char) & 0xFF);\n    }\n    return out;\n  }\n  *out++ = c;\n  return out;\n}\n\ntemplate <typename Char, typename OutputIt>\nauto write_escaped_string(OutputIt out, basic_string_view<Char> str)\n    -> OutputIt {\n  *out++ = static_cast<Char>('\"');\n  auto begin = str.begin(), end = str.end();\n  do {\n    auto escape = find_escape(begin, end);\n    out = copy<Char>(begin, escape.begin, out);\n    begin = escape.end;\n    if (!begin) break;\n    out = write_escaped_cp<OutputIt, Char>(out, escape);\n  } while (begin != end);\n  *out++ = static_cast<Char>('\"');\n  return out;\n}\n\ntemplate <typename Char, typename OutputIt>\nauto write_escaped_char(OutputIt out, Char v) -> OutputIt {\n  Char v_array[1] = {v};\n  *out++ = static_cast<Char>('\\'');\n  if ((needs_escape(static_cast<uint32_t>(v)) && v != static_cast<Char>('\"')) ||\n      v == static_cast<Char>('\\'')) {\n    out = write_escaped_cp(out,\n                           find_escape_result<Char>{v_array, v_array + 1,\n                                                    static_cast<uint32_t>(v)});\n  } else {\n    *out++ = v;\n  }\n  *out++ = static_cast<Char>('\\'');\n  return out;\n}\n\ntemplate <typename Char, typename OutputIt>\nFMT_CONSTEXPR auto write_char(OutputIt out, Char value,\n                              const format_specs& specs) -> OutputIt {\n  bool is_debug = specs.type() == presentation_type::debug;\n  return write_padded<Char>(out, specs, 1, [=](reserve_iterator<OutputIt> it) {\n    if (is_debug) return write_escaped_char(it, value);\n    *it++ = value;\n    return it;\n  });\n}\n\ntemplate <typename Char> class digit_grouping {\n private:\n  std::string grouping_;\n  std::basic_string<Char> thousands_sep_;\n\n  struct next_state {\n    std::string::const_iterator group;\n    int pos;\n  };\n  auto initial_state() const -> next_state { return {grouping_.begin(), 0}; }\n\n  // Returns the next digit group separator position.\n  auto next(next_state& state) const -> int {\n    if (thousands_sep_.empty()) return max_value<int>();\n    if (state.group == grouping_.end()) return state.pos += grouping_.back();\n    if (*state.group <= 0 || *state.group == max_value<char>())\n      return max_value<int>();\n    state.pos += *state.group++;\n    return state.pos;\n  }\n\n public:\n  explicit digit_grouping(locale_ref loc, bool localized = true) {\n    if (!localized) return;\n    auto sep = thousands_sep<Char>(loc);\n    grouping_ = sep.grouping;\n    if (sep.thousands_sep) thousands_sep_.assign(1, sep.thousands_sep);\n  }\n  digit_grouping(std::string grouping, std::basic_string<Char> sep)\n      : grouping_(std::move(grouping)), thousands_sep_(std::move(sep)) {}\n\n  auto has_separator() const -> bool { return !thousands_sep_.empty(); }\n\n  auto count_separators(int num_digits) const -> int {\n    int count = 0;\n    auto state = initial_state();\n    while (num_digits > next(state)) ++count;\n    return count;\n  }\n\n  // Applies grouping to digits and writes the output to out.\n  template <typename Out, typename C>\n  auto apply(Out out, basic_string_view<C> digits) const -> Out {\n    auto num_digits = static_cast<int>(digits.size());\n    auto separators = basic_memory_buffer<int>();\n    separators.push_back(0);\n    auto state = initial_state();\n    while (int i = next(state)) {\n      if (i >= num_digits) break;\n      separators.push_back(i);\n    }\n    for (int i = 0, sep_index = static_cast<int>(separators.size() - 1);\n         i < num_digits; ++i) {\n      if (num_digits - i == separators[sep_index]) {\n        out = copy<Char>(thousands_sep_.data(),\n                         thousands_sep_.data() + thousands_sep_.size(), out);\n        --sep_index;\n      }\n      *out++ = static_cast<Char>(digits[to_unsigned(i)]);\n    }\n    return out;\n  }\n};\n\nFMT_CONSTEXPR inline void prefix_append(unsigned& prefix, unsigned value) {\n  prefix |= prefix != 0 ? value << 8 : value;\n  prefix += (1u + (value > 0xff ? 1 : 0)) << 24;\n}\n\n// Writes a decimal integer with digit grouping.\ntemplate <typename OutputIt, typename UInt, typename Char>\nauto write_int(OutputIt out, UInt value, unsigned prefix,\n               const format_specs& specs, const digit_grouping<Char>& grouping)\n    -> OutputIt {\n  static_assert(std::is_same<uint64_or_128_t<UInt>, UInt>::value, \"\");\n  int num_digits = 0;\n  auto buffer = memory_buffer();\n  switch (specs.type()) {\n  default: FMT_ASSERT(false, \"\"); FMT_FALLTHROUGH;\n  case presentation_type::none:\n  case presentation_type::dec:\n    num_digits = count_digits(value);\n    format_decimal<char>(appender(buffer), value, num_digits);\n    break;\n  case presentation_type::hex:\n    if (specs.alt())\n      prefix_append(prefix, unsigned(specs.upper() ? 'X' : 'x') << 8 | '0');\n    num_digits = count_digits<4>(value);\n    format_base2e<char>(4, appender(buffer), value, num_digits, specs.upper());\n    break;\n  case presentation_type::oct:\n    num_digits = count_digits<3>(value);\n    // Octal prefix '0' is counted as a digit, so only add it if precision\n    // is not greater than the number of digits.\n    if (specs.alt() && specs.precision <= num_digits && value != 0)\n      prefix_append(prefix, '0');\n    format_base2e<char>(3, appender(buffer), value, num_digits);\n    break;\n  case presentation_type::bin:\n    if (specs.alt())\n      prefix_append(prefix, unsigned(specs.upper() ? 'B' : 'b') << 8 | '0');\n    num_digits = count_digits<1>(value);\n    format_base2e<char>(1, appender(buffer), value, num_digits);\n    break;\n  case presentation_type::chr:\n    return write_char<Char>(out, static_cast<Char>(value), specs);\n  }\n\n  unsigned size = (prefix != 0 ? prefix >> 24 : 0) + to_unsigned(num_digits) +\n                  to_unsigned(grouping.count_separators(num_digits));\n  return write_padded<Char, align::right>(\n      out, specs, size, size, [&](reserve_iterator<OutputIt> it) {\n        for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)\n          *it++ = static_cast<Char>(p & 0xff);\n        return grouping.apply(it, string_view(buffer.data(), buffer.size()));\n      });\n}\n\n#if FMT_USE_LOCALE\n// Writes a localized value.\nFMT_API auto write_loc(appender out, loc_value value, const format_specs& specs,\n                       locale_ref loc) -> bool;\nauto write_loc(basic_appender<wchar_t> out, loc_value value,\n               const format_specs& specs, locale_ref loc) -> bool;\n#endif\ntemplate <typename OutputIt>\ninline auto write_loc(OutputIt, const loc_value&, const format_specs&,\n                      locale_ref) -> bool {\n  return false;\n}\n\ntemplate <typename UInt> struct write_int_arg {\n  UInt abs_value;\n  unsigned prefix;\n};\n\ntemplate <typename T>\nFMT_CONSTEXPR auto make_write_int_arg(T value, sign s)\n    -> write_int_arg<uint32_or_64_or_128_t<T>> {\n  auto prefix = 0u;\n  auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);\n  if (is_negative(value)) {\n    prefix = 0x01000000 | '-';\n    abs_value = 0 - abs_value;\n  } else {\n    constexpr unsigned prefixes[4] = {0, 0, 0x1000000u | '+', 0x1000000u | ' '};\n    prefix = prefixes[static_cast<int>(s)];\n  }\n  return {abs_value, prefix};\n}\n\ntemplate <typename Char = char> struct loc_writer {\n  basic_appender<Char> out;\n  const format_specs& specs;\n  std::basic_string<Char> sep;\n  std::string grouping;\n  std::basic_string<Char> decimal_point;\n\n  template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>\n  auto operator()(T value) -> bool {\n    auto arg = make_write_int_arg(value, specs.sign());\n    write_int(out, static_cast<uint64_or_128_t<T>>(arg.abs_value), arg.prefix,\n              specs, digit_grouping<Char>(grouping, sep));\n    return true;\n  }\n\n  template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>\n  auto operator()(T) -> bool {\n    return false;\n  }\n};\n\n// Size and padding computation separate from write_int to avoid template bloat.\nstruct size_padding {\n  unsigned size;\n  unsigned padding;\n\n  FMT_CONSTEXPR size_padding(int num_digits, unsigned prefix,\n                             const format_specs& specs)\n      : size((prefix >> 24) + to_unsigned(num_digits)), padding(0) {\n    if (specs.align() == align::numeric) {\n      auto width = to_unsigned(specs.width);\n      if (width > size) {\n        padding = width - size;\n        size = width;\n      }\n    } else if (specs.precision > num_digits) {\n      size = (prefix >> 24) + to_unsigned(specs.precision);\n      padding = to_unsigned(specs.precision - num_digits);\n    }\n  }\n};\n\ntemplate <typename Char, typename OutputIt, typename T>\nFMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, write_int_arg<T> arg,\n                                        const format_specs& specs) -> OutputIt {\n  static_assert(std::is_same<T, uint32_or_64_or_128_t<T>>::value, \"\");\n\n  constexpr size_t buffer_size = num_bits<T>();\n  char buffer[buffer_size];\n  if (is_constant_evaluated()) fill_n(buffer, buffer_size, '\\0');\n  const char* begin = nullptr;\n  const char* end = buffer + buffer_size;\n\n  auto abs_value = arg.abs_value;\n  auto prefix = arg.prefix;\n  switch (specs.type()) {\n  default: FMT_ASSERT(false, \"\"); FMT_FALLTHROUGH;\n  case presentation_type::none:\n  case presentation_type::dec:\n    begin = do_format_decimal(buffer, abs_value, buffer_size);\n    break;\n  case presentation_type::hex:\n    begin = do_format_base2e(4, buffer, abs_value, buffer_size, specs.upper());\n    if (specs.alt())\n      prefix_append(prefix, unsigned(specs.upper() ? 'X' : 'x') << 8 | '0');\n    break;\n  case presentation_type::oct: {\n    begin = do_format_base2e(3, buffer, abs_value, buffer_size);\n    // Octal prefix '0' is counted as a digit, so only add it if precision\n    // is not greater than the number of digits.\n    auto num_digits = end - begin;\n    if (specs.alt() && specs.precision <= num_digits && abs_value != 0)\n      prefix_append(prefix, '0');\n    break;\n  }\n  case presentation_type::bin:\n    begin = do_format_base2e(1, buffer, abs_value, buffer_size);\n    if (specs.alt())\n      prefix_append(prefix, unsigned(specs.upper() ? 'B' : 'b') << 8 | '0');\n    break;\n  case presentation_type::chr:\n    return write_char<Char>(out, static_cast<Char>(abs_value), specs);\n  }\n\n  // Write an integer in the format\n  //   <left-padding><prefix><numeric-padding><digits><right-padding>\n  // prefix contains chars in three lower bytes and the size in the fourth byte.\n  int num_digits = static_cast<int>(end - begin);\n  // Slightly faster check for specs.width == 0 && specs.precision == -1.\n  if ((specs.width | (specs.precision + 1)) == 0) {\n    auto it = reserve(out, to_unsigned(num_digits) + (prefix >> 24));\n    for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)\n      *it++ = static_cast<Char>(p & 0xff);\n    return base_iterator(out, copy<Char>(begin, end, it));\n  }\n  auto sp = size_padding(num_digits, prefix, specs);\n  unsigned padding = sp.padding;\n  return write_padded<Char, align::right>(\n      out, specs, sp.size, [=](reserve_iterator<OutputIt> it) {\n        for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)\n          *it++ = static_cast<Char>(p & 0xff);\n        it = detail::fill_n(it, padding, static_cast<Char>('0'));\n        return copy<Char>(begin, end, it);\n      });\n}\n\ntemplate <typename Char, typename OutputIt, typename T>\nFMT_CONSTEXPR FMT_NOINLINE auto write_int_noinline(OutputIt out,\n                                                   write_int_arg<T> arg,\n                                                   const format_specs& specs)\n    -> OutputIt {\n  return write_int<Char>(out, arg, specs);\n}\n\ntemplate <typename Char, typename T,\n          FMT_ENABLE_IF(is_integral<T>::value &&\n                        !std::is_same<T, bool>::value &&\n                        !std::is_same<T, Char>::value)>\nFMT_CONSTEXPR FMT_INLINE auto write(basic_appender<Char> out, T value,\n                                    const format_specs& specs, locale_ref loc)\n    -> basic_appender<Char> {\n  if (specs.localized() && write_loc(out, value, specs, loc)) return out;\n  return write_int_noinline<Char>(out, make_write_int_arg(value, specs.sign()),\n                                  specs);\n}\n\n// An inlined version of write used in format string compilation.\ntemplate <typename Char, typename OutputIt, typename T,\n          FMT_ENABLE_IF(is_integral<T>::value &&\n                        !std::is_same<T, bool>::value &&\n                        !std::is_same<T, Char>::value &&\n                        !std::is_same<OutputIt, basic_appender<Char>>::value)>\nFMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value,\n                                    const format_specs& specs, locale_ref loc)\n    -> OutputIt {\n  if (specs.localized() && write_loc(out, value, specs, loc)) return out;\n  return write_int<Char>(out, make_write_int_arg(value, specs.sign()), specs);\n}\n\ntemplate <typename Char, typename OutputIt>\nFMT_CONSTEXPR auto write(OutputIt out, Char value, const format_specs& specs,\n                         locale_ref loc = {}) -> OutputIt {\n  // char is formatted as unsigned char for consistency across platforms.\n  using unsigned_type =\n      conditional_t<std::is_same<Char, char>::value, unsigned char, unsigned>;\n  return check_char_specs(specs)\n             ? write_char<Char>(out, value, specs)\n             : write<Char>(out, static_cast<unsigned_type>(value), specs, loc);\n}\n\ntemplate <typename Char, typename OutputIt,\n          FMT_ENABLE_IF(std::is_same<Char, char>::value)>\nFMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,\n                         const format_specs& specs) -> OutputIt {\n  bool is_debug = specs.type() == presentation_type::debug;\n  if (specs.precision < 0 && specs.width == 0) {\n    auto&& it = reserve(out, s.size());\n    return is_debug ? write_escaped_string(it, s) : copy<char>(s, it);\n  }\n\n  size_t display_width_limit =\n      specs.precision < 0 ? SIZE_MAX : to_unsigned(specs.precision);\n  size_t display_width =\n      !is_debug || specs.precision == 0 ? 0 : 1;  // Account for opening '\"'.\n  size_t size = !is_debug || specs.precision == 0 ? 0 : 1;\n  for_each_codepoint(s, [&](uint32_t cp, string_view sv) {\n    if (is_debug && needs_escape(cp)) {\n      counting_buffer<char> buf;\n      write_escaped_cp(basic_appender<char>(buf),\n                       find_escape_result<char>{sv.begin(), sv.end(), cp});\n      // We're reinterpreting bytes as display width. That's okay\n      // because write_escaped_cp() only writes ASCII characters.\n      size_t cp_width = buf.count();\n      if (display_width + cp_width <= display_width_limit) {\n        display_width += cp_width;\n        size += cp_width;\n        // If this is the end of the string, account for closing '\"'.\n        if (display_width < display_width_limit && sv.end() == s.end()) {\n          ++display_width;\n          ++size;\n        }\n        return true;\n      }\n\n      size += display_width_limit - display_width;\n      display_width = display_width_limit;\n      return false;\n    }\n\n    size_t cp_width = display_width_of(cp);\n    if (cp_width + display_width <= display_width_limit) {\n      display_width += cp_width;\n      size += sv.size();\n      // If this is the end of the string, account for closing '\"'.\n      if (is_debug && display_width < display_width_limit &&\n          sv.end() == s.end()) {\n        ++display_width;\n        ++size;\n      }\n      return true;\n    }\n\n    return false;\n  });\n\n  struct bounded_output_iterator {\n    reserve_iterator<OutputIt> underlying_iterator;\n    size_t bound;\n\n    FMT_CONSTEXPR auto operator*() -> bounded_output_iterator& { return *this; }\n    FMT_CONSTEXPR auto operator++() -> bounded_output_iterator& {\n      return *this;\n    }\n    FMT_CONSTEXPR auto operator++(int) -> bounded_output_iterator& {\n      return *this;\n    }\n    FMT_CONSTEXPR auto operator=(char c) -> bounded_output_iterator& {\n      if (bound > 0) {\n        *underlying_iterator++ = c;\n        --bound;\n      }\n      return *this;\n    }\n  };\n\n  return write_padded<char>(\n      out, specs, size, display_width, [=](reserve_iterator<OutputIt> it) {\n        return is_debug\n                   ? write_escaped_string(bounded_output_iterator{it, size}, s)\n                         .underlying_iterator\n                   : copy<char>(s.data(), s.data() + size, it);\n      });\n}\n\ntemplate <typename Char, typename OutputIt,\n          FMT_ENABLE_IF(!std::is_same<Char, char>::value)>\nFMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,\n                         const format_specs& specs) -> OutputIt {\n  auto data = s.data();\n  auto size = s.size();\n  if (specs.precision >= 0 && to_unsigned(specs.precision) < size)\n    size = to_unsigned(specs.precision);\n\n  bool is_debug = specs.type() == presentation_type::debug;\n  if (is_debug) {\n    auto buf = counting_buffer<Char>();\n    write_escaped_string(basic_appender<Char>(buf), s);\n    size = buf.count();\n  }\n\n  return write_padded<Char>(\n      out, specs, size, [=](reserve_iterator<OutputIt> it) {\n        return is_debug ? write_escaped_string(it, s)\n                        : copy<Char>(data, data + size, it);\n      });\n}\n\ntemplate <typename Char, typename OutputIt>\nFMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,\n                         const format_specs& specs, locale_ref) -> OutputIt {\n  return write<Char>(out, s, specs);\n}\n\ntemplate <typename Char, typename OutputIt>\nFMT_CONSTEXPR auto write(OutputIt out, const Char* s, const format_specs& specs,\n                         locale_ref) -> OutputIt {\n  if (specs.type() == presentation_type::pointer)\n    return write_ptr<Char>(out, bit_cast<uintptr_t>(s), &specs);\n  if (!s) report_error(\"string pointer is null\");\n  return write<Char>(out, basic_string_view<Char>(s), specs, {});\n}\n\ntemplate <typename Char, typename OutputIt, typename T,\n          FMT_ENABLE_IF(is_integral<T>::value &&\n                        !std::is_same<T, bool>::value &&\n                        !std::is_same<T, Char>::value)>\nFMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {\n  auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);\n  bool negative = is_negative(value);\n  // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer.\n  if (negative) abs_value = ~abs_value + 1;\n  int num_digits = count_digits(abs_value);\n  auto size = (negative ? 1 : 0) + static_cast<size_t>(num_digits);\n  if (auto ptr = to_pointer<Char>(out, size)) {\n    if (negative) *ptr++ = static_cast<Char>('-');\n    format_decimal<Char>(ptr, abs_value, num_digits);\n    return out;\n  }\n  if (negative) *out++ = static_cast<Char>('-');\n  return format_decimal<Char>(out, abs_value, num_digits);\n}\n\ntemplate <typename Char>\nFMT_CONSTEXPR auto parse_align(const Char* begin, const Char* end,\n                               format_specs& specs) -> const Char* {\n  FMT_ASSERT(begin != end, \"\");\n  auto alignment = align::none;\n  auto p = begin + code_point_length(begin);\n  if (end - p <= 0) p = begin;\n  for (;;) {\n    switch (to_ascii(*p)) {\n    case '<': alignment = align::left; break;\n    case '>': alignment = align::right; break;\n    case '^': alignment = align::center; break;\n    }\n    if (alignment != align::none) {\n      if (p != begin) {\n        auto c = *begin;\n        if (c == '}') return begin;\n        if (c == '{') {\n          report_error(\"invalid fill character '{'\");\n          return begin;\n        }\n        specs.set_fill(basic_string_view<Char>(begin, to_unsigned(p - begin)));\n        begin = p + 1;\n      } else {\n        ++begin;\n      }\n      break;\n    } else if (p == begin) {\n      break;\n    }\n    p = begin;\n  }\n  specs.set_align(alignment);\n  return begin;\n}\n\ntemplate <typename Char, typename OutputIt>\nFMT_CONSTEXPR20 auto write_nonfinite(OutputIt out, bool isnan,\n                                     format_specs specs, sign s) -> OutputIt {\n  auto str =\n      isnan ? (specs.upper() ? \"NAN\" : \"nan\") : (specs.upper() ? \"INF\" : \"inf\");\n  constexpr size_t str_size = 3;\n  auto size = str_size + (s != sign::none ? 1 : 0);\n  // Replace '0'-padding with space for non-finite values.\n  const bool is_zero_fill =\n      specs.fill_size() == 1 && specs.fill_unit<Char>() == '0';\n  if (is_zero_fill) specs.set_fill(' ');\n  return write_padded<Char>(out, specs, size,\n                            [=](reserve_iterator<OutputIt> it) {\n                              if (s != sign::none)\n                                *it++ = detail::getsign<Char>(s);\n                              return copy<Char>(str, str + str_size, it);\n                            });\n}\n\n// A decimal floating-point number significand * pow(10, exp).\nstruct big_decimal_fp {\n  const char* significand;\n  int significand_size;\n  int exponent;\n};\n\nconstexpr auto get_significand_size(const big_decimal_fp& f) -> int {\n  return f.significand_size;\n}\ntemplate <typename T>\ninline auto get_significand_size(const dragonbox::decimal_fp<T>& f) -> int {\n  return count_digits(f.significand);\n}\n\ntemplate <typename Char, typename OutputIt>\nconstexpr auto write_significand(OutputIt out, const char* significand,\n                                 int significand_size) -> OutputIt {\n  return copy<Char>(significand, significand + significand_size, out);\n}\ntemplate <typename Char, typename OutputIt, typename UInt>\ninline auto write_significand(OutputIt out, UInt significand,\n                              int significand_size) -> OutputIt {\n  return format_decimal<Char>(out, significand, significand_size);\n}\ntemplate <typename Char, typename OutputIt, typename T, typename Grouping>\nFMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,\n                                       int significand_size, int exponent,\n                                       const Grouping& grouping) -> OutputIt {\n  if (!grouping.has_separator()) {\n    out = write_significand<Char>(out, significand, significand_size);\n    return detail::fill_n(out, exponent, static_cast<Char>('0'));\n  }\n  auto buffer = memory_buffer();\n  write_significand<char>(appender(buffer), significand, significand_size);\n  detail::fill_n(appender(buffer), exponent, '0');\n  return grouping.apply(out, string_view(buffer.data(), buffer.size()));\n}\n\ntemplate <typename Char, typename UInt,\n          FMT_ENABLE_IF(std::is_integral<UInt>::value)>\ninline auto write_significand(Char* out, UInt significand, int significand_size,\n                              int integral_size, Char decimal_point) -> Char* {\n  if (!decimal_point) return format_decimal(out, significand, significand_size);\n  out += significand_size + 1;\n  Char* end = out;\n  int floating_size = significand_size - integral_size;\n  for (int i = floating_size / 2; i > 0; --i) {\n    out -= 2;\n    write2digits(out, static_cast<size_t>(significand % 100));\n    significand /= 100;\n  }\n  if (floating_size % 2 != 0) {\n    *--out = static_cast<Char>('0' + significand % 10);\n    significand /= 10;\n  }\n  *--out = decimal_point;\n  format_decimal(out - integral_size, significand, integral_size);\n  return end;\n}\n\ntemplate <typename OutputIt, typename UInt, typename Char,\n          FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<OutputIt>>::value)>\ninline auto write_significand(OutputIt out, UInt significand,\n                              int significand_size, int integral_size,\n                              Char decimal_point) -> OutputIt {\n  // Buffer is large enough to hold digits (digits10 + 1) and a decimal point.\n  Char buffer[digits10<UInt>() + 2];\n  auto end = write_significand(buffer, significand, significand_size,\n                               integral_size, decimal_point);\n  return detail::copy_noinline<Char>(buffer, end, out);\n}\n\ntemplate <typename OutputIt, typename Char>\nFMT_CONSTEXPR auto write_significand(OutputIt out, const char* significand,\n                                     int significand_size, int integral_size,\n                                     Char decimal_point) -> OutputIt {\n  out = detail::copy_noinline<Char>(significand, significand + integral_size,\n                                    out);\n  if (!decimal_point) return out;\n  *out++ = decimal_point;\n  return detail::copy_noinline<Char>(significand + integral_size,\n                                     significand + significand_size, out);\n}\n\ntemplate <typename OutputIt, typename Char, typename T, typename Grouping>\nFMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,\n                                       int significand_size, int integral_size,\n                                       Char decimal_point,\n                                       const Grouping& grouping) -> OutputIt {\n  if (!grouping.has_separator()) {\n    return write_significand(out, significand, significand_size, integral_size,\n                             decimal_point);\n  }\n  auto buffer = basic_memory_buffer<Char>();\n  write_significand(basic_appender<Char>(buffer), significand, significand_size,\n                    integral_size, decimal_point);\n  grouping.apply(\n      out, basic_string_view<Char>(buffer.data(), to_unsigned(integral_size)));\n  return detail::copy_noinline<Char>(buffer.data() + integral_size,\n                                     buffer.end(), out);\n}\n\n// Numbers with exponents greater or equal to the returned value will use\n// the exponential notation.\ntemplate <typename T> FMT_CONSTEVAL auto exp_upper() -> int {\n  return std::numeric_limits<T>::digits10 != 0\n             ? min_of(16, std::numeric_limits<T>::digits10 + 1)\n             : 16;\n}\n\n// Use the fixed notation if the exponent is in [-4, exp_upper),\n// e.g. 0.0001 instead of 1e-04. Otherwise use the exponent notation.\nconstexpr auto use_fixed(int exp, int exp_upper) -> bool {\n  return exp >= -4 && exp < exp_upper;\n}\n\ntemplate <typename Char> class fallback_digit_grouping {\n public:\n  constexpr fallback_digit_grouping(locale_ref, bool) {}\n\n  constexpr auto has_separator() const -> bool { return false; }\n\n  constexpr auto count_separators(int) const -> int { return 0; }\n\n  template <typename Out, typename C>\n  constexpr auto apply(Out out, basic_string_view<C>) const -> Out {\n    return out;\n  }\n};\n\ntemplate <typename Char, typename Grouping, typename OutputIt,\n          typename DecimalFP>\nFMT_CONSTEXPR20 auto write_fixed(OutputIt out, const DecimalFP& f,\n                                 int significand_size, Char decimal_point,\n                                 const format_specs& specs, sign s,\n                                 locale_ref loc = {}) -> OutputIt {\n  using iterator = reserve_iterator<OutputIt>;\n\n  int exp = f.exponent + significand_size;\n  long long size = significand_size + (s != sign::none ? 1 : 0);\n  if (f.exponent >= 0) {\n    // 1234e5 -> 123400000[.0+]\n    size += f.exponent;\n    int num_zeros = specs.precision - exp;\n    abort_fuzzing_if(num_zeros > 5000);\n    if (specs.alt()) {\n      ++size;\n      if (num_zeros <= 0 && specs.type() != presentation_type::fixed)\n        num_zeros = 0;\n      if (num_zeros > 0) size += num_zeros;\n    }\n    auto grouping = Grouping(loc, specs.localized());\n    size += grouping.count_separators(exp);\n    return write_padded<Char, align::right>(\n        out, specs, to_unsigned(size), [&](iterator it) {\n          if (s != sign::none) *it++ = detail::getsign<Char>(s);\n          it = write_significand<Char>(it, f.significand, significand_size,\n                                       f.exponent, grouping);\n          if (!specs.alt()) return it;\n          *it++ = decimal_point;\n          return num_zeros > 0 ? detail::fill_n(it, num_zeros, Char('0')) : it;\n        });\n  }\n  if (exp > 0) {\n    // 1234e-2 -> 12.34[0+]\n    int num_zeros = specs.alt() ? specs.precision - significand_size : 0;\n    size += 1 + max_of(num_zeros, 0);\n    auto grouping = Grouping(loc, specs.localized());\n    size += grouping.count_separators(exp);\n    return write_padded<Char, align::right>(\n        out, specs, to_unsigned(size), [&](iterator it) {\n          if (s != sign::none) *it++ = detail::getsign<Char>(s);\n          it = write_significand(it, f.significand, significand_size, exp,\n                                 decimal_point, grouping);\n          return num_zeros > 0 ? detail::fill_n(it, num_zeros, Char('0')) : it;\n        });\n  }\n  // 1234e-6 -> 0.001234\n  int num_zeros = -exp;\n  if (significand_size == 0 && specs.precision >= 0 &&\n      specs.precision < num_zeros) {\n    num_zeros = specs.precision;\n  }\n  bool pointy = num_zeros != 0 || significand_size != 0 || specs.alt();\n  size += 1 + (pointy ? 1 : 0) + num_zeros;\n  return write_padded<Char, align::right>(\n      out, specs, to_unsigned(size), [&](iterator it) {\n        if (s != sign::none) *it++ = detail::getsign<Char>(s);\n        *it++ = Char('0');\n        if (!pointy) return it;\n        *it++ = decimal_point;\n        it = detail::fill_n(it, num_zeros, Char('0'));\n        return write_significand<Char>(it, f.significand, significand_size);\n      });\n}\n\ntemplate <typename Char, typename Grouping, typename OutputIt,\n          typename DecimalFP>\nFMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& f,\n                                    const format_specs& specs, sign s,\n                                    int exp_upper, locale_ref loc) -> OutputIt {\n  Char point = specs.localized() ? detail::decimal_point<Char>(loc) : Char('.');\n  int significand_size = get_significand_size(f);\n  int exp = f.exponent + significand_size - 1;\n  if (specs.type() == presentation_type::fixed ||\n      (specs.type() != presentation_type::exp &&\n       use_fixed(exp, specs.precision > 0 ? specs.precision : exp_upper))) {\n    return write_fixed<Char, Grouping>(out, f, significand_size, point, specs,\n                                       s, loc);\n  }\n\n  // Write value in the exponential format.\n  int num_zeros = 0;\n  long long size = significand_size + (s != sign::none ? 1 : 0);\n  if (specs.alt()) {\n    num_zeros = max_of(specs.precision - significand_size, 0);\n    size += num_zeros;\n  } else if (significand_size == 1) {\n    point = Char();\n  }\n  size += (point ? 1 : 0) + compute_exp_size(exp);\n  char exp_char = specs.upper() ? 'E' : 'e';\n  auto write = [=](reserve_iterator<OutputIt> it) {\n    if (s != sign::none) *it++ = detail::getsign<Char>(s);\n    // Insert a decimal point after the first digit and add an exponent.\n    it = write_significand(it, f.significand, significand_size, 1, point);\n    if (num_zeros > 0) it = detail::fill_n(it, num_zeros, Char('0'));\n    *it++ = Char(exp_char);\n    return write_exponent<Char>(exp, it);\n  };\n  auto usize = to_unsigned(size);\n  return specs.width > 0\n             ? write_padded<Char, align::right>(out, specs, usize, write)\n             : base_iterator(out, write(reserve(out, usize)));\n}\n\ntemplate <typename Char, typename OutputIt, typename DecimalFP>\nFMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& f,\n                                 const format_specs& specs, sign s,\n                                 int exp_upper, locale_ref loc) -> OutputIt {\n  if (is_constant_evaluated()) {\n    return do_write_float<Char, fallback_digit_grouping<Char>>(out, f, specs, s,\n                                                               exp_upper, loc);\n  } else {\n    return do_write_float<Char, digit_grouping<Char>>(out, f, specs, s,\n                                                      exp_upper, loc);\n  }\n}\n\ntemplate <typename T> constexpr auto isnan(T value) -> bool {\n  return value != value;  // std::isnan doesn't support __float128.\n}\n\ntemplate <typename T, typename Enable = void>\nstruct has_isfinite : std::false_type {};\n\ntemplate <typename T>\nstruct has_isfinite<T, enable_if_t<sizeof(std::isfinite(T())) != 0>>\n    : std::true_type {};\n\ntemplate <typename T,\n          FMT_ENABLE_IF(is_floating_point<T>::value&& has_isfinite<T>::value)>\nFMT_CONSTEXPR20 auto isfinite(T value) -> bool {\n  constexpr T inf = T(std::numeric_limits<double>::infinity());\n  if (is_constant_evaluated())\n    return !detail::isnan(value) && value < inf && value > -inf;\n  return std::isfinite(value);\n}\ntemplate <typename T, FMT_ENABLE_IF(!has_isfinite<T>::value)>\nFMT_CONSTEXPR auto isfinite(T value) -> bool {\n  T inf = T(std::numeric_limits<double>::infinity());\n  // std::isfinite doesn't support __float128.\n  return !detail::isnan(value) && value < inf && value > -inf;\n}\n\ntemplate <typename T, FMT_ENABLE_IF(is_floating_point<T>::value)>\nFMT_INLINE FMT_CONSTEXPR auto signbit(T value) -> bool {\n  if (is_constant_evaluated()) {\n#ifdef __cpp_if_constexpr\n    if constexpr (std::numeric_limits<double>::is_iec559) {\n      auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));\n      return (bits >> (num_bits<uint64_t>() - 1)) != 0;\n    }\n#endif\n  }\n  return std::signbit(static_cast<double>(value));\n}\n\ninline FMT_CONSTEXPR20 void adjust_precision(int& precision, int exp10) {\n  // Adjust fixed precision by exponent because it is relative to decimal\n  // point.\n  if (exp10 > 0 && precision > max_value<int>() - exp10)\n    FMT_THROW(format_error(\"number is too big\"));\n  precision += exp10;\n}\n\nclass bigint {\n private:\n  // A bigint is a number in the form bigit_[N - 1] ... bigit_[0] * 32^exp_.\n  using bigit = uint32_t;  // A big digit.\n  using double_bigit = uint64_t;\n  enum { bigit_bits = num_bits<bigit>() };\n  enum { bigits_capacity = 32 };\n  basic_memory_buffer<bigit, bigits_capacity> bigits_;\n  int exp_;\n\n  friend struct formatter<bigint>;\n\n  FMT_CONSTEXPR auto get_bigit(int i) const -> bigit {\n    return i >= exp_ && i < num_bigits() ? bigits_[i - exp_] : 0;\n  }\n\n  FMT_CONSTEXPR void subtract_bigits(int index, bigit other, bigit& borrow) {\n    auto result = double_bigit(bigits_[index]) - other - borrow;\n    bigits_[index] = static_cast<bigit>(result);\n    borrow = static_cast<bigit>(result >> (bigit_bits * 2 - 1));\n  }\n\n  FMT_CONSTEXPR void remove_leading_zeros() {\n    int num_bigits = static_cast<int>(bigits_.size()) - 1;\n    while (num_bigits > 0 && bigits_[num_bigits] == 0) --num_bigits;\n    bigits_.resize(to_unsigned(num_bigits + 1));\n  }\n\n  // Computes *this -= other assuming aligned bigints and *this >= other.\n  FMT_CONSTEXPR void subtract_aligned(const bigint& other) {\n    FMT_ASSERT(other.exp_ >= exp_, \"unaligned bigints\");\n    FMT_ASSERT(compare(*this, other) >= 0, \"\");\n    bigit borrow = 0;\n    int i = other.exp_ - exp_;\n    for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j)\n      subtract_bigits(i, other.bigits_[j], borrow);\n    if (borrow != 0) subtract_bigits(i, 0, borrow);\n    FMT_ASSERT(borrow == 0, \"\");\n    remove_leading_zeros();\n  }\n\n  FMT_CONSTEXPR void multiply(uint32_t value) {\n    bigit carry = 0;\n    const double_bigit wide_value = value;\n    for (size_t i = 0, n = bigits_.size(); i < n; ++i) {\n      double_bigit result = bigits_[i] * wide_value + carry;\n      bigits_[i] = static_cast<bigit>(result);\n      carry = static_cast<bigit>(result >> bigit_bits);\n    }\n    if (carry != 0) bigits_.push_back(carry);\n  }\n\n  template <typename UInt, FMT_ENABLE_IF(std::is_same<UInt, uint64_t>::value ||\n                                         std::is_same<UInt, uint128_t>::value)>\n  FMT_CONSTEXPR void multiply(UInt value) {\n    using half_uint =\n        conditional_t<std::is_same<UInt, uint128_t>::value, uint64_t, uint32_t>;\n    const int shift = num_bits<half_uint>() - bigit_bits;\n    const UInt lower = static_cast<half_uint>(value);\n    const UInt upper = value >> num_bits<half_uint>();\n    UInt carry = 0;\n    for (size_t i = 0, n = bigits_.size(); i < n; ++i) {\n      UInt result = lower * bigits_[i] + static_cast<bigit>(carry);\n      carry = (upper * bigits_[i] << shift) + (result >> bigit_bits) +\n              (carry >> bigit_bits);\n      bigits_[i] = static_cast<bigit>(result);\n    }\n    while (carry != 0) {\n      bigits_.push_back(static_cast<bigit>(carry));\n      carry >>= bigit_bits;\n    }\n  }\n\n  template <typename UInt, FMT_ENABLE_IF(std::is_same<UInt, uint64_t>::value ||\n                                         std::is_same<UInt, uint128_t>::value)>\n  FMT_CONSTEXPR void assign(UInt n) {\n    size_t num_bigits = 0;\n    do {\n      bigits_[num_bigits++] = static_cast<bigit>(n);\n      n >>= bigit_bits;\n    } while (n != 0);\n    bigits_.resize(num_bigits);\n    exp_ = 0;\n  }\n\n public:\n  FMT_CONSTEXPR bigint() : exp_(0) {}\n  explicit bigint(uint64_t n) { assign(n); }\n\n  bigint(const bigint&) = delete;\n  void operator=(const bigint&) = delete;\n\n  FMT_CONSTEXPR void assign(const bigint& other) {\n    auto size = other.bigits_.size();\n    bigits_.resize(size);\n    auto data = other.bigits_.data();\n    copy<bigit>(data, data + size, bigits_.data());\n    exp_ = other.exp_;\n  }\n\n  template <typename Int> FMT_CONSTEXPR void operator=(Int n) {\n    FMT_ASSERT(n > 0, \"\");\n    assign(uint64_or_128_t<Int>(n));\n  }\n\n  FMT_CONSTEXPR auto num_bigits() const -> int {\n    return static_cast<int>(bigits_.size()) + exp_;\n  }\n\n  FMT_CONSTEXPR auto operator<<=(int shift) -> bigint& {\n    FMT_ASSERT(shift >= 0, \"\");\n    exp_ += shift / bigit_bits;\n    shift %= bigit_bits;\n    if (shift == 0) return *this;\n    bigit carry = 0;\n    for (size_t i = 0, n = bigits_.size(); i < n; ++i) {\n      bigit c = bigits_[i] >> (bigit_bits - shift);\n      bigits_[i] = (bigits_[i] << shift) + carry;\n      carry = c;\n    }\n    if (carry != 0) bigits_.push_back(carry);\n    return *this;\n  }\n\n  template <typename Int> FMT_CONSTEXPR auto operator*=(Int value) -> bigint& {\n    FMT_ASSERT(value > 0, \"\");\n    multiply(uint32_or_64_or_128_t<Int>(value));\n    return *this;\n  }\n\n  friend FMT_CONSTEXPR auto compare(const bigint& b1, const bigint& b2) -> int {\n    int num_bigits1 = b1.num_bigits(), num_bigits2 = b2.num_bigits();\n    if (num_bigits1 != num_bigits2) return num_bigits1 > num_bigits2 ? 1 : -1;\n    int i = static_cast<int>(b1.bigits_.size()) - 1;\n    int j = static_cast<int>(b2.bigits_.size()) - 1;\n    int end = i - j;\n    if (end < 0) end = 0;\n    for (; i >= end; --i, --j) {\n      bigit b1_bigit = b1.bigits_[i], b2_bigit = b2.bigits_[j];\n      if (b1_bigit != b2_bigit) return b1_bigit > b2_bigit ? 1 : -1;\n    }\n    if (i != j) return i > j ? 1 : -1;\n    return 0;\n  }\n\n  // Returns compare(lhs1 + lhs2, rhs).\n  friend FMT_CONSTEXPR auto add_compare(const bigint& lhs1, const bigint& lhs2,\n                                        const bigint& rhs) -> int {\n    int max_lhs_bigits = max_of(lhs1.num_bigits(), lhs2.num_bigits());\n    int num_rhs_bigits = rhs.num_bigits();\n    if (max_lhs_bigits + 1 < num_rhs_bigits) return -1;\n    if (max_lhs_bigits > num_rhs_bigits) return 1;\n    double_bigit borrow = 0;\n    int min_exp = min_of(min_of(lhs1.exp_, lhs2.exp_), rhs.exp_);\n    for (int i = num_rhs_bigits - 1; i >= min_exp; --i) {\n      double_bigit sum = double_bigit(lhs1.get_bigit(i)) + lhs2.get_bigit(i);\n      bigit rhs_bigit = rhs.get_bigit(i);\n      if (sum > rhs_bigit + borrow) return 1;\n      borrow = rhs_bigit + borrow - sum;\n      if (borrow > 1) return -1;\n      borrow <<= bigit_bits;\n    }\n    return borrow != 0 ? -1 : 0;\n  }\n\n  // Assigns pow(10, exp) to this bigint.\n  FMT_CONSTEXPR20 void assign_pow10(int exp) {\n    FMT_ASSERT(exp >= 0, \"\");\n    if (exp == 0) return *this = 1;\n    int bitmask = 1 << (num_bits<unsigned>() -\n                        countl_zero(static_cast<uint32_t>(exp)) - 1);\n    // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by\n    // repeated squaring and multiplication.\n    *this = 5;\n    bitmask >>= 1;\n    while (bitmask != 0) {\n      square();\n      if ((exp & bitmask) != 0) *this *= 5;\n      bitmask >>= 1;\n    }\n    *this <<= exp;  // Multiply by pow(2, exp) by shifting.\n  }\n\n  FMT_CONSTEXPR20 void square() {\n    int num_bigits = static_cast<int>(bigits_.size());\n    int num_result_bigits = 2 * num_bigits;\n    basic_memory_buffer<bigit, bigits_capacity> n(std::move(bigits_));\n    bigits_.resize(to_unsigned(num_result_bigits));\n    auto sum = uint128_t();\n    for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) {\n      // Compute bigit at position bigit_index of the result by adding\n      // cross-product terms n[i] * n[j] such that i + j == bigit_index.\n      for (int i = 0, j = bigit_index; j >= 0; ++i, --j) {\n        // Most terms are multiplied twice which can be optimized in the future.\n        sum += double_bigit(n[i]) * n[j];\n      }\n      bigits_[bigit_index] = static_cast<bigit>(sum);\n      sum >>= num_bits<bigit>();  // Compute the carry.\n    }\n    // Do the same for the top half.\n    for (int bigit_index = num_bigits; bigit_index < num_result_bigits;\n         ++bigit_index) {\n      for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;)\n        sum += double_bigit(n[i++]) * n[j--];\n      bigits_[bigit_index] = static_cast<bigit>(sum);\n      sum >>= num_bits<bigit>();\n    }\n    remove_leading_zeros();\n    exp_ *= 2;\n  }\n\n  // If this bigint has a bigger exponent than other, adds trailing zero to make\n  // exponents equal. This simplifies some operations such as subtraction.\n  FMT_CONSTEXPR void align(const bigint& other) {\n    int exp_difference = exp_ - other.exp_;\n    if (exp_difference <= 0) return;\n    int num_bigits = static_cast<int>(bigits_.size());\n    bigits_.resize(to_unsigned(num_bigits + exp_difference));\n    for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j)\n      bigits_[j] = bigits_[i];\n    fill_n(bigits_.data(), to_unsigned(exp_difference), 0U);\n    exp_ -= exp_difference;\n  }\n\n  // Divides this bignum by divisor, assigning the remainder to this and\n  // returning the quotient.\n  FMT_CONSTEXPR auto divmod_assign(const bigint& divisor) -> int {\n    FMT_ASSERT(this != &divisor, \"\");\n    if (compare(*this, divisor) < 0) return 0;\n    FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, \"\");\n    align(divisor);\n    int quotient = 0;\n    do {\n      subtract_aligned(divisor);\n      ++quotient;\n    } while (compare(*this, divisor) >= 0);\n    return quotient;\n  }\n};\n\n// format_dragon flags.\nenum dragon {\n  predecessor_closer = 1,\n  fixup = 2,  // Run fixup to correct exp10 which can be off by one.\n  fixed = 4,\n};\n\n// Formats a floating-point number using a variation of the Fixed-Precision\n// Positive Floating-Point Printout ((FPP)^2) algorithm by Steele & White:\n// https://fmt.dev/papers/p372-steele.pdf.\nFMT_CONSTEXPR20 inline void format_dragon(basic_fp<uint128_t> value,\n                                          unsigned flags, int num_digits,\n                                          buffer<char>& buf, int& exp10) {\n  bigint numerator;    // 2 * R in (FPP)^2.\n  bigint denominator;  // 2 * S in (FPP)^2.\n  // lower and upper are differences between value and corresponding boundaries.\n  bigint lower;             // (M^- in (FPP)^2).\n  bigint upper_store;       // upper's value if different from lower.\n  bigint* upper = nullptr;  // (M^+ in (FPP)^2).\n  // Shift numerator and denominator by an extra bit or two (if lower boundary\n  // is closer) to make lower and upper integers. This eliminates multiplication\n  // by 2 during later computations.\n  bool is_predecessor_closer = (flags & dragon::predecessor_closer) != 0;\n  int shift = is_predecessor_closer ? 2 : 1;\n  if (value.e >= 0) {\n    numerator = value.f;\n    numerator <<= value.e + shift;\n    lower = 1;\n    lower <<= value.e;\n    if (is_predecessor_closer) {\n      upper_store = 1;\n      upper_store <<= value.e + 1;\n      upper = &upper_store;\n    }\n    denominator.assign_pow10(exp10);\n    denominator <<= shift;\n  } else if (exp10 < 0) {\n    numerator.assign_pow10(-exp10);\n    lower.assign(numerator);\n    if (is_predecessor_closer) {\n      upper_store.assign(numerator);\n      upper_store <<= 1;\n      upper = &upper_store;\n    }\n    numerator *= value.f;\n    numerator <<= shift;\n    denominator = 1;\n    denominator <<= shift - value.e;\n  } else {\n    numerator = value.f;\n    numerator <<= shift;\n    denominator.assign_pow10(exp10);\n    denominator <<= shift - value.e;\n    lower = 1;\n    if (is_predecessor_closer) {\n      upper_store = 1ULL << 1;\n      upper = &upper_store;\n    }\n  }\n  int even = static_cast<int>((value.f & 1) == 0);\n  if (!upper) upper = &lower;\n  bool shortest = num_digits < 0;\n  if ((flags & dragon::fixup) != 0) {\n    if (add_compare(numerator, *upper, denominator) + even <= 0) {\n      --exp10;\n      numerator *= 10;\n      if (num_digits < 0) {\n        lower *= 10;\n        if (upper != &lower) *upper *= 10;\n      }\n    }\n    if ((flags & dragon::fixed) != 0) adjust_precision(num_digits, exp10 + 1);\n  }\n  // Invariant: value == (numerator / denominator) * pow(10, exp10).\n  if (shortest) {\n    // Generate the shortest representation.\n    num_digits = 0;\n    char* data = buf.data();\n    for (;;) {\n      int digit = numerator.divmod_assign(denominator);\n      bool low = compare(numerator, lower) - even < 0;  // numerator <[=] lower.\n      // numerator + upper >[=] pow10:\n      bool high = add_compare(numerator, *upper, denominator) + even > 0;\n      data[num_digits++] = static_cast<char>('0' + digit);\n      if (low || high) {\n        if (!low) {\n          ++data[num_digits - 1];\n        } else if (high) {\n          int result = add_compare(numerator, numerator, denominator);\n          // Round half to even.\n          if (result > 0 || (result == 0 && (digit % 2) != 0))\n            ++data[num_digits - 1];\n        }\n        buf.try_resize(to_unsigned(num_digits));\n        exp10 -= num_digits - 1;\n        return;\n      }\n      numerator *= 10;\n      lower *= 10;\n      if (upper != &lower) *upper *= 10;\n    }\n  }\n  // Generate the given number of digits.\n  exp10 -= num_digits - 1;\n  if (num_digits <= 0) {\n    auto digit = '0';\n    if (num_digits == 0) {\n      denominator *= 10;\n      digit = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0';\n    }\n    buf.push_back(digit);\n    return;\n  }\n  buf.try_resize(to_unsigned(num_digits));\n  for (int i = 0; i < num_digits - 1; ++i) {\n    int digit = numerator.divmod_assign(denominator);\n    buf[i] = static_cast<char>('0' + digit);\n    numerator *= 10;\n  }\n  int digit = numerator.divmod_assign(denominator);\n  auto result = add_compare(numerator, numerator, denominator);\n  if (result > 0 || (result == 0 && (digit % 2) != 0)) {\n    if (digit == 9) {\n      const auto overflow = '0' + 10;\n      buf[num_digits - 1] = overflow;\n      // Propagate the carry.\n      for (int i = num_digits - 1; i > 0 && buf[i] == overflow; --i) {\n        buf[i] = '0';\n        ++buf[i - 1];\n      }\n      if (buf[0] == overflow) {\n        buf[0] = '1';\n        if ((flags & dragon::fixed) != 0)\n          buf.push_back('0');\n        else\n          ++exp10;\n      }\n      return;\n    }\n    ++digit;\n  }\n  buf[num_digits - 1] = static_cast<char>('0' + digit);\n}\n\n// Formats a floating-point number using the hexfloat format.\ntemplate <typename Float, FMT_ENABLE_IF(!is_double_double<Float>::value)>\nFMT_CONSTEXPR20 void format_hexfloat(Float value, format_specs specs,\n                                     buffer<char>& buf) {\n  // float is passed as double to reduce the number of instantiations and to\n  // simplify implementation.\n  static_assert(!std::is_same<Float, float>::value, \"\");\n\n  using info = dragonbox::float_info<Float>;\n\n  // Assume Float is in the format [sign][exponent][significand].\n  using carrier_uint = typename info::carrier_uint;\n\n  const auto num_float_significand_bits = detail::num_significand_bits<Float>();\n\n  basic_fp<carrier_uint> f(value);\n  f.e += num_float_significand_bits;\n  if (!has_implicit_bit<Float>()) --f.e;\n\n  const auto num_fraction_bits =\n      num_float_significand_bits + (has_implicit_bit<Float>() ? 1 : 0);\n  const auto num_xdigits = (num_fraction_bits + 3) / 4;\n\n  const auto leading_shift = ((num_xdigits - 1) * 4);\n  const auto leading_mask = carrier_uint(0xF) << leading_shift;\n  const auto leading_xdigit =\n      static_cast<uint32_t>((f.f & leading_mask) >> leading_shift);\n  if (leading_xdigit > 1) f.e -= (32 - countl_zero(leading_xdigit) - 1);\n\n  int print_xdigits = num_xdigits - 1;\n  if (specs.precision >= 0 && print_xdigits > specs.precision) {\n    const int shift = ((print_xdigits - specs.precision - 1) * 4);\n    const auto mask = carrier_uint(0xF) << shift;\n    const auto v = static_cast<uint32_t>((f.f & mask) >> shift);\n\n    if (v >= 8) {\n      const auto inc = carrier_uint(1) << (shift + 4);\n      f.f += inc;\n      f.f &= ~(inc - 1);\n    }\n\n    // Check long double overflow\n    if (!has_implicit_bit<Float>()) {\n      const auto implicit_bit = carrier_uint(1) << num_float_significand_bits;\n      if ((f.f & implicit_bit) == implicit_bit) {\n        f.f >>= 4;\n        f.e += 4;\n      }\n    }\n\n    print_xdigits = specs.precision;\n  }\n\n  char xdigits[num_bits<carrier_uint>() / 4];\n  detail::fill_n(xdigits, sizeof(xdigits), '0');\n  format_base2e(4, xdigits, f.f, num_xdigits, specs.upper());\n\n  // Remove zero tail\n  while (print_xdigits > 0 && xdigits[print_xdigits] == '0') --print_xdigits;\n\n  buf.push_back('0');\n  buf.push_back(specs.upper() ? 'X' : 'x');\n  buf.push_back(xdigits[0]);\n  if (specs.alt() || print_xdigits > 0 || print_xdigits < specs.precision)\n    buf.push_back('.');\n  buf.append(xdigits + 1, xdigits + 1 + print_xdigits);\n  for (; print_xdigits < specs.precision; ++print_xdigits) buf.push_back('0');\n\n  buf.push_back(specs.upper() ? 'P' : 'p');\n\n  uint32_t abs_e;\n  if (f.e < 0) {\n    buf.push_back('-');\n    abs_e = static_cast<uint32_t>(-f.e);\n  } else {\n    buf.push_back('+');\n    abs_e = static_cast<uint32_t>(f.e);\n  }\n  format_decimal<char>(appender(buf), abs_e, detail::count_digits(abs_e));\n}\n\ntemplate <typename Float, FMT_ENABLE_IF(is_double_double<Float>::value)>\nFMT_CONSTEXPR20 void format_hexfloat(Float value, format_specs specs,\n                                     buffer<char>& buf) {\n  format_hexfloat(static_cast<double>(value), specs, buf);\n}\n\nconstexpr auto fractional_part_rounding_thresholds(int index) -> uint32_t {\n  // For checking rounding thresholds.\n  // The kth entry is chosen to be the smallest integer such that the\n  // upper 32-bits of 10^(k+1) times it is strictly bigger than 5 * 10^k.\n  // It is equal to ceil(2^31 + 2^32/10^(k + 1)).\n  // These are stored in a string literal because we cannot have static arrays\n  // in constexpr functions and non-static ones are poorly optimized.\n  return U\"\\x9999999a\\x828f5c29\\x80418938\\x80068db9\\x8000a7c6\\x800010c7\"\n         U\"\\x800001ae\\x8000002b\"[index];\n}\n\ntemplate <typename Float>\nFMT_CONSTEXPR20 auto format_float(Float value, int precision,\n                                  const format_specs& specs, bool binary32,\n                                  buffer<char>& buf) -> int {\n  // float is passed as double to reduce the number of instantiations.\n  static_assert(!std::is_same<Float, float>::value, \"\");\n  auto converted_value = convert_float(value);\n\n  const bool fixed = specs.type() == presentation_type::fixed;\n  if (value == 0) {\n    if (precision <= 0 || !fixed) {\n      buf.push_back('0');\n      return 0;\n    }\n    buf.try_resize(to_unsigned(precision));\n    fill_n(buf.data(), precision, '0');\n    return -precision;\n  }\n\n  int exp = 0;\n  bool use_dragon = true;\n  unsigned dragon_flags = 0;\n  if (!is_fast_float<Float>() || is_constant_evaluated()) {\n    const auto inv_log2_10 = 0.3010299956639812;  // 1 / log2(10)\n    using info = dragonbox::float_info<decltype(converted_value)>;\n    const auto f = basic_fp<typename info::carrier_uint>(converted_value);\n    // Compute exp, an approximate power of 10, such that\n    //   10^(exp - 1) <= value < 10^exp or 10^exp <= value < 10^(exp + 1).\n    // This is based on log10(value) == log2(value) / log2(10) and approximation\n    // of log2(value) by e + num_fraction_bits idea from double-conversion.\n    auto e = (f.e + count_digits<1>(f.f) - 1) * inv_log2_10 - 1e-10;\n    exp = static_cast<int>(e);\n    if (e > exp) ++exp;  // Compute ceil.\n    dragon_flags = dragon::fixup;\n  } else {\n    // Extract significand bits and exponent bits.\n    using info = dragonbox::float_info<double>;\n    auto br = bit_cast<uint64_t>(static_cast<double>(value));\n\n    const uint64_t significand_mask =\n        (static_cast<uint64_t>(1) << num_significand_bits<double>()) - 1;\n    uint64_t significand = (br & significand_mask);\n    int exponent = static_cast<int>((br & exponent_mask<double>()) >>\n                                    num_significand_bits<double>());\n\n    if (exponent != 0) {  // Check if normal.\n      exponent -= exponent_bias<double>() + num_significand_bits<double>();\n      significand |=\n          (static_cast<uint64_t>(1) << num_significand_bits<double>());\n      significand <<= 1;\n    } else {\n      // Normalize subnormal inputs.\n      FMT_ASSERT(significand != 0, \"zeros should not appear here\");\n      int shift = countl_zero(significand);\n      FMT_ASSERT(shift >= num_bits<uint64_t>() - num_significand_bits<double>(),\n                 \"\");\n      shift -= (num_bits<uint64_t>() - num_significand_bits<double>() - 2);\n      exponent = (std::numeric_limits<double>::min_exponent -\n                  num_significand_bits<double>()) -\n                 shift;\n      significand <<= shift;\n    }\n\n    // Compute the first several nonzero decimal significand digits.\n    // We call the number we get the first segment.\n    const int k = info::kappa - dragonbox::floor_log10_pow2(exponent);\n    exp = -k;\n    const int beta = exponent + dragonbox::floor_log2_pow10(k);\n    uint64_t first_segment;\n    bool has_more_segments;\n    int digits_in_the_first_segment;\n    {\n      const auto r = dragonbox::umul192_upper128(\n          significand << beta, dragonbox::get_cached_power(k));\n      first_segment = r.high();\n      has_more_segments = r.low() != 0;\n\n      // The first segment can have 18 ~ 19 digits.\n      if (first_segment >= 1000000000000000000ULL) {\n        digits_in_the_first_segment = 19;\n      } else {\n        // When it is of 18-digits, we align it to 19-digits by adding a bogus\n        // zero at the end.\n        digits_in_the_first_segment = 18;\n        first_segment *= 10;\n      }\n    }\n\n    // Compute the actual number of decimal digits to print.\n    if (fixed) adjust_precision(precision, exp + digits_in_the_first_segment);\n\n    // Use Dragon4 only when there might be not enough digits in the first\n    // segment.\n    if (digits_in_the_first_segment > precision) {\n      use_dragon = false;\n\n      if (precision <= 0) {\n        exp += digits_in_the_first_segment;\n\n        if (precision < 0) {\n          // Nothing to do, since all we have are just leading zeros.\n          buf.try_resize(0);\n        } else {\n          // We may need to round-up.\n          buf.try_resize(1);\n          if ((first_segment | static_cast<uint64_t>(has_more_segments)) >\n              5000000000000000000ULL) {\n            buf[0] = '1';\n          } else {\n            buf[0] = '0';\n          }\n        }\n      }  // precision <= 0\n      else {\n        exp += digits_in_the_first_segment - precision;\n\n        // When precision > 0, we divide the first segment into three\n        // subsegments, each with 9, 9, and 0 ~ 1 digits so that each fits\n        // in 32-bits which usually allows faster calculation than in\n        // 64-bits. Since some compiler (e.g. MSVC) doesn't know how to optimize\n        // division-by-constant for large 64-bit divisors, we do it here\n        // manually. The magic number 7922816251426433760 below is equal to\n        // ceil(2^(64+32) / 10^10).\n        const uint32_t first_subsegment = static_cast<uint32_t>(\n            dragonbox::umul128_upper64(first_segment, 7922816251426433760ULL) >>\n            32);\n        const uint64_t second_third_subsegments =\n            first_segment - first_subsegment * 10000000000ULL;\n\n        uint64_t prod;\n        uint32_t digits;\n        bool should_round_up;\n        int number_of_digits_to_print = min_of(precision, 9);\n\n        // Print a 9-digits subsegment, either the first or the second.\n        auto print_subsegment = [&](uint32_t subsegment, char* buffer) {\n          int number_of_digits_printed = 0;\n\n          // If we want to print an odd number of digits from the subsegment,\n          if ((number_of_digits_to_print & 1) != 0) {\n            // Convert to 64-bit fixed-point fractional form with 1-digit\n            // integer part. The magic number 720575941 is a good enough\n            // approximation of 2^(32 + 24) / 10^8; see\n            // https://jk-jeon.github.io/posts/2022/12/fixed-precision-formatting/#fixed-length-case\n            // for details.\n            prod = ((subsegment * static_cast<uint64_t>(720575941)) >> 24) + 1;\n            digits = static_cast<uint32_t>(prod >> 32);\n            *buffer = static_cast<char>('0' + digits);\n            number_of_digits_printed++;\n          }\n          // If we want to print an even number of digits from the\n          // first_subsegment,\n          else {\n            // Convert to 64-bit fixed-point fractional form with 2-digits\n            // integer part. The magic number 450359963 is a good enough\n            // approximation of 2^(32 + 20) / 10^7; see\n            // https://jk-jeon.github.io/posts/2022/12/fixed-precision-formatting/#fixed-length-case\n            // for details.\n            prod = ((subsegment * static_cast<uint64_t>(450359963)) >> 20) + 1;\n            digits = static_cast<uint32_t>(prod >> 32);\n            write2digits(buffer, digits);\n            number_of_digits_printed += 2;\n          }\n\n          // Print all digit pairs.\n          while (number_of_digits_printed < number_of_digits_to_print) {\n            prod = static_cast<uint32_t>(prod) * static_cast<uint64_t>(100);\n            digits = static_cast<uint32_t>(prod >> 32);\n            write2digits(buffer + number_of_digits_printed, digits);\n            number_of_digits_printed += 2;\n          }\n        };\n\n        // Print first subsegment.\n        print_subsegment(first_subsegment, buf.data());\n\n        // Perform rounding if the first subsegment is the last subsegment to\n        // print.\n        if (precision <= 9) {\n          // Rounding inside the subsegment.\n          // We round-up if:\n          //  - either the fractional part is strictly larger than 1/2, or\n          //  - the fractional part is exactly 1/2 and the last digit is odd.\n          // We rely on the following observations:\n          //  - If fractional_part >= threshold, then the fractional part is\n          //    strictly larger than 1/2.\n          //  - If the MSB of fractional_part is set, then the fractional part\n          //    must be at least 1/2.\n          //  - When the MSB of fractional_part is set, either\n          //    second_third_subsegments being nonzero or has_more_segments\n          //    being true means there are further digits not printed, so the\n          //    fractional part is strictly larger than 1/2.\n          if (precision < 9) {\n            uint32_t fractional_part = static_cast<uint32_t>(prod);\n            should_round_up =\n                fractional_part >= fractional_part_rounding_thresholds(\n                                       8 - number_of_digits_to_print) ||\n                ((fractional_part >> 31) &\n                 ((digits & 1) | (second_third_subsegments != 0) |\n                  has_more_segments)) != 0;\n          }\n          // Rounding at the subsegment boundary.\n          // In this case, the fractional part is at least 1/2 if and only if\n          // second_third_subsegments >= 5000000000ULL, and is strictly larger\n          // than 1/2 if we further have either second_third_subsegments >\n          // 5000000000ULL or has_more_segments == true.\n          else {\n            should_round_up = second_third_subsegments > 5000000000ULL ||\n                              (second_third_subsegments == 5000000000ULL &&\n                               ((digits & 1) != 0 || has_more_segments));\n          }\n        }\n        // Otherwise, print the second subsegment.\n        else {\n          // Compilers are not aware of how to leverage the maximum value of\n          // second_third_subsegments to find out a better magic number which\n          // allows us to eliminate an additional shift. 1844674407370955162 =\n          // ceil(2^64/10) < ceil(2^64*(10^9/(10^10 - 1))).\n          const uint32_t second_subsegment =\n              static_cast<uint32_t>(dragonbox::umul128_upper64(\n                  second_third_subsegments, 1844674407370955162ULL));\n          const uint32_t third_subsegment =\n              static_cast<uint32_t>(second_third_subsegments) -\n              second_subsegment * 10;\n\n          number_of_digits_to_print = precision - 9;\n          print_subsegment(second_subsegment, buf.data() + 9);\n\n          // Rounding inside the subsegment.\n          if (precision < 18) {\n            // The condition third_subsegment != 0 implies that the segment was\n            // of 19 digits, so in this case the third segment should be\n            // consisting of a genuine digit from the input.\n            uint32_t fractional_part = static_cast<uint32_t>(prod);\n            should_round_up =\n                fractional_part >= fractional_part_rounding_thresholds(\n                                       8 - number_of_digits_to_print) ||\n                ((fractional_part >> 31) &\n                 ((digits & 1) | (third_subsegment != 0) |\n                  has_more_segments)) != 0;\n          }\n          // Rounding at the subsegment boundary.\n          else {\n            // In this case, the segment must be of 19 digits, thus\n            // the third subsegment should be consisting of a genuine digit from\n            // the input.\n            should_round_up = third_subsegment > 5 ||\n                              (third_subsegment == 5 &&\n                               ((digits & 1) != 0 || has_more_segments));\n          }\n        }\n\n        // Round-up if necessary.\n        if (should_round_up) {\n          ++buf[precision - 1];\n          for (int i = precision - 1; i > 0 && buf[i] > '9'; --i) {\n            buf[i] = '0';\n            ++buf[i - 1];\n          }\n          if (buf[0] > '9') {\n            buf[0] = '1';\n            if (fixed)\n              buf[precision++] = '0';\n            else\n              ++exp;\n          }\n        }\n        buf.try_resize(to_unsigned(precision));\n      }\n    }  // if (digits_in_the_first_segment > precision)\n    else {\n      // Adjust the exponent for its use in Dragon4.\n      exp += digits_in_the_first_segment - 1;\n    }\n  }\n  if (use_dragon) {\n    auto f = basic_fp<uint128_t>();\n    bool is_predecessor_closer = binary32 ? f.assign(static_cast<float>(value))\n                                          : f.assign(converted_value);\n    if (is_predecessor_closer) dragon_flags |= dragon::predecessor_closer;\n    if (fixed) dragon_flags |= dragon::fixed;\n    // Limit precision to the maximum possible number of significant digits in\n    // an IEEE754 double because we don't need to generate zeros.\n    const int max_double_digits = 767;\n    if (precision > max_double_digits) precision = max_double_digits;\n    format_dragon(f, dragon_flags, precision, buf, exp);\n  }\n  if (!fixed && !specs.alt()) {\n    // Remove trailing zeros.\n    auto num_digits = buf.size();\n    while (num_digits > 0 && buf[num_digits - 1] == '0') {\n      --num_digits;\n      ++exp;\n    }\n    buf.try_resize(num_digits);\n  }\n  return exp;\n}\n\ntemplate <typename Char, typename OutputIt, typename T,\n          FMT_ENABLE_IF(is_floating_point<T>::value)>\nFMT_CONSTEXPR20 auto write(OutputIt out, T value, format_specs specs,\n                           locale_ref loc = {}) -> OutputIt {\n  if (specs.localized() && write_loc(out, value, specs, loc)) return out;\n\n  // Use signbit because value < 0 is false for NaN.\n  sign s = detail::signbit(value) ? sign::minus : specs.sign();\n\n  if (!detail::isfinite(value))\n    return write_nonfinite<Char>(out, detail::isnan(value), specs, s);\n\n  if (specs.align() == align::numeric && s != sign::none) {\n    *out++ = detail::getsign<Char>(s);\n    s = sign::none;\n    if (specs.width != 0) --specs.width;\n  }\n\n  const int exp_upper = detail::exp_upper<T>();\n  int precision = specs.precision;\n  if (precision < 0) {\n    if (specs.type() != presentation_type::none) {\n      precision = 6;\n    } else if (is_fast_float<T>::value && !is_constant_evaluated()) {\n      // Use Dragonbox for the shortest format.\n      auto dec = dragonbox::to_decimal(static_cast<fast_float_t<T>>(value));\n      return write_float<Char>(out, dec, specs, s, exp_upper, loc);\n    }\n  }\n\n  memory_buffer buffer;\n  if (specs.type() == presentation_type::hexfloat) {\n    if (s != sign::none) buffer.push_back(detail::getsign<char>(s));\n    format_hexfloat(convert_float(value), specs, buffer);\n    return write_bytes<Char, align::right>(out, {buffer.data(), buffer.size()},\n                                           specs);\n  }\n\n  if (specs.type() == presentation_type::exp) {\n    if (precision == max_value<int>())\n      report_error(\"number is too big\");\n    else\n      ++precision;\n    if (specs.precision != 0) specs.set_alt();\n  } else if (specs.type() == presentation_type::fixed) {\n    if (specs.precision != 0) specs.set_alt();\n  } else if (precision == 0) {\n    precision = 1;\n  }\n  int exp = format_float(convert_float(value), precision, specs,\n                         std::is_same<T, float>(), buffer);\n\n  specs.precision = precision;\n  auto f = big_decimal_fp{buffer.data(), static_cast<int>(buffer.size()), exp};\n  return write_float<Char>(out, f, specs, s, exp_upper, loc);\n}\n\ntemplate <typename Char, typename OutputIt, typename T,\n          FMT_ENABLE_IF(is_fast_float<T>::value)>\nFMT_CONSTEXPR20 auto write(OutputIt out, T value) -> OutputIt {\n  if (is_constant_evaluated()) return write<Char>(out, value, format_specs());\n\n  auto s = detail::signbit(value) ? sign::minus : sign::none;\n  auto mask = exponent_mask<fast_float_t<T>>();\n  if ((bit_cast<decltype(mask)>(value) & mask) == mask)\n    return write_nonfinite<Char>(out, std::isnan(value), {}, s);\n\n  auto dec = dragonbox::to_decimal(static_cast<fast_float_t<T>>(value));\n  auto significand = dec.significand;\n  int significand_size = count_digits(significand);\n  int exponent = dec.exponent + significand_size - 1;\n  if (use_fixed(exponent, detail::exp_upper<T>())) {\n    return write_fixed<Char, fallback_digit_grouping<Char>>(\n        out, dec, significand_size, Char('.'), {}, s);\n  }\n\n  // Write value in the exponential format.\n  const char* prefix = \"e+\";\n  int abs_exponent = exponent;\n  if (exponent < 0) {\n    abs_exponent = -exponent;\n    prefix = \"e-\";\n  }\n  auto has_decimal_point = significand_size != 1;\n  size_t size = std::is_pointer<OutputIt>::value\n                    ? 0u\n                    : to_unsigned((s != sign::none ? 1 : 0) + significand_size +\n                                  (has_decimal_point ? 1 : 0) +\n                                  (abs_exponent >= 100 ? 5 : 4));\n  if (auto ptr = to_pointer<Char>(out, size)) {\n    if (s != sign::none) *ptr++ = Char('-');\n    if (has_decimal_point) {\n      auto begin = ptr;\n      ptr = format_decimal<Char>(ptr, significand, significand_size + 1);\n      *begin = begin[1];\n      begin[1] = '.';\n    } else {\n      *ptr++ = static_cast<Char>('0' + significand);\n    }\n    if (std::is_same<Char, char>::value) {\n      memcpy(ptr, prefix, 2);\n      ptr += 2;\n    } else {\n      *ptr++ = prefix[0];\n      *ptr++ = prefix[1];\n    }\n    if (abs_exponent >= 100) {\n      *ptr++ = static_cast<Char>('0' + abs_exponent / 100);\n      abs_exponent %= 100;\n    }\n    write2digits(ptr, static_cast<unsigned>(abs_exponent));\n    return select<std::is_pointer<OutputIt>::value>(ptr + 2, out);\n  }\n  auto it = reserve(out, size);\n  if (s != sign::none) *it++ = Char('-');\n  // Insert a decimal point after the first digit and add an exponent.\n  it = write_significand(it, significand, significand_size, 1,\n                         has_decimal_point ? Char('.') : Char());\n  *it++ = Char('e');\n  it = write_exponent<Char>(exponent, it);\n  return base_iterator(out, it);\n}\n\ntemplate <typename Char, typename OutputIt, typename T,\n          FMT_ENABLE_IF(is_floating_point<T>::value &&\n                        !is_fast_float<T>::value)>\ninline auto write(OutputIt out, T value) -> OutputIt {\n  return write<Char>(out, value, {});\n}\n\ntemplate <typename Char, typename OutputIt>\nauto write(OutputIt out, monostate, format_specs = {}, locale_ref = {})\n    -> OutputIt {\n  FMT_ASSERT(false, \"\");\n  return out;\n}\n\ntemplate <typename Char, typename OutputIt>\nFMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> value)\n    -> OutputIt {\n  return copy_noinline<Char>(value.begin(), value.end(), out);\n}\n\ntemplate <typename Char, typename OutputIt, typename T,\n          FMT_ENABLE_IF(has_to_string_view<T>::value)>\nconstexpr auto write(OutputIt out, const T& value) -> OutputIt {\n  return write<Char>(out, to_string_view(value));\n}\n\n// FMT_ENABLE_IF() condition separated to workaround an MSVC bug.\ntemplate <\n    typename Char, typename OutputIt, typename T,\n    bool check = std::is_enum<T>::value && !std::is_same<T, Char>::value &&\n                 mapped_type_constant<T, Char>::value != type::custom_type,\n    FMT_ENABLE_IF(check)>\nFMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {\n  return write<Char>(out, static_cast<underlying_t<T>>(value));\n}\n\ntemplate <typename Char, typename OutputIt, typename T,\n          FMT_ENABLE_IF(std::is_same<T, bool>::value)>\nFMT_CONSTEXPR auto write(OutputIt out, T value, const format_specs& specs = {},\n                         locale_ref = {}) -> OutputIt {\n  return specs.type() != presentation_type::none &&\n                 specs.type() != presentation_type::string\n             ? write<Char>(out, value ? 1 : 0, specs, {})\n             : write_bytes<Char>(out, value ? \"true\" : \"false\", specs);\n}\n\ntemplate <typename Char, typename OutputIt>\nFMT_CONSTEXPR auto write(OutputIt out, Char value) -> OutputIt {\n  auto it = reserve(out, 1);\n  *it++ = value;\n  return base_iterator(out, it);\n}\n\ntemplate <typename Char, typename OutputIt>\nFMT_CONSTEXPR20 auto write(OutputIt out, const Char* value) -> OutputIt {\n  if (value) return write(out, basic_string_view<Char>(value));\n  report_error(\"string pointer is null\");\n  return out;\n}\n\ntemplate <typename Char, typename OutputIt, typename T,\n          FMT_ENABLE_IF(std::is_same<T, void>::value)>\nauto write(OutputIt out, const T* value, const format_specs& specs = {},\n           locale_ref = {}) -> OutputIt {\n  return write_ptr<Char>(out, bit_cast<uintptr_t>(value), &specs);\n}\n\ntemplate <typename Char, typename OutputIt, typename T,\n          FMT_ENABLE_IF(mapped_type_constant<T, Char>::value ==\n                            type::custom_type &&\n                        !std::is_fundamental<T>::value)>\nFMT_CONSTEXPR auto write(OutputIt out, const T& value) -> OutputIt {\n  auto f = formatter<T, Char>();\n  auto parse_ctx = parse_context<Char>({});\n  f.parse(parse_ctx);\n  auto ctx = basic_format_context<OutputIt, Char>(out, {}, {});\n  return f.format(value, ctx);\n}\n\ntemplate <typename T>\nusing is_builtin =\n    bool_constant<std::is_same<T, int>::value || FMT_BUILTIN_TYPES>;\n\n// An argument visitor that formats the argument and writes it via the output\n// iterator. It's a class and not a generic lambda for compatibility with C++11.\ntemplate <typename Char> struct default_arg_formatter {\n  using context = buffered_context<Char>;\n\n  basic_appender<Char> out;\n\n  void operator()(monostate) { report_error(\"argument not found\"); }\n\n  template <typename T, FMT_ENABLE_IF(is_builtin<T>::value)>\n  void operator()(T value) {\n    write<Char>(out, value);\n  }\n\n  template <typename T, FMT_ENABLE_IF(!is_builtin<T>::value)>\n  void operator()(T) {\n    FMT_ASSERT(false, \"\");\n  }\n\n  void operator()(typename basic_format_arg<context>::handle h) {\n    // Use a null locale since the default format must be unlocalized.\n    auto parse_ctx = parse_context<Char>({});\n    auto format_ctx = context(out, {}, {});\n    h.format(parse_ctx, format_ctx);\n  }\n};\n\ntemplate <typename Char> struct arg_formatter {\n  basic_appender<Char> out;\n  const format_specs& specs;\n  FMT_NO_UNIQUE_ADDRESS locale_ref locale;\n\n  template <typename T, FMT_ENABLE_IF(is_builtin<T>::value)>\n  FMT_CONSTEXPR FMT_INLINE void operator()(T value) {\n    detail::write<Char>(out, value, specs, locale);\n  }\n\n  template <typename T, FMT_ENABLE_IF(!is_builtin<T>::value)>\n  void operator()(T) {\n    FMT_ASSERT(false, \"\");\n  }\n\n  void operator()(typename basic_format_arg<buffered_context<Char>>::handle) {\n    // User-defined types are handled separately because they require access\n    // to the parse context.\n  }\n};\n\nstruct dynamic_spec_getter {\n  template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>\n  FMT_CONSTEXPR auto operator()(T value) -> unsigned long long {\n    return is_negative(value) ? ~0ull : static_cast<unsigned long long>(value);\n  }\n\n  template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>\n  FMT_CONSTEXPR auto operator()(T) -> unsigned long long {\n    report_error(\"width/precision is not integer\");\n    return 0;\n  }\n};\n\ntemplate <typename Context>\nFMT_CONSTEXPR void handle_dynamic_spec(\n    arg_id_kind kind, int& value,\n    const arg_ref<typename Context::char_type>& ref, Context& ctx) {\n  if (kind == arg_id_kind::none) return;\n  auto arg =\n      kind == arg_id_kind::index ? ctx.arg(ref.index) : ctx.arg(ref.name);\n  if (!arg) report_error(\"argument not found\");\n  unsigned long long result = arg.visit(dynamic_spec_getter());\n  if (result > to_unsigned(max_value<int>()))\n    report_error(\"width/precision is out of range\");\n  value = static_cast<int>(result);\n}\n\n#if FMT_USE_NONTYPE_TEMPLATE_ARGS\ntemplate <typename T, typename Char, size_t N,\n          fmt::detail::fixed_string<Char, N> Str>\nstruct static_named_arg : view {\n  static constexpr auto name = Str.data;\n\n  const T& value;\n  static_named_arg(const T& v) : value(v) {}\n};\n\ntemplate <typename T, typename Char, size_t N,\n          fmt::detail::fixed_string<Char, N> Str>\nstruct is_named_arg<static_named_arg<T, Char, N, Str>> : std::true_type {};\n\ntemplate <typename T, typename Char, size_t N,\n          fmt::detail::fixed_string<Char, N> Str>\nstruct is_static_named_arg<static_named_arg<T, Char, N, Str>> : std::true_type {\n};\n\ntemplate <typename Char, size_t N, fmt::detail::fixed_string<Char, N> Str>\nstruct udl_arg {\n  template <typename T> auto operator=(T&& value) const {\n    return static_named_arg<T, Char, N, Str>(std::forward<T>(value));\n  }\n};\n#else\ntemplate <typename Char> struct udl_arg {\n  const Char* str;\n\n  template <typename T> auto operator=(T&& value) const -> named_arg<Char, T> {\n    return {str, std::forward<T>(value)};\n  }\n};\n#endif  // FMT_USE_NONTYPE_TEMPLATE_ARGS\n\ntemplate <typename Char = char> struct format_handler {\n  parse_context<Char> parse_ctx;\n  buffered_context<Char> ctx;\n\n  void on_text(const Char* begin, const Char* end) {\n    copy_noinline<Char>(begin, end, ctx.out());\n  }\n\n  FMT_CONSTEXPR auto on_arg_id() -> int { return parse_ctx.next_arg_id(); }\n  FMT_CONSTEXPR auto on_arg_id(int id) -> int {\n    parse_ctx.check_arg_id(id);\n    return id;\n  }\n  FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {\n    parse_ctx.check_arg_id(id);\n    int arg_id = ctx.arg_id(id);\n    if (arg_id < 0) report_error(\"argument not found\");\n    return arg_id;\n  }\n\n  FMT_INLINE void on_replacement_field(int id, const Char*) {\n    ctx.arg(id).visit(default_arg_formatter<Char>{ctx.out()});\n  }\n\n  auto on_format_specs(int id, const Char* begin, const Char* end)\n      -> const Char* {\n    auto arg = ctx.arg(id);\n    if (!arg) report_error(\"argument not found\");\n    // Not using a visitor for custom types gives better codegen.\n    if (arg.format_custom(begin, parse_ctx, ctx)) return parse_ctx.begin();\n\n    auto specs = dynamic_format_specs<Char>();\n    begin = parse_format_specs(begin, end, specs, parse_ctx, arg.type());\n    if (specs.dynamic()) {\n      handle_dynamic_spec(specs.dynamic_width(), specs.width, specs.width_ref,\n                          ctx);\n      handle_dynamic_spec(specs.dynamic_precision(), specs.precision,\n                          specs.precision_ref, ctx);\n    }\n\n    arg.visit(arg_formatter<Char>{ctx.out(), specs, ctx.locale()});\n    return begin;\n  }\n\n  FMT_NORETURN void on_error(const char* message) { report_error(message); }\n};\n\n// It is used in format-inl.h and os.cc.\nusing format_func = void (*)(detail::buffer<char>&, int, const char*);\nFMT_API void do_report_error(format_func func, int error_code,\n                             const char* message) noexcept;\n\nFMT_API void format_error_code(buffer<char>& out, int error_code,\n                               string_view message) noexcept;\n\ntemplate <typename T, typename Char, type TYPE>\ntemplate <typename FormatContext>\nFMT_CONSTEXPR auto native_formatter<T, Char, TYPE>::format(\n    const T& val, FormatContext& ctx) const -> decltype(ctx.out()) {\n  if (!specs_.dynamic())\n    return write<Char>(ctx.out(), val, specs_, ctx.locale());\n  auto specs = format_specs(specs_);\n  handle_dynamic_spec(specs.dynamic_width(), specs.width, specs_.width_ref,\n                      ctx);\n  handle_dynamic_spec(specs.dynamic_precision(), specs.precision,\n                      specs_.precision_ref, ctx);\n  return write<Char>(ctx.out(), val, specs, ctx.locale());\n}\n}  // namespace detail\n\nFMT_BEGIN_EXPORT\n\n// A generic formatting context with custom output iterator and character\n// (code unit) support. Char is the format string code unit type which can be\n// different from OutputIt::value_type.\ntemplate <typename OutputIt, typename Char> class generic_context {\n private:\n  OutputIt out_;\n  basic_format_args<generic_context> args_;\n  locale_ref loc_;\n\n public:\n  using char_type = Char;\n  using iterator = OutputIt;\n  enum { builtin_types = FMT_BUILTIN_TYPES };\n\n  constexpr generic_context(OutputIt out,\n                            basic_format_args<generic_context> args,\n                            locale_ref loc = {})\n      : out_(out), args_(args), loc_(loc) {}\n  generic_context(generic_context&&) = default;\n  generic_context(const generic_context&) = delete;\n  void operator=(const generic_context&) = delete;\n\n  constexpr auto arg(int id) const -> basic_format_arg<generic_context> {\n    return args_.get(id);\n  }\n  auto arg(basic_string_view<Char> name) const\n      -> basic_format_arg<generic_context> {\n    return args_.get(name);\n  }\n  constexpr auto arg_id(basic_string_view<Char> name) const -> int {\n    return args_.get_id(name);\n  }\n\n  constexpr auto out() const -> iterator { return out_; }\n\n  void advance_to(iterator it) {\n    if (!detail::is_back_insert_iterator<iterator>()) out_ = it;\n  }\n\n  constexpr auto locale() const -> locale_ref { return loc_; }\n};\n\nclass loc_value {\n private:\n  basic_format_arg<context> value_;\n\n public:\n  template <typename T, FMT_ENABLE_IF(!detail::is_float128<T>::value)>\n  loc_value(T value) : value_(value) {}\n\n  template <typename T, FMT_ENABLE_IF(detail::is_float128<T>::value)>\n  loc_value(T) {}\n\n  template <typename Visitor> auto visit(Visitor&& vis) -> decltype(vis(0)) {\n    return value_.visit(vis);\n  }\n};\n\n// A locale facet that formats values in UTF-8.\n// It is parameterized on the locale to avoid the heavy <locale> include.\ntemplate <typename Locale> class format_facet : public Locale::facet {\n private:\n  std::string separator_;\n  std::string grouping_;\n  std::string decimal_point_;\n\n protected:\n  virtual auto do_put(appender out, loc_value val,\n                      const format_specs& specs) const -> bool;\n\n public:\n  static FMT_API typename Locale::id id;\n\n  explicit format_facet(Locale& loc);\n  explicit format_facet(string_view sep = \"\", std::string grouping = \"\\3\",\n                        std::string decimal_point = \".\")\n      : separator_(sep.data(), sep.size()),\n        grouping_(grouping),\n        decimal_point_(decimal_point) {}\n\n  auto put(appender out, loc_value val, const format_specs& specs) const\n      -> bool {\n    return do_put(out, val, specs);\n  }\n};\n\n#define FMT_FORMAT_AS(Type, Base)                                   \\\n  template <typename Char>                                          \\\n  struct formatter<Type, Char> : formatter<Base, Char> {            \\\n    template <typename FormatContext>                               \\\n    FMT_CONSTEXPR auto format(Type value, FormatContext& ctx) const \\\n        -> decltype(ctx.out()) {                                    \\\n      return formatter<Base, Char>::format(value, ctx);             \\\n    }                                                               \\\n  }\n\nFMT_FORMAT_AS(signed char, int);\nFMT_FORMAT_AS(unsigned char, unsigned);\nFMT_FORMAT_AS(short, int);\nFMT_FORMAT_AS(unsigned short, unsigned);\nFMT_FORMAT_AS(long, detail::long_type);\nFMT_FORMAT_AS(unsigned long, detail::ulong_type);\nFMT_FORMAT_AS(Char*, const Char*);\nFMT_FORMAT_AS(detail::std_string_view<Char>, basic_string_view<Char>);\nFMT_FORMAT_AS(std::nullptr_t, const void*);\nFMT_FORMAT_AS(void*, const void*);\n\ntemplate <typename Char, size_t N>\nstruct formatter<Char[N], Char> : formatter<basic_string_view<Char>, Char> {};\n\ntemplate <typename Char, typename Traits, typename Allocator>\nclass formatter<std::basic_string<Char, Traits, Allocator>, Char>\n    : public formatter<basic_string_view<Char>, Char> {};\n\ntemplate <int N, typename Char>\nstruct formatter<detail::bitint<N>, Char> : formatter<long long, Char> {};\ntemplate <int N, typename Char>\nstruct formatter<detail::ubitint<N>, Char>\n    : formatter<unsigned long long, Char> {};\n\ntemplate <typename Char>\nstruct formatter<detail::float128, Char>\n    : detail::native_formatter<detail::float128, Char,\n                               detail::type::float_type> {};\n\ntemplate <typename T, typename Char>\nstruct formatter<T, Char, void_t<detail::format_as_result<T>>>\n    : formatter<detail::format_as_result<T>, Char> {\n  template <typename FormatContext>\n  FMT_CONSTEXPR auto format(const T& value, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    auto&& val = format_as(value);  // Make an lvalue reference for format.\n    return formatter<detail::format_as_result<T>, Char>::format(val, ctx);\n  }\n};\n\n/**\n * Converts `p` to `const void*` for pointer formatting.\n *\n * **Example**:\n *\n *     auto s = fmt::format(\"{}\", fmt::ptr(p));\n */\ntemplate <typename T> auto ptr(T p) -> const void* {\n  static_assert(std::is_pointer<T>::value, \"fmt::ptr used with non-pointer\");\n  return detail::bit_cast<const void*>(p);\n}\n\n/**\n * Converts `e` to the underlying type.\n *\n * **Example**:\n *\n *     enum class color { red, green, blue };\n *     auto s = fmt::format(\"{}\", fmt::underlying(color::red));  // s == \"0\"\n */\ntemplate <typename Enum>\nconstexpr auto underlying(Enum e) noexcept -> underlying_t<Enum> {\n  return static_cast<underlying_t<Enum>>(e);\n}\n\nnamespace enums {\ntemplate <typename Enum, FMT_ENABLE_IF(std::is_enum<Enum>::value)>\nconstexpr auto format_as(Enum e) noexcept -> underlying_t<Enum> {\n  return static_cast<underlying_t<Enum>>(e);\n}\n}  // namespace enums\n\n#ifdef __cpp_lib_byte\ntemplate <typename Char>\nstruct formatter<std::byte, Char> : formatter<unsigned, Char> {\n  static auto format_as(std::byte b) -> unsigned char {\n    return static_cast<unsigned char>(b);\n  }\n  template <typename Context>\n  auto format(std::byte b, Context& ctx) const -> decltype(ctx.out()) {\n    return formatter<unsigned, Char>::format(format_as(b), ctx);\n  }\n};\n#endif\n\nstruct bytes {\n  string_view data;\n\n  inline explicit bytes(string_view s) : data(s) {}\n};\n\ntemplate <> struct formatter<bytes> {\n private:\n  detail::dynamic_format_specs<> specs_;\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* {\n    return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx,\n                              detail::type::string_type);\n  }\n\n  template <typename FormatContext>\n  auto format(bytes b, FormatContext& ctx) const -> decltype(ctx.out()) {\n    auto specs = specs_;\n    detail::handle_dynamic_spec(specs.dynamic_width(), specs.width,\n                                specs.width_ref, ctx);\n    detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision,\n                                specs.precision_ref, ctx);\n    return detail::write_bytes<char>(ctx.out(), b.data, specs);\n  }\n};\n\n// group_digits_view is not derived from view because it copies the argument.\ntemplate <typename T> struct group_digits_view {\n  T value;\n};\n\n/**\n * Returns a view that formats an integer value using ',' as a\n * locale-independent thousands separator.\n *\n * **Example**:\n *\n *     fmt::print(\"{}\", fmt::group_digits(12345));\n *     // Output: \"12,345\"\n */\ntemplate <typename T> auto group_digits(T value) -> group_digits_view<T> {\n  return {value};\n}\n\ntemplate <typename T> struct formatter<group_digits_view<T>> : formatter<T> {\n private:\n  detail::dynamic_format_specs<> specs_;\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* {\n    return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx,\n                              detail::type::int_type);\n  }\n\n  template <typename FormatContext>\n  auto format(group_digits_view<T> view, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    auto specs = specs_;\n    detail::handle_dynamic_spec(specs.dynamic_width(), specs.width,\n                                specs.width_ref, ctx);\n    detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision,\n                                specs.precision_ref, ctx);\n    auto arg = detail::make_write_int_arg(view.value, specs.sign());\n    return detail::write_int(\n        ctx.out(), static_cast<detail::uint64_or_128_t<T>>(arg.abs_value),\n        arg.prefix, specs, detail::digit_grouping<char>(\"\\3\", \",\"));\n  }\n};\n\ntemplate <typename T, typename Char> struct nested_view {\n  const formatter<T, Char>* fmt;\n  const T* value;\n};\n\ntemplate <typename T, typename Char>\nstruct formatter<nested_view<T, Char>, Char> {\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    return ctx.begin();\n  }\n  template <typename FormatContext>\n  auto format(nested_view<T, Char> view, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    return view.fmt->format(*view.value, ctx);\n  }\n};\n\ntemplate <typename T, typename Char = char> struct nested_formatter {\n private:\n  basic_specs specs_;\n  int width_;\n  formatter<T, Char> formatter_;\n\n public:\n  constexpr nested_formatter() : width_(0) {}\n\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    auto it = ctx.begin(), end = ctx.end();\n    if (it == end) return it;\n    auto specs = format_specs();\n    it = detail::parse_align(it, end, specs);\n    specs_ = specs;\n    Char c = *it;\n    auto width_ref = detail::arg_ref<Char>();\n    if ((c >= '0' && c <= '9') || c == '{') {\n      it = detail::parse_width(it, end, specs, width_ref, ctx);\n      width_ = specs.width;\n    }\n    ctx.advance_to(it);\n    return formatter_.parse(ctx);\n  }\n\n  template <typename FormatContext, typename F>\n  auto write_padded(FormatContext& ctx, F write) const -> decltype(ctx.out()) {\n    if (width_ == 0) return write(ctx.out());\n    auto buf = basic_memory_buffer<Char>();\n    write(basic_appender<Char>(buf));\n    auto specs = format_specs();\n    specs.width = width_;\n    specs.copy_fill_from(specs_);\n    specs.set_align(specs_.align());\n    return detail::write<Char>(\n        ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs);\n  }\n\n  auto nested(const T& value) const -> nested_view<T, Char> {\n    return nested_view<T, Char>{&formatter_, &value};\n  }\n};\n\ninline namespace literals {\n#if FMT_USE_NONTYPE_TEMPLATE_ARGS\ntemplate <detail::fixed_string S> constexpr auto operator\"\"_a() {\n  using char_t = remove_cvref_t<decltype(*S.data)>;\n  return detail::udl_arg<char_t, sizeof(S.data) / sizeof(char_t), S>();\n}\n#else\n/**\n * User-defined literal equivalent of `fmt::arg`.\n *\n * **Example**:\n *\n *     using namespace fmt::literals;\n *     fmt::print(\"The answer is {answer}.\", \"answer\"_a=42);\n */\nconstexpr auto operator\"\"_a(const char* s, size_t) -> detail::udl_arg<char> {\n  return {s};\n}\n#endif  // FMT_USE_NONTYPE_TEMPLATE_ARGS\n}  // namespace literals\n\n/// A fast integer formatter.\nclass format_int {\n private:\n  // Buffer should be large enough to hold all digits (digits10 + 1),\n  // a sign and a null character.\n  enum { buffer_size = std::numeric_limits<unsigned long long>::digits10 + 3 };\n  mutable char buffer_[buffer_size];\n  char* str_;\n\n  template <typename UInt>\n  FMT_CONSTEXPR20 auto format_unsigned(UInt value) -> char* {\n    auto n = static_cast<detail::uint32_or_64_or_128_t<UInt>>(value);\n    return detail::do_format_decimal(buffer_, n, buffer_size - 1);\n  }\n\n  template <typename Int>\n  FMT_CONSTEXPR20 auto format_signed(Int value) -> char* {\n    auto abs_value = static_cast<detail::uint32_or_64_or_128_t<Int>>(value);\n    bool negative = value < 0;\n    if (negative) abs_value = 0 - abs_value;\n    auto begin = format_unsigned(abs_value);\n    if (negative) *--begin = '-';\n    return begin;\n  }\n\n public:\n  FMT_CONSTEXPR20 explicit format_int(int value) : str_(format_signed(value)) {}\n  FMT_CONSTEXPR20 explicit format_int(long value)\n      : str_(format_signed(value)) {}\n  FMT_CONSTEXPR20 explicit format_int(long long value)\n      : str_(format_signed(value)) {}\n  FMT_CONSTEXPR20 explicit format_int(unsigned value)\n      : str_(format_unsigned(value)) {}\n  FMT_CONSTEXPR20 explicit format_int(unsigned long value)\n      : str_(format_unsigned(value)) {}\n  FMT_CONSTEXPR20 explicit format_int(unsigned long long value)\n      : str_(format_unsigned(value)) {}\n\n  /// Returns the number of characters written to the output buffer.\n  FMT_CONSTEXPR20 auto size() const -> size_t {\n    return detail::to_unsigned(buffer_ - str_ + buffer_size - 1);\n  }\n\n  /// Returns a pointer to the output buffer content. No terminating null\n  /// character is appended.\n  FMT_CONSTEXPR20 auto data() const -> const char* { return str_; }\n\n  /// Returns a pointer to the output buffer content with terminating null\n  /// character appended.\n  FMT_CONSTEXPR20 auto c_str() const -> const char* {\n    buffer_[buffer_size - 1] = '\\0';\n    return str_;\n  }\n\n  /// Returns the content of the output buffer as an `std::string`.\n  inline auto str() const -> std::string { return {str_, size()}; }\n};\n\n#if FMT_CLANG_ANALYZER\n#  define FMT_STRING_IMPL(s, base) s\n#else\n#  define FMT_STRING_IMPL(s, base)                                           \\\n    [] {                                                                     \\\n      /* Use the hidden visibility as a workaround for a GCC bug (#1973). */ \\\n      /* Use a macro-like name to avoid shadowing warnings. */               \\\n      struct FMT_VISIBILITY(\"hidden\") FMT_COMPILE_STRING : base {            \\\n        using char_type = fmt::remove_cvref_t<decltype(s[0])>;               \\\n        constexpr explicit operator fmt::basic_string_view<char_type>()      \\\n            const {                                                          \\\n          return fmt::detail::compile_string_to_view<char_type>(s);          \\\n        }                                                                    \\\n      };                                                                     \\\n      using FMT_STRING_VIEW =                                                \\\n          fmt::basic_string_view<typename FMT_COMPILE_STRING::char_type>;    \\\n      fmt::detail::ignore_unused(FMT_STRING_VIEW(FMT_COMPILE_STRING()));     \\\n      return FMT_COMPILE_STRING();                                           \\\n    }()\n#endif  // FMT_CLANG_ANALYZER\n\n/**\n * Constructs a legacy compile-time format string from a string literal `s`.\n *\n * **Example**:\n *\n *     // A compile-time error because 'd' is an invalid specifier for strings.\n *     std::string s = fmt::format(FMT_STRING(\"{:d}\"), \"foo\");\n */\n#define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::detail::compile_string)\n\nFMT_API auto vsystem_error(int error_code, string_view fmt, format_args args)\n    -> std::system_error;\n\n/**\n * Constructs `std::system_error` with a message formatted with\n * `fmt::format(fmt, args...)`.\n * `error_code` is a system error code as given by `errno`.\n *\n * **Example**:\n *\n *     // This throws std::system_error with the description\n *     //   cannot open file 'madeup': No such file or directory\n *     // or similar (system message may vary).\n *     const char* filename = \"madeup\";\n *     FILE* file = fopen(filename, \"r\");\n *     if (!file)\n *       throw fmt::system_error(errno, \"cannot open file '{}'\", filename);\n */\ntemplate <typename... T>\nauto system_error(int error_code, format_string<T...> fmt, T&&... args)\n    -> std::system_error {\n  return vsystem_error(error_code, fmt.str, vargs<T...>{{args...}});\n}\n\n/**\n * Formats an error message for an error returned by an operating system or a\n * language runtime, for example a file opening error, and writes it to `out`.\n * The format is the same as the one used by `std::system_error(ec, message)`\n * where `ec` is `std::error_code(error_code, std::generic_category())`.\n * It is implementation-defined but normally looks like:\n *\n *     <message>: <system-message>\n *\n * where `<message>` is the passed message and `<system-message>` is the system\n * message corresponding to the error code.\n * `error_code` is a system error code as given by `errno`.\n */\nFMT_API void format_system_error(detail::buffer<char>& out, int error_code,\n                                 const char* message) noexcept;\n\n// Reports a system error without throwing an exception.\n// Can be used to report errors from destructors.\nFMT_API void report_system_error(int error_code, const char* message) noexcept;\n\ninline auto vformat(locale_ref loc, string_view fmt, format_args args)\n    -> std::string {\n  auto buf = memory_buffer();\n  detail::vformat_to(buf, fmt, args, loc);\n  return {buf.data(), buf.size()};\n}\n\ntemplate <typename... T>\nFMT_INLINE auto format(locale_ref loc, format_string<T...> fmt, T&&... args)\n    -> std::string {\n  return vformat(loc, fmt.str, vargs<T...>{{args...}});\n}\n\ntemplate <typename OutputIt,\n          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>\nauto vformat_to(OutputIt out, locale_ref loc, string_view fmt, format_args args)\n    -> OutputIt {\n  auto&& buf = detail::get_buffer<char>(out);\n  detail::vformat_to(buf, fmt, args, loc);\n  return detail::get_iterator(buf, out);\n}\n\ntemplate <typename OutputIt, typename... T,\n          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>\nFMT_INLINE auto format_to(OutputIt out, locale_ref loc, format_string<T...> fmt,\n                          T&&... args) -> OutputIt {\n  return fmt::vformat_to(out, loc, fmt.str, vargs<T...>{{args...}});\n}\n\ntemplate <typename... T>\nFMT_NODISCARD FMT_INLINE auto formatted_size(locale_ref loc,\n                                             format_string<T...> fmt,\n                                             T&&... args) -> size_t {\n  auto buf = detail::counting_buffer<>();\n  detail::vformat_to(buf, fmt.str, vargs<T...>{{args...}}, loc);\n  return buf.count();\n}\n\nFMT_API auto vformat(string_view fmt, format_args args) -> std::string;\n\n/**\n * Formats `args` according to specifications in `fmt` and returns the result\n * as a string.\n *\n * **Example**:\n *\n *     #include <fmt/format.h>\n *     std::string message = fmt::format(\"The answer is {}.\", 42);\n */\ntemplate <typename... T>\nFMT_NODISCARD FMT_INLINE auto format(format_string<T...> fmt, T&&... args)\n    -> std::string {\n  return vformat(fmt.str, vargs<T...>{{args...}});\n}\n\n/**\n * Converts `value` to `std::string` using the default format for type `T`.\n *\n * **Example**:\n *\n *     std::string answer = fmt::to_string(42);\n */\ntemplate <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>\nFMT_NODISCARD FMT_CONSTEXPR_STRING auto to_string(T value) -> std::string {\n  // The buffer should be large enough to store the number including the sign\n  // or \"false\" for bool.\n  char buffer[max_of(detail::digits10<T>() + 2, 5)];\n  return {buffer, detail::write<char>(buffer, value)};\n}\n\ntemplate <typename T, FMT_ENABLE_IF(detail::use_format_as<T>::value)>\nFMT_NODISCARD FMT_CONSTEXPR_STRING auto to_string(const T& value)\n    -> std::string {\n  return to_string(format_as(value));\n}\n\ntemplate <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value &&\n                                    !detail::use_format_as<T>::value)>\nFMT_NODISCARD FMT_CONSTEXPR_STRING auto to_string(const T& value)\n    -> std::string {\n  auto buffer = memory_buffer();\n  detail::write<char>(appender(buffer), value);\n  return {buffer.data(), buffer.size()};\n}\n\nFMT_END_EXPORT\nFMT_END_NAMESPACE\n\n#ifdef FMT_HEADER_ONLY\n#  define FMT_FUNC inline\n#  include \"format-inl.h\"\n#endif\n\n// Restore _LIBCPP_REMOVE_TRANSITIVE_INCLUDES.\n#ifdef FMT_REMOVE_TRANSITIVE_INCLUDES\n#  undef _LIBCPP_REMOVE_TRANSITIVE_INCLUDES\n#endif\n\n#endif  // FMT_FORMAT_H_\n"
  },
  {
    "path": "include/fmt/os.h",
    "content": "// Formatting library for C++ - optional OS-specific functionality\n//\n// Copyright (c) 2012 - present, Victor Zverovich\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_OS_H_\n#define FMT_OS_H_\n\n#include \"format.h\"\n\n#ifndef FMT_MODULE\n#  include <cerrno>\n#  include <cstddef>\n#  include <cstdio>\n#  include <system_error>  // std::system_error\n\n#  if FMT_HAS_INCLUDE(<xlocale.h>)\n#    include <xlocale.h>  // LC_NUMERIC_MASK on macOS\n#  endif\n#endif  // FMT_MODULE\n\n#ifndef FMT_USE_FCNTL\n// UWP doesn't provide _pipe.\n#  if FMT_HAS_INCLUDE(\"winapifamily.h\")\n#    include <winapifamily.h>\n#  endif\n#  if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \\\n       defined(__linux__)) &&                              \\\n      (!defined(WINAPI_FAMILY) ||                          \\\n       (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)) &&    \\\n      !defined(__wasm__)\n#    include <fcntl.h>  // for O_RDONLY\n#    define FMT_USE_FCNTL 1\n#  else\n#    define FMT_USE_FCNTL 0\n#  endif\n#endif\n\n#ifndef FMT_POSIX\n#  if defined(_WIN32) && !defined(__MINGW32__)\n// Fix warnings about deprecated symbols.\n#    define FMT_POSIX(call) _##call\n#  else\n#    define FMT_POSIX(call) call\n#  endif\n#endif\n\n// Calls to system functions are wrapped in FMT_SYSTEM for testability.\n#ifdef FMT_SYSTEM\n#  define FMT_HAS_SYSTEM\n#  define FMT_POSIX_CALL(call) FMT_SYSTEM(call)\n#else\n#  define FMT_SYSTEM(call) ::call\n#  ifdef _WIN32\n// Fix warnings about deprecated symbols.\n#    define FMT_POSIX_CALL(call) ::_##call\n#  else\n#    define FMT_POSIX_CALL(call) ::call\n#  endif\n#endif\n\n// Retries the expression while it evaluates to error_result and errno\n// equals to EINTR.\n#ifndef _WIN32\n#  define FMT_RETRY_VAL(result, expression, error_result) \\\n    do {                                                  \\\n      (result) = (expression);                            \\\n    } while ((result) == (error_result) && errno == EINTR)\n#else\n#  define FMT_RETRY_VAL(result, expression, error_result) result = (expression)\n#endif\n\n#define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1)\n\nFMT_BEGIN_NAMESPACE\nFMT_BEGIN_EXPORT\n\n/**\n * A reference to a null-terminated string. It can be constructed from a C\n * string or `std::string`.\n *\n * You can use one of the following type aliases for common character types:\n *\n * +---------------+-----------------------------+\n * | Type          | Definition                  |\n * +===============+=============================+\n * | cstring_view  | basic_cstring_view<char>    |\n * +---------------+-----------------------------+\n * | wcstring_view | basic_cstring_view<wchar_t> |\n * +---------------+-----------------------------+\n *\n * This class is most useful as a parameter type for functions that wrap C APIs.\n */\ntemplate <typename Char> class basic_cstring_view {\n private:\n  const Char* data_;\n\n public:\n  /// Constructs a string reference object from a C string.\n  basic_cstring_view(const Char* s) : data_(s) {}\n\n  /// Constructs a string reference from an `std::string` object.\n  basic_cstring_view(const std::basic_string<Char>& s) : data_(s.c_str()) {}\n\n  /// Returns the pointer to a C string.\n  auto c_str() const -> const Char* { return data_; }\n};\n\nusing cstring_view = basic_cstring_view<char>;\nusing wcstring_view = basic_cstring_view<wchar_t>;\n\n#ifdef _WIN32\nFMT_API const std::error_category& system_category() noexcept;\n\nnamespace detail {\nFMT_API void format_windows_error(buffer<char>& out, int error_code,\n                                  const char* message) noexcept;\n}\n\nFMT_API std::system_error vwindows_error(int error_code, string_view fmt,\n                                         format_args args);\n\n/**\n * Constructs a `std::system_error` object with the description of the form\n *\n *     <message>: <system-message>\n *\n * where `<message>` is the formatted message and `<system-message>` is the\n * system message corresponding to the error code.\n * `error_code` is a Windows error code as given by `GetLastError`.\n * If `error_code` is not a valid error code such as -1, the system message\n * will look like \"error -1\".\n *\n * **Example**:\n *\n *     // This throws a system_error with the description\n *     //   cannot open file 'madeup': The system cannot find the file\n * specified.\n *     // or similar (system message may vary).\n *     const char *filename = \"madeup\";\n *     LPOFSTRUCT of = LPOFSTRUCT();\n *     HFILE file = OpenFile(filename, &of, OF_READ);\n *     if (file == HFILE_ERROR) {\n *       throw fmt::windows_error(GetLastError(),\n *                                \"cannot open file '{}'\", filename);\n *     }\n */\ntemplate <typename... T>\nauto windows_error(int error_code, string_view message, const T&... args)\n    -> std::system_error {\n  return vwindows_error(error_code, message, vargs<T...>{{args...}});\n}\n\n// Reports a Windows error without throwing an exception.\n// Can be used to report errors from destructors.\nFMT_API void report_windows_error(int error_code, const char* message) noexcept;\n#else\ninline auto system_category() noexcept -> const std::error_category& {\n  return std::system_category();\n}\n#endif  // _WIN32\n\n// std::system is not available on some platforms such as iOS (#2248).\n#ifdef __OSX__\ntemplate <typename S, typename... Args, typename Char = char_t<S>>\nvoid say(const S& fmt, Args&&... args) {\n  std::system(format(\"say \\\"{}\\\"\", format(fmt, args...)).c_str());\n}\n#endif\n\n// A buffered file.\nclass buffered_file {\n private:\n  FILE* file_;\n\n  friend class file;\n\n  inline explicit buffered_file(FILE* f) : file_(f) {}\n\n public:\n  buffered_file(const buffered_file&) = delete;\n  void operator=(const buffered_file&) = delete;\n\n  // Constructs a buffered_file object which doesn't represent any file.\n  inline buffered_file() noexcept : file_(nullptr) {}\n\n  // Destroys the object closing the file it represents if any.\n  FMT_API ~buffered_file() noexcept;\n\n public:\n  inline buffered_file(buffered_file&& other) noexcept : file_(other.file_) {\n    other.file_ = nullptr;\n  }\n\n  inline auto operator=(buffered_file&& other) -> buffered_file& {\n    close();\n    file_ = other.file_;\n    other.file_ = nullptr;\n    return *this;\n  }\n\n  // Opens a file.\n  FMT_API buffered_file(cstring_view filename, cstring_view mode);\n\n  // Closes the file.\n  FMT_API void close();\n\n  // Returns the pointer to a FILE object representing this file.\n  inline auto get() const noexcept -> FILE* { return file_; }\n\n  FMT_API auto descriptor() const -> int;\n\n  template <typename... T>\n  inline void print(string_view fmt, const T&... args) {\n    fmt::vargs<T...> vargs = {{args...}};\n    detail::is_locking<T...>() ? fmt::vprint_buffered(file_, fmt, vargs)\n                               : fmt::vprint(file_, fmt, vargs);\n  }\n};\n\n#if FMT_USE_FCNTL\n\n// A file. Closed file is represented by a file object with descriptor -1.\n// Methods that are not declared with noexcept may throw\n// fmt::system_error in case of failure. Note that some errors such as\n// closing the file multiple times will cause a crash on Windows rather\n// than an exception. You can get standard behavior by overriding the\n// invalid parameter handler with _set_invalid_parameter_handler.\nclass FMT_API file {\n private:\n  int fd_;  // File descriptor.\n\n  // Constructs a file object with a given descriptor.\n  explicit file(int fd) : fd_(fd) {}\n\n  friend struct pipe;\n\n public:\n  // Possible values for the oflag argument to the constructor.\n  enum {\n    RDONLY = FMT_POSIX(O_RDONLY),  // Open for reading only.\n    WRONLY = FMT_POSIX(O_WRONLY),  // Open for writing only.\n    RDWR = FMT_POSIX(O_RDWR),      // Open for reading and writing.\n    CREATE = FMT_POSIX(O_CREAT),   // Create if the file doesn't exist.\n    APPEND = FMT_POSIX(O_APPEND),  // Open in append mode.\n    TRUNC = FMT_POSIX(O_TRUNC)     // Truncate the content of the file.\n  };\n\n  // Constructs a file object which doesn't represent any file.\n  inline file() noexcept : fd_(-1) {}\n\n  // Opens a file and constructs a file object representing this file.\n  file(cstring_view path, int oflag);\n\n public:\n  file(const file&) = delete;\n  void operator=(const file&) = delete;\n\n  inline file(file&& other) noexcept : fd_(other.fd_) { other.fd_ = -1; }\n\n  // Move assignment is not noexcept because close may throw.\n  inline auto operator=(file&& other) -> file& {\n    close();\n    fd_ = other.fd_;\n    other.fd_ = -1;\n    return *this;\n  }\n\n  // Destroys the object closing the file it represents if any.\n  ~file() noexcept;\n\n  // Returns the file descriptor.\n  inline auto descriptor() const noexcept -> int { return fd_; }\n\n  // Closes the file.\n  void close();\n\n  // Returns the file size. The size has signed type for consistency with\n  // stat::st_size.\n  auto size() const -> long long;\n\n  // Attempts to read count bytes from the file into the specified buffer.\n  auto read(void* buffer, size_t count) -> size_t;\n\n  // Attempts to write count bytes from the specified buffer to the file.\n  auto write(const void* buffer, size_t count) -> size_t;\n\n  // Duplicates a file descriptor with the dup function and returns\n  // the duplicate as a file object.\n  static auto dup(int fd) -> file;\n\n  // Makes fd be the copy of this file descriptor, closing fd first if\n  // necessary.\n  void dup2(int fd);\n\n  // Makes fd be the copy of this file descriptor, closing fd first if\n  // necessary.\n  void dup2(int fd, std::error_code& ec) noexcept;\n\n  // Creates a buffered_file object associated with this file and detaches\n  // this file object from the file.\n  auto fdopen(const char* mode) -> buffered_file;\n\n#  if defined(_WIN32) && !defined(__MINGW32__)\n  // Opens a file and constructs a file object representing this file by\n  // wcstring_view filename. Windows only.\n  static file open_windows_file(wcstring_view path, int oflag);\n#  endif\n};\n\nstruct FMT_API pipe {\n  file read_end;\n  file write_end;\n\n  // Creates a pipe setting up read_end and write_end file objects for reading\n  // and writing respectively.\n  pipe();\n};\n\n// Returns the memory page size.\nauto getpagesize() -> long;\n\nnamespace detail {\n\nstruct buffer_size {\n  constexpr buffer_size() = default;\n  size_t value = 0;\n  FMT_CONSTEXPR auto operator=(size_t val) const -> buffer_size {\n    auto bs = buffer_size();\n    bs.value = val;\n    return bs;\n  }\n};\n\nstruct ostream_params {\n  int oflag = file::WRONLY | file::CREATE | file::TRUNC;\n  size_t buffer_size = BUFSIZ > 32768 ? BUFSIZ : 32768;\n\n  constexpr ostream_params() {}\n\n  template <typename... T>\n  ostream_params(T... params, int new_oflag) : ostream_params(params...) {\n    oflag = new_oflag;\n  }\n\n  template <typename... T>\n  ostream_params(T... params, detail::buffer_size bs)\n      : ostream_params(params...) {\n    this->buffer_size = bs.value;\n  }\n\n// Intel has a bug that results in failure to deduce a constructor\n// for empty parameter packs.\n#  if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 2000\n  ostream_params(int new_oflag) : oflag(new_oflag) {}\n  ostream_params(detail::buffer_size bs) : buffer_size(bs.value) {}\n#  endif\n};\n\n}  // namespace detail\n\nFMT_INLINE_VARIABLE constexpr auto buffer_size = detail::buffer_size();\n\n/// A fast buffered output stream for writing from a single thread. Writing from\n/// multiple threads without external synchronization may result in a data race.\nclass FMT_API ostream : private detail::buffer<char> {\n private:\n  file file_;\n\n  ostream(cstring_view path, const detail::ostream_params& params);\n\n  static void grow(buffer<char>& buf, size_t);\n\n public:\n  ostream(ostream&& other) noexcept;\n  ~ostream();\n\n  operator writer() {\n    detail::buffer<char>& buf = *this;\n    return buf;\n  }\n\n  inline void flush() {\n    if (size() == 0) return;\n    file_.write(data(), size() * sizeof(data()[0]));\n    clear();\n  }\n\n  template <typename... T>\n  friend auto output_file(cstring_view path, T... params) -> ostream;\n\n  inline void close() {\n    flush();\n    file_.close();\n  }\n\n  /// Formats `args` according to specifications in `fmt` and writes the\n  /// output to the file.\n  template <typename... T> void print(format_string<T...> fmt, T&&... args) {\n    vformat_to(appender(*this), fmt.str, vargs<T...>{{args...}});\n  }\n};\n\n/**\n * Opens a file for writing. Supported parameters passed in `params`:\n *\n * - `<integer>`: Flags passed to [open](\n *   https://pubs.opengroup.org/onlinepubs/007904875/functions/open.html)\n *   (`file::WRONLY | file::CREATE | file::TRUNC` by default)\n * - `buffer_size=<integer>`: Output buffer size\n *\n * **Example**:\n *\n *     auto out = fmt::output_file(\"guide.txt\");\n *     out.print(\"Don't {}\", \"Panic\");\n */\ntemplate <typename... T>\ninline auto output_file(cstring_view path, T... params) -> ostream {\n  return {path, detail::ostream_params(params...)};\n}\n#endif  // FMT_USE_FCNTL\n\nFMT_END_EXPORT\nFMT_END_NAMESPACE\n\n#endif  // FMT_OS_H_\n"
  },
  {
    "path": "include/fmt/ostream.h",
    "content": "// Formatting library for C++ - std::ostream support\n//\n// Copyright (c) 2012 - present, Victor Zverovich\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_OSTREAM_H_\n#define FMT_OSTREAM_H_\n\n#ifndef FMT_MODULE\n#  include <fstream>  // std::filebuf\n#endif\n\n#ifdef _WIN32\n#  ifdef __GLIBCXX__\n#    include <ext/stdio_filebuf.h>\n#    include <ext/stdio_sync_filebuf.h>\n#  endif\n#  include <io.h>\n#endif\n\n#include \"chrono.h\"  // formatbuf\n\n#ifdef _MSVC_STL_UPDATE\n#  define FMT_MSVC_STL_UPDATE _MSVC_STL_UPDATE\n#elif defined(_MSC_VER) && _MSC_VER < 1912  // VS 15.5\n#  define FMT_MSVC_STL_UPDATE _MSVC_LANG\n#else\n#  define FMT_MSVC_STL_UPDATE 0\n#endif\n\nFMT_BEGIN_NAMESPACE\nnamespace detail {\n\n// Generate a unique explicit instantiation in every translation unit using a\n// tag type in an anonymous namespace.\nnamespace {\nstruct file_access_tag {};\n}  // namespace\ntemplate <typename Tag, typename BufType, FILE* BufType::*FileMemberPtr>\nclass file_access {\n  friend auto get_file(BufType& obj) -> FILE* { return obj.*FileMemberPtr; }\n};\n\n#if FMT_MSVC_STL_UPDATE\ntemplate class file_access<file_access_tag, std::filebuf,\n                           &std::filebuf::_Myfile>;\nauto get_file(std::filebuf&) -> FILE*;\n#endif\n\n// Write the content of buf to os.\n// It is a separate function rather than a part of vprint to simplify testing.\ntemplate <typename Char>\nvoid write_buffer(std::basic_ostream<Char>& os, buffer<Char>& buf) {\n  const Char* buf_data = buf.data();\n  using unsigned_streamsize = make_unsigned_t<std::streamsize>;\n  unsigned_streamsize size = buf.size();\n  unsigned_streamsize max_size = to_unsigned(max_value<std::streamsize>());\n  do {\n    unsigned_streamsize n = size <= max_size ? size : max_size;\n    os.write(buf_data, static_cast<std::streamsize>(n));\n    buf_data += n;\n    size -= n;\n  } while (size != 0);\n}\n\ntemplate <typename T> struct streamed_view {\n  const T& value;\n};\n}  // namespace detail\n\n// Formats an object of type T that has an overloaded ostream operator<<.\ntemplate <typename Char>\nstruct basic_ostream_formatter : formatter<basic_string_view<Char>, Char> {\n  void set_debug_format() = delete;\n\n  template <typename T, typename Context>\n  auto format(const T& value, Context& ctx) const -> decltype(ctx.out()) {\n    auto buffer = basic_memory_buffer<Char>();\n    auto&& formatbuf = detail::formatbuf<std::basic_streambuf<Char>>(buffer);\n    auto&& output = std::basic_ostream<Char>(&formatbuf);\n    output.imbue(std::locale::classic());  // The default is always unlocalized.\n    output << value;\n    output.exceptions(std::ios_base::failbit | std::ios_base::badbit);\n    return formatter<basic_string_view<Char>, Char>::format(\n        {buffer.data(), buffer.size()}, ctx);\n  }\n};\n\nusing ostream_formatter = basic_ostream_formatter<char>;\n\ntemplate <typename T, typename Char>\nstruct formatter<detail::streamed_view<T>, Char>\n    : basic_ostream_formatter<Char> {\n  template <typename Context>\n  auto format(detail::streamed_view<T> view, Context& ctx) const\n      -> decltype(ctx.out()) {\n    return basic_ostream_formatter<Char>::format(view.value, ctx);\n  }\n};\n\n/**\n * Returns a view that formats `value` via an ostream `operator<<`.\n *\n * **Example**:\n *\n *     fmt::print(\"Current thread id: {}\\n\",\n *                fmt::streamed(std::this_thread::get_id()));\n */\ntemplate <typename T>\nconstexpr auto streamed(const T& value) -> detail::streamed_view<T> {\n  return {value};\n}\n\ninline void vprint(std::ostream& os, string_view fmt, format_args args) {\n  auto buffer = memory_buffer();\n  detail::vformat_to(buffer, fmt, args);\n  FILE* f = nullptr;\n#if FMT_MSVC_STL_UPDATE && FMT_USE_RTTI\n  if (auto* buf = dynamic_cast<std::filebuf*>(os.rdbuf()))\n    f = detail::get_file(*buf);\n#elif defined(_WIN32) && defined(__GLIBCXX__) && FMT_USE_RTTI\n  auto* rdbuf = os.rdbuf();\n  if (auto* sfbuf = dynamic_cast<__gnu_cxx::stdio_sync_filebuf<char>*>(rdbuf))\n    f = sfbuf->file();\n  else if (auto* fbuf = dynamic_cast<__gnu_cxx::stdio_filebuf<char>*>(rdbuf))\n    f = fbuf->file();\n#endif\n#ifdef _WIN32\n  if (f) {\n    int fd = _fileno(f);\n    if (_isatty(fd)) {\n      os.flush();\n      if (detail::write_console(fd, {buffer.data(), buffer.size()})) return;\n    }\n  }\n#endif\n  detail::ignore_unused(f);\n  detail::write_buffer(os, buffer);\n}\n\n/**\n * Prints formatted data to the stream `os`.\n *\n * **Example**:\n *\n *     fmt::print(cerr, \"Don't {}!\", \"panic\");\n */\nFMT_EXPORT template <typename... T>\nvoid print(std::ostream& os, format_string<T...> fmt, T&&... args) {\n  fmt::vargs<T...> vargs = {{args...}};\n  if (detail::const_check(detail::use_utf8)) return vprint(os, fmt.str, vargs);\n  auto buffer = memory_buffer();\n  detail::vformat_to(buffer, fmt.str, vargs);\n  detail::write_buffer(os, buffer);\n}\n\nFMT_EXPORT template <typename... T>\nvoid println(std::ostream& os, format_string<T...> fmt, T&&... args) {\n  fmt::print(os, FMT_STRING(\"{}\\n\"),\n             fmt::format(fmt, std::forward<T>(args)...));\n}\n\nFMT_END_NAMESPACE\n\n#endif  // FMT_OSTREAM_H_\n"
  },
  {
    "path": "include/fmt/printf.h",
    "content": "// Formatting library for C++ - legacy printf implementation\n//\n// Copyright (c) 2012 - 2016, Victor Zverovich\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_PRINTF_H_\n#define FMT_PRINTF_H_\n\n#ifndef FMT_MODULE\n#  include <algorithm>  // std::find\n#  include <limits>     // std::numeric_limits\n#endif\n\n#include \"format.h\"\n\nFMT_BEGIN_NAMESPACE\nFMT_BEGIN_EXPORT\n\ntemplate <typename Char> class basic_printf_context {\n private:\n  basic_appender<Char> out_;\n  basic_format_args<basic_printf_context> args_;\n\n  static_assert(std::is_same<Char, char>::value ||\n                    std::is_same<Char, wchar_t>::value,\n                \"Unsupported code unit type.\");\n\n public:\n  using char_type = Char;\n  enum { builtin_types = 1 };\n\n  /// Constructs a `printf_context` object. References to the arguments are\n  /// stored in the context object so make sure they have appropriate lifetimes.\n  basic_printf_context(basic_appender<Char> out,\n                       basic_format_args<basic_printf_context> args)\n      : out_(out), args_(args) {}\n\n  auto out() -> basic_appender<Char> { return out_; }\n  void advance_to(basic_appender<Char>) {}\n\n  auto locale() -> locale_ref { return {}; }\n\n  auto arg(int id) const -> basic_format_arg<basic_printf_context> {\n    return args_.get(id);\n  }\n};\n\nnamespace detail {\n\n// Return the result via the out param to workaround gcc bug 77539.\ntemplate <bool IS_CONSTEXPR, typename T, typename Ptr = const T*>\nFMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr& out) -> bool {\n  for (out = first; out != last; ++out) {\n    if (*out == value) return true;\n  }\n  return false;\n}\n\ntemplate <>\ninline auto find<false, char>(const char* first, const char* last, char value,\n                              const char*& out) -> bool {\n  out =\n      static_cast<const char*>(memchr(first, value, to_unsigned(last - first)));\n  return out != nullptr;\n}\n\n// Checks if a value fits in int - used to avoid warnings about comparing\n// signed and unsigned integers.\ntemplate <bool IS_SIGNED> struct int_checker {\n  template <typename T> static auto fits_in_int(T value) -> bool {\n    return value <= to_unsigned(max_value<int>());\n  }\n  inline static auto fits_in_int(bool) -> bool { return true; }\n};\n\ntemplate <> struct int_checker<true> {\n  template <typename T> static auto fits_in_int(T value) -> bool {\n    return value >= (std::numeric_limits<int>::min)() &&\n           value <= max_value<int>();\n  }\n  inline static auto fits_in_int(int) -> bool { return true; }\n};\n\nstruct printf_precision_handler {\n  template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>\n  auto operator()(T value) -> int {\n    if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value))\n      report_error(\"number is too big\");\n    return max_of(static_cast<int>(value), 0);\n  }\n\n  template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>\n  auto operator()(T) -> int {\n    report_error(\"precision is not integer\");\n    return 0;\n  }\n};\n\n// An argument visitor that returns true iff arg is a zero integer.\nstruct is_zero_int {\n  template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>\n  auto operator()(T value) -> bool {\n    return value == 0;\n  }\n\n  template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>\n  auto operator()(T) -> bool {\n    return false;\n  }\n};\n\ntemplate <typename T> struct make_unsigned_or_bool : std::make_unsigned<T> {};\n\ntemplate <> struct make_unsigned_or_bool<bool> {\n  using type = bool;\n};\n\ntemplate <typename T, typename Context> class arg_converter {\n private:\n  using char_type = typename Context::char_type;\n\n  basic_format_arg<Context>& arg_;\n  char_type type_;\n\n public:\n  arg_converter(basic_format_arg<Context>& arg, char_type type)\n      : arg_(arg), type_(type) {}\n\n  void operator()(bool value) {\n    if (type_ != 's') operator()<bool>(value);\n  }\n\n  template <typename U, FMT_ENABLE_IF(std::is_integral<U>::value)>\n  void operator()(U value) {\n    bool is_signed = type_ == 'd' || type_ == 'i';\n    using target_type = conditional_t<std::is_same<T, void>::value, U, T>;\n    if (const_check(sizeof(target_type) <= sizeof(int))) {\n      // Extra casts are used to silence warnings.\n      using unsigned_type = typename make_unsigned_or_bool<target_type>::type;\n      if (is_signed)\n        arg_ = static_cast<int>(static_cast<target_type>(value));\n      else\n        arg_ = static_cast<unsigned>(static_cast<unsigned_type>(value));\n    } else {\n      // glibc's printf doesn't sign extend arguments of smaller types:\n      //   std::printf(\"%lld\", -42);  // prints \"4294967254\"\n      // but we don't have to do the same because it's a UB.\n      if (is_signed)\n        arg_ = static_cast<long long>(value);\n      else\n        arg_ = static_cast<typename make_unsigned_or_bool<U>::type>(value);\n    }\n  }\n\n  template <typename U, FMT_ENABLE_IF(!std::is_integral<U>::value)>\n  void operator()(U) {}  // No conversion needed for non-integral types.\n};\n\n// Converts an integer argument to T for printf, if T is an integral type.\n// If T is void, the argument is converted to corresponding signed or unsigned\n// type depending on the type specifier: 'd' and 'i' - signed, other -\n// unsigned).\ntemplate <typename T, typename Context, typename Char>\nvoid convert_arg(basic_format_arg<Context>& arg, Char type) {\n  arg.visit(arg_converter<T, Context>(arg, type));\n}\n\n// Converts an integer argument to char for printf.\ntemplate <typename Context> class char_converter {\n private:\n  basic_format_arg<Context>& arg_;\n\n public:\n  explicit char_converter(basic_format_arg<Context>& arg) : arg_(arg) {}\n\n  template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>\n  void operator()(T value) {\n    arg_ = static_cast<typename Context::char_type>(value);\n  }\n\n  template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>\n  void operator()(T) {}  // No conversion needed for non-integral types.\n};\n\n// An argument visitor that return a pointer to a C string if argument is a\n// string or null otherwise.\ntemplate <typename Char> struct get_cstring {\n  template <typename T> auto operator()(T) -> const Char* { return nullptr; }\n  auto operator()(const Char* s) -> const Char* { return s; }\n};\n\n// Checks if an argument is a valid printf width specifier and sets\n// left alignment if it is negative.\nclass printf_width_handler {\n private:\n  format_specs& specs_;\n\n public:\n  inline explicit printf_width_handler(format_specs& specs) : specs_(specs) {}\n\n  template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>\n  auto operator()(T value) -> unsigned {\n    auto width = static_cast<uint32_or_64_or_128_t<T>>(value);\n    if (detail::is_negative(value)) {\n      specs_.set_align(align::left);\n      width = 0 - width;\n    }\n    unsigned int_max = to_unsigned(max_value<int>());\n    if (width > int_max) report_error(\"number is too big\");\n    return static_cast<unsigned>(width);\n  }\n\n  template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>\n  auto operator()(T) -> unsigned {\n    report_error(\"width is not integer\");\n    return 0;\n  }\n};\n\n// Workaround for a bug with the XL compiler when initializing\n// printf_arg_formatter's base class.\ntemplate <typename Char>\nauto make_arg_formatter(basic_appender<Char> iter, format_specs& s)\n    -> arg_formatter<Char> {\n  return {iter, s, locale_ref()};\n}\n\n// The `printf` argument formatter.\ntemplate <typename Char>\nclass printf_arg_formatter : public arg_formatter<Char> {\n private:\n  using base = arg_formatter<Char>;\n  using context_type = basic_printf_context<Char>;\n\n  context_type& context_;\n\n  void write_null_pointer(bool is_string = false) {\n    auto s = this->specs;\n    s.set_type(presentation_type::none);\n    write_bytes<Char>(this->out, is_string ? \"(null)\" : \"(nil)\", s);\n  }\n\n  template <typename T> void write(T value) {\n    detail::write<Char>(this->out, value, this->specs, this->locale);\n  }\n\n public:\n  printf_arg_formatter(basic_appender<Char> iter, format_specs& s,\n                       context_type& ctx)\n      : base(make_arg_formatter(iter, s)), context_(ctx) {}\n\n  void operator()(monostate value) { write(value); }\n\n  template <typename T, FMT_ENABLE_IF(detail::is_integral<T>::value)>\n  void operator()(T value) {\n    // MSVC2013 fails to compile separate overloads for bool and Char so use\n    // std::is_same instead.\n    if (!std::is_same<T, Char>::value) {\n      write(value);\n      return;\n    }\n    format_specs s = this->specs;\n    if (s.type() != presentation_type::none &&\n        s.type() != presentation_type::chr) {\n      return (*this)(static_cast<int>(value));\n    }\n    s.set_sign(sign::none);\n    s.clear_alt();\n    s.set_fill(' ');  // Ignore '0' flag for char types.\n    // align::numeric needs to be overwritten here since the '0' flag is\n    // ignored for non-numeric types\n    if (s.align() == align::none || s.align() == align::numeric)\n      s.set_align(align::right);\n    detail::write<Char>(this->out, static_cast<Char>(value), s);\n  }\n\n  template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>\n  void operator()(T value) {\n    write(value);\n  }\n\n  void operator()(const char* value) {\n    if (value)\n      write(value);\n    else\n      write_null_pointer(this->specs.type() != presentation_type::pointer);\n  }\n\n  void operator()(const wchar_t* value) {\n    if (value)\n      write(value);\n    else\n      write_null_pointer(this->specs.type() != presentation_type::pointer);\n  }\n\n  void operator()(basic_string_view<Char> value) { write(value); }\n\n  void operator()(const void* value) {\n    if (value)\n      write(value);\n    else\n      write_null_pointer();\n  }\n\n  void operator()(typename basic_format_arg<context_type>::handle handle) {\n    auto parse_ctx = parse_context<Char>({});\n    handle.format(parse_ctx, context_);\n  }\n};\n\ntemplate <typename Char>\nvoid parse_flags(format_specs& specs, const Char*& it, const Char* end) {\n  for (; it != end; ++it) {\n    switch (*it) {\n    case '-': specs.set_align(align::left); break;\n    case '+': specs.set_sign(sign::plus); break;\n    case '0': specs.set_fill('0'); break;\n    case ' ':\n      if (specs.sign() != sign::plus) specs.set_sign(sign::space);\n      break;\n    case '#': specs.set_alt(); break;\n    default:  return;\n    }\n  }\n}\n\ntemplate <typename Char, typename GetArg>\nauto parse_header(const Char*& it, const Char* end, format_specs& specs,\n                  GetArg get_arg) -> int {\n  int arg_index = -1;\n  Char c = *it;\n  if (c >= '0' && c <= '9') {\n    // Parse an argument index (if followed by '$') or a width possibly\n    // preceded with '0' flag(s).\n    int value = parse_nonnegative_int(it, end, -1);\n    if (it != end && *it == '$') {  // value is an argument index\n      ++it;\n      arg_index = value != -1 ? value : max_value<int>();\n    } else {\n      if (c == '0') specs.set_fill('0');\n      if (value != 0) {\n        // Nonzero value means that we parsed width and don't need to\n        // parse it or flags again, so return now.\n        if (value == -1) report_error(\"number is too big\");\n        specs.width = value;\n        return arg_index;\n      }\n    }\n  }\n  parse_flags(specs, it, end);\n  // Parse width.\n  if (it != end) {\n    if (*it >= '0' && *it <= '9') {\n      specs.width = parse_nonnegative_int(it, end, -1);\n      if (specs.width == -1) report_error(\"number is too big\");\n    } else if (*it == '*') {\n      ++it;\n      specs.width = static_cast<int>(\n          get_arg(-1).visit(detail::printf_width_handler(specs)));\n    }\n  }\n  return arg_index;\n}\n\ninline auto parse_printf_presentation_type(char c, type t, bool& upper)\n    -> presentation_type {\n  using pt = presentation_type;\n  constexpr auto integral_set = sint_set | uint_set | bool_set | char_set;\n  switch (c) {\n  case 'd': return in(t, integral_set) ? pt::dec : pt::none;\n  case 'o': return in(t, integral_set) ? pt::oct : pt::none;\n  case 'X': upper = true; FMT_FALLTHROUGH;\n  case 'x': return in(t, integral_set) ? pt::hex : pt::none;\n  case 'E': upper = true; FMT_FALLTHROUGH;\n  case 'e': return in(t, float_set) ? pt::exp : pt::none;\n  case 'F': upper = true; FMT_FALLTHROUGH;\n  case 'f': return in(t, float_set) ? pt::fixed : pt::none;\n  case 'G': upper = true; FMT_FALLTHROUGH;\n  case 'g': return in(t, float_set) ? pt::general : pt::none;\n  case 'A': upper = true; FMT_FALLTHROUGH;\n  case 'a': return in(t, float_set) ? pt::hexfloat : pt::none;\n  case 'c': return in(t, integral_set) ? pt::chr : pt::none;\n  case 's': return in(t, string_set | cstring_set) ? pt::string : pt::none;\n  case 'p': return in(t, pointer_set | cstring_set) ? pt::pointer : pt::none;\n  default:  return pt::none;\n  }\n}\n\ntemplate <typename Char, typename Context>\nvoid vprintf(buffer<Char>& buf, basic_string_view<Char> format,\n             basic_format_args<Context> args) {\n  using iterator = basic_appender<Char>;\n  auto out = iterator(buf);\n  auto context = basic_printf_context<Char>(out, args);\n  auto parse_ctx = parse_context<Char>(format);\n\n  // Returns the argument with specified index or, if arg_index is -1, the next\n  // argument.\n  auto get_arg = [&](int arg_index) {\n    if (arg_index < 0)\n      arg_index = parse_ctx.next_arg_id();\n    else\n      parse_ctx.check_arg_id(--arg_index);\n    auto arg = context.arg(arg_index);\n    if (!arg) report_error(\"argument not found\");\n    return arg;\n  };\n\n  const Char* start = parse_ctx.begin();\n  const Char* end = parse_ctx.end();\n  auto it = start;\n  while (it != end) {\n    if (!find<false, Char>(it, end, '%', it)) {\n      it = end;  // find leaves it == nullptr if it doesn't find '%'.\n      break;\n    }\n    Char c = *it++;\n    if (it != end && *it == c) {\n      write(out, basic_string_view<Char>(start, to_unsigned(it - start)));\n      start = ++it;\n      continue;\n    }\n    write(out, basic_string_view<Char>(start, to_unsigned(it - 1 - start)));\n\n    auto specs = format_specs();\n    specs.set_align(align::right);\n\n    // Parse argument index, flags and width.\n    int arg_index = parse_header(it, end, specs, get_arg);\n    if (arg_index == 0) report_error(\"argument not found\");\n\n    // Parse precision.\n    if (it != end && *it == '.') {\n      ++it;\n      c = it != end ? *it : 0;\n      if ('0' <= c && c <= '9') {\n        specs.precision = parse_nonnegative_int(it, end, 0);\n      } else if (c == '*') {\n        ++it;\n        specs.precision =\n            static_cast<int>(get_arg(-1).visit(printf_precision_handler()));\n      } else {\n        specs.precision = 0;\n      }\n    }\n\n    auto arg = get_arg(arg_index);\n    // For d, i, o, u, x, and X conversion specifiers, if a precision is\n    // specified, the '0' flag is ignored\n    if (specs.precision >= 0 && is_integral_type(arg.type())) {\n      // Ignore '0' for non-numeric types or if '-' present.\n      specs.set_fill(' ');\n    }\n    if (specs.precision >= 0 && arg.type() == type::cstring_type) {\n      auto str = arg.visit(get_cstring<Char>());\n      auto str_end = str + specs.precision;\n      auto nul = std::find(str, str_end, Char());\n      auto sv = basic_string_view<Char>(\n          str, to_unsigned(nul != str_end ? nul - str : specs.precision));\n      arg = sv;\n    }\n    if (specs.alt() && arg.visit(is_zero_int())) specs.clear_alt();\n    if (specs.fill_unit<Char>() == '0') {\n      if (is_arithmetic_type(arg.type()) && specs.align() != align::left) {\n        specs.set_align(align::numeric);\n      } else {\n        // Ignore '0' flag for non-numeric types or if '-' flag is also present.\n        specs.set_fill(' ');\n      }\n    }\n\n    // Parse length and convert the argument to the required type.\n    c = it != end ? *it++ : 0;\n    Char t = it != end ? *it : 0;\n    switch (c) {\n    case 'h':\n      if (t == 'h') {\n        ++it;\n        t = it != end ? *it : 0;\n        convert_arg<signed char>(arg, t);\n      } else {\n        convert_arg<short>(arg, t);\n      }\n      break;\n    case 'l':\n      if (t == 'l') {\n        ++it;\n        t = it != end ? *it : 0;\n        convert_arg<long long>(arg, t);\n      } else {\n        convert_arg<long>(arg, t);\n      }\n      break;\n    case 'j': convert_arg<intmax_t>(arg, t); break;\n    case 'z': convert_arg<size_t>(arg, t); break;\n    case 't': convert_arg<std::ptrdiff_t>(arg, t); break;\n    case 'L':\n      // printf produces garbage when 'L' is omitted for long double, no\n      // need to do the same.\n      break;\n    default: --it; convert_arg<void>(arg, c);\n    }\n\n    // Parse type.\n    if (it == end) report_error(\"invalid format string\");\n    char type = static_cast<char>(*it++);\n    if (is_integral_type(arg.type())) {\n      // Normalize type.\n      switch (type) {\n      case 'i':\n      case 'u': type = 'd'; break;\n      case 'c':\n        arg.visit(char_converter<basic_printf_context<Char>>(arg));\n        break;\n      }\n    }\n    bool upper = false;\n    specs.set_type(parse_printf_presentation_type(type, arg.type(), upper));\n    if (specs.type() == presentation_type::none)\n      report_error(\"invalid format specifier\");\n    if (upper) specs.set_upper();\n\n    start = it;\n\n    // Format argument.\n    arg.visit(printf_arg_formatter<Char>(out, specs, context));\n  }\n  write(out, basic_string_view<Char>(start, to_unsigned(it - start)));\n}\n}  // namespace detail\n\nusing printf_context = basic_printf_context<char>;\nusing wprintf_context = basic_printf_context<wchar_t>;\n\nusing printf_args = basic_format_args<printf_context>;\nusing wprintf_args = basic_format_args<wprintf_context>;\n\n/// Constructs an `format_arg_store` object that contains references to\n/// arguments and can be implicitly converted to `printf_args`.\ntemplate <typename Char = char, typename... T>\ninline auto make_printf_args(T&... args)\n    -> decltype(fmt::make_format_args<basic_printf_context<Char>>(args...)) {\n  return fmt::make_format_args<basic_printf_context<Char>>(args...);\n}\n\ntemplate <typename Char> struct vprintf_args {\n  using type = basic_format_args<basic_printf_context<Char>>;\n};\n\ntemplate <typename Char>\ninline auto vsprintf(basic_string_view<Char> fmt,\n                     typename vprintf_args<Char>::type args)\n    -> std::basic_string<Char> {\n  auto buf = basic_memory_buffer<Char>();\n  detail::vprintf(buf, fmt, args);\n  return {buf.data(), buf.size()};\n}\n\n/**\n * Formats `args` according to specifications in `fmt` and returns the result\n * as as string.\n *\n * **Example**:\n *\n *     std::string message = fmt::sprintf(\"The answer is %d\", 42);\n */\ntemplate <typename... T>\ninline auto sprintf(string_view fmt, const T&... args) -> std::string {\n  return vsprintf(fmt, make_printf_args(args...));\n}\ntemplate <typename... T>\nFMT_DEPRECATED auto sprintf(basic_string_view<wchar_t> fmt, const T&... args)\n    -> std::wstring {\n  return vsprintf(fmt, make_printf_args<wchar_t>(args...));\n}\n\ntemplate <typename Char>\nauto vfprintf(std::FILE* f, basic_string_view<Char> fmt,\n              typename vprintf_args<Char>::type args) -> int {\n  auto buf = basic_memory_buffer<Char>();\n  detail::vprintf(buf, fmt, args);\n  size_t size = buf.size();\n  return std::fwrite(buf.data(), sizeof(Char), size, f) < size\n             ? -1\n             : static_cast<int>(size);\n}\n\n/**\n * Formats `args` according to specifications in `fmt` and writes the output\n * to `f`.\n *\n * **Example**:\n *\n *     fmt::fprintf(stderr, \"Don't %s!\", \"panic\");\n */\ntemplate <typename... T>\ninline auto fprintf(std::FILE* f, string_view fmt, const T&... args) -> int {\n  return vfprintf(f, fmt, make_printf_args(args...));\n}\ntemplate <typename... T>\nFMT_DEPRECATED auto fprintf(std::FILE* f, basic_string_view<wchar_t> fmt,\n                            const T&... args) -> int {\n  return vfprintf(f, fmt, make_printf_args<wchar_t>(args...));\n}\n\n/**\n * Formats `args` according to specifications in `fmt` and writes the output\n * to `stdout`.\n *\n * **Example**:\n *\n *   fmt::printf(\"Elapsed time: %.2f seconds\", 1.23);\n */\ntemplate <typename... T>\ninline auto printf(string_view fmt, const T&... args) -> int {\n  return vfprintf(stdout, fmt, make_printf_args(args...));\n}\n\nFMT_END_EXPORT\nFMT_END_NAMESPACE\n\n#endif  // FMT_PRINTF_H_\n"
  },
  {
    "path": "include/fmt/ranges.h",
    "content": "// Formatting library for C++ - range and tuple support\n//\n// Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_RANGES_H_\n#define FMT_RANGES_H_\n\n#ifndef FMT_MODULE\n#  include <initializer_list>\n#  include <iterator>\n#  include <tuple>\n#  include <type_traits>\n#  include <utility>\n#endif\n\n#include \"format.h\"\n\nFMT_BEGIN_NAMESPACE\n\nFMT_EXPORT\nenum class range_format { disabled, map, set, sequence, string, debug_string };\n\nnamespace detail {\n\ntemplate <typename T> class is_map {\n  template <typename U> static auto check(U*) -> typename U::mapped_type;\n  template <typename> static void check(...);\n\n public:\n  static constexpr bool value =\n      !std::is_void<decltype(check<T>(nullptr))>::value;\n};\n\ntemplate <typename T> class is_set {\n  template <typename U> static auto check(U*) -> typename U::key_type;\n  template <typename> static void check(...);\n\n public:\n  static constexpr bool value =\n      !std::is_void<decltype(check<T>(nullptr))>::value && !is_map<T>::value;\n};\n\n// C array overload\ntemplate <typename T, size_t N>\nauto range_begin(const T (&arr)[N]) -> const T* {\n  return arr;\n}\ntemplate <typename T, size_t N> auto range_end(const T (&arr)[N]) -> const T* {\n  return arr + N;\n}\n\ntemplate <typename T, typename Enable = void>\nstruct has_member_fn_begin_end_t : std::false_type {};\n\ntemplate <typename T>\nstruct has_member_fn_begin_end_t<T, void_t<decltype(*std::declval<T>().begin()),\n                                           decltype(std::declval<T>().end())>>\n    : std::true_type {};\n\n// Member function overloads.\ntemplate <typename T>\nauto range_begin(T&& rng) -> decltype(static_cast<T&&>(rng).begin()) {\n  return static_cast<T&&>(rng).begin();\n}\ntemplate <typename T>\nauto range_end(T&& rng) -> decltype(static_cast<T&&>(rng).end()) {\n  return static_cast<T&&>(rng).end();\n}\n\n// ADL overloads. Only participate in overload resolution if member functions\n// are not found.\ntemplate <typename T>\nauto range_begin(T&& rng)\n    -> enable_if_t<!has_member_fn_begin_end_t<T&&>::value,\n                   decltype(begin(static_cast<T&&>(rng)))> {\n  return begin(static_cast<T&&>(rng));\n}\ntemplate <typename T>\nauto range_end(T&& rng) -> enable_if_t<!has_member_fn_begin_end_t<T&&>::value,\n                                       decltype(end(static_cast<T&&>(rng)))> {\n  return end(static_cast<T&&>(rng));\n}\n\ntemplate <typename T, typename Enable = void>\nstruct has_const_begin_end : std::false_type {};\ntemplate <typename T, typename Enable = void>\nstruct has_mutable_begin_end : std::false_type {};\n\ntemplate <typename T>\nstruct has_const_begin_end<\n    T, void_t<decltype(*detail::range_begin(\n                  std::declval<const remove_cvref_t<T>&>())),\n              decltype(detail::range_end(\n                  std::declval<const remove_cvref_t<T>&>()))>>\n    : std::true_type {};\n\ntemplate <typename T>\nstruct has_mutable_begin_end<\n    T, void_t<decltype(*detail::range_begin(std::declval<T&>())),\n              decltype(detail::range_end(std::declval<T&>())),\n              // the extra int here is because older versions of MSVC don't\n              // SFINAE properly unless there are distinct types\n              int>> : std::true_type {};\n\ntemplate <typename T, typename _ = void> struct is_range_ : std::false_type {};\ntemplate <typename T>\nstruct is_range_<T, void>\n    : std::integral_constant<bool, (has_const_begin_end<T>::value ||\n                                    has_mutable_begin_end<T>::value)> {};\n\n// tuple_size and tuple_element check.\ntemplate <typename T> class is_tuple_like_ {\n  template <typename U, typename V = typename std::remove_cv<U>::type>\n  static auto check(U* p) -> decltype(std::tuple_size<V>::value, 0);\n  template <typename> static void check(...);\n\n public:\n  static constexpr bool value =\n      !std::is_void<decltype(check<T>(nullptr))>::value;\n};\n\n// Check for integer_sequence\n#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VERSION >= 1900\ntemplate <typename T, T... N>\nusing integer_sequence = std::integer_sequence<T, N...>;\ntemplate <size_t... N> using index_sequence = std::index_sequence<N...>;\ntemplate <size_t N> using make_index_sequence = std::make_index_sequence<N>;\n#else\ntemplate <typename T, T... N> struct integer_sequence {\n  using value_type = T;\n\n  static FMT_CONSTEXPR auto size() -> size_t { return sizeof...(N); }\n};\n\ntemplate <size_t... N> using index_sequence = integer_sequence<size_t, N...>;\n\ntemplate <typename T, size_t N, T... Ns>\nstruct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> {};\ntemplate <typename T, T... Ns>\nstruct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> {};\n\ntemplate <size_t N>\nusing make_index_sequence = make_integer_sequence<size_t, N>;\n#endif\n\ntemplate <typename T>\nusing tuple_index_sequence = make_index_sequence<std::tuple_size<T>::value>;\n\ntemplate <typename T, typename C, bool = is_tuple_like_<T>::value>\nclass is_tuple_formattable_ {\n public:\n  static constexpr bool value = false;\n};\ntemplate <typename T, typename C> class is_tuple_formattable_<T, C, true> {\n  template <size_t... Is>\n  static auto all_true(index_sequence<Is...>,\n                       integer_sequence<bool, (Is >= 0)...>) -> std::true_type;\n  static auto all_true(...) -> std::false_type;\n\n  template <size_t... Is>\n  static auto check(index_sequence<Is...>) -> decltype(all_true(\n      index_sequence<Is...>{},\n      integer_sequence<bool,\n                       (is_formattable<typename std::tuple_element<Is, T>::type,\n                                       C>::value)...>{}));\n\n public:\n  static constexpr bool value =\n      decltype(check(tuple_index_sequence<T>{}))::value;\n};\n\ntemplate <typename Tuple, typename F, size_t... Is>\nFMT_CONSTEXPR void for_each(index_sequence<Is...>, Tuple&& t, F&& f) {\n  using std::get;\n  // Using a free function get<Is>(Tuple) now.\n  const int unused[] = {0, ((void)f(get<Is>(t)), 0)...};\n  ignore_unused(unused);\n}\n\ntemplate <typename Tuple, typename F>\nFMT_CONSTEXPR void for_each(Tuple&& t, F&& f) {\n  for_each(tuple_index_sequence<remove_cvref_t<Tuple>>(),\n           std::forward<Tuple>(t), std::forward<F>(f));\n}\n\ntemplate <typename Tuple1, typename Tuple2, typename F, size_t... Is>\nvoid for_each2(index_sequence<Is...>, Tuple1&& t1, Tuple2&& t2, F&& f) {\n  using std::get;\n  const int unused[] = {0, ((void)f(get<Is>(t1), get<Is>(t2)), 0)...};\n  ignore_unused(unused);\n}\n\ntemplate <typename Tuple1, typename Tuple2, typename F>\nvoid for_each2(Tuple1&& t1, Tuple2&& t2, F&& f) {\n  for_each2(tuple_index_sequence<remove_cvref_t<Tuple1>>(),\n            std::forward<Tuple1>(t1), std::forward<Tuple2>(t2),\n            std::forward<F>(f));\n}\n\nnamespace tuple {\n// Workaround a bug in MSVC 2019 (v140).\ntemplate <typename Char, typename... T>\nusing result_t = std::tuple<formatter<remove_cvref_t<T>, Char>...>;\n\nusing std::get;\ntemplate <typename Tuple, typename Char, size_t... Is>\nauto get_formatters(index_sequence<Is...>)\n    -> result_t<Char, decltype(get<Is>(std::declval<Tuple>()))...>;\n}  // namespace tuple\n\n#if FMT_MSC_VERSION && FMT_MSC_VERSION < 1920\n// Older MSVC doesn't get the reference type correctly for arrays.\ntemplate <typename R> struct range_reference_type_impl {\n  using type = decltype(*detail::range_begin(std::declval<R&>()));\n};\n\ntemplate <typename T, size_t N> struct range_reference_type_impl<T[N]> {\n  using type = T&;\n};\n\ntemplate <typename T>\nusing range_reference_type = typename range_reference_type_impl<T>::type;\n#else\ntemplate <typename Range>\nusing range_reference_type =\n    decltype(*detail::range_begin(std::declval<Range&>()));\n#endif\n\n// We don't use the Range's value_type for anything, but we do need the Range's\n// reference type, with cv-ref stripped.\ntemplate <typename Range>\nusing uncvref_type = remove_cvref_t<range_reference_type<Range>>;\n\ntemplate <typename Formatter>\nFMT_CONSTEXPR auto maybe_set_debug_format(Formatter& f, bool set)\n    -> decltype(f.set_debug_format(set)) {\n  f.set_debug_format(set);\n}\ntemplate <typename Formatter>\nFMT_CONSTEXPR void maybe_set_debug_format(Formatter&, ...) {}\n\ntemplate <typename T>\nstruct range_format_kind_\n    : std::integral_constant<range_format,\n                             std::is_same<uncvref_type<T>, T>::value\n                                 ? range_format::disabled\n                             : is_map<T>::value ? range_format::map\n                             : is_set<T>::value ? range_format::set\n                                                : range_format::sequence> {};\n\ntemplate <range_format K>\nusing range_format_constant = std::integral_constant<range_format, K>;\n\n// These are not generic lambdas for compatibility with C++11.\ntemplate <typename Char> struct parse_empty_specs {\n  template <typename Formatter> FMT_CONSTEXPR void operator()(Formatter& f) {\n    f.parse(ctx);\n    detail::maybe_set_debug_format(f, true);\n  }\n  parse_context<Char>& ctx;\n};\ntemplate <typename FormatContext> struct format_tuple_element {\n  using char_type = typename FormatContext::char_type;\n\n  template <typename T>\n  void operator()(const formatter<T, char_type>& f, const T& v) {\n    if (i > 0) ctx.advance_to(detail::copy<char_type>(separator, ctx.out()));\n    ctx.advance_to(f.format(v, ctx));\n    ++i;\n  }\n\n  int i;\n  FormatContext& ctx;\n  basic_string_view<char_type> separator;\n};\n\n}  // namespace detail\n\nFMT_EXPORT\ntemplate <typename T> struct is_tuple_like {\n  static constexpr bool value =\n      detail::is_tuple_like_<T>::value && !detail::is_range_<T>::value;\n};\n\nFMT_EXPORT\ntemplate <typename T, typename C> struct is_tuple_formattable {\n  static constexpr bool value = detail::is_tuple_formattable_<T, C>::value;\n};\n\ntemplate <typename Tuple, typename Char>\nstruct formatter<Tuple, Char,\n                 enable_if_t<fmt::is_tuple_like<Tuple>::value &&\n                             fmt::is_tuple_formattable<Tuple, Char>::value>> {\n private:\n  decltype(detail::tuple::get_formatters<Tuple, Char>(\n      detail::tuple_index_sequence<Tuple>())) formatters_;\n\n  basic_string_view<Char> separator_ = detail::string_literal<Char, ',', ' '>{};\n  basic_string_view<Char> opening_bracket_ =\n      detail::string_literal<Char, '('>{};\n  basic_string_view<Char> closing_bracket_ =\n      detail::string_literal<Char, ')'>{};\n\n public:\n  FMT_CONSTEXPR formatter() {}\n\n  FMT_CONSTEXPR void set_separator(basic_string_view<Char> sep) {\n    separator_ = sep;\n  }\n\n  FMT_CONSTEXPR void set_brackets(basic_string_view<Char> open,\n                                  basic_string_view<Char> close) {\n    opening_bracket_ = open;\n    closing_bracket_ = close;\n  }\n\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    auto it = ctx.begin();\n    auto end = ctx.end();\n    if (it != end && detail::to_ascii(*it) == 'n') {\n      ++it;\n      set_brackets({}, {});\n      set_separator({});\n    }\n    if (it != end && *it != '}') report_error(\"invalid format specifier\");\n    ctx.advance_to(it);\n    detail::for_each(formatters_, detail::parse_empty_specs<Char>{ctx});\n    return it;\n  }\n\n  template <typename FormatContext>\n  auto format(const Tuple& value, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    ctx.advance_to(detail::copy<Char>(opening_bracket_, ctx.out()));\n    detail::for_each2(\n        formatters_, value,\n        detail::format_tuple_element<FormatContext>{0, ctx, separator_});\n    return detail::copy<Char>(closing_bracket_, ctx.out());\n  }\n};\n\nFMT_EXPORT\ntemplate <typename T, typename Char> struct is_range {\n  static constexpr bool value =\n      detail::is_range_<T>::value && !detail::has_to_string_view<T>::value;\n};\n\nnamespace detail {\n\ntemplate <typename Char, typename Element>\nusing range_formatter_type = formatter<remove_cvref_t<Element>, Char>;\n\ntemplate <typename R>\nusing maybe_const_range =\n    conditional_t<has_const_begin_end<R>::value, const R, R>;\n\ntemplate <typename R, typename Char>\nstruct is_formattable_delayed\n    : is_formattable<uncvref_type<maybe_const_range<R>>, Char> {};\n}  // namespace detail\n\ntemplate <typename...> struct conjunction : std::true_type {};\ntemplate <typename P> struct conjunction<P> : P {};\ntemplate <typename P1, typename... Pn>\nstruct conjunction<P1, Pn...>\n    : conditional_t<bool(P1::value), conjunction<Pn...>, P1> {};\n\nFMT_EXPORT\ntemplate <typename T, typename Char, typename Enable = void>\nstruct range_formatter;\n\ntemplate <typename T, typename Char>\nstruct range_formatter<\n    T, Char,\n    enable_if_t<conjunction<std::is_same<T, remove_cvref_t<T>>,\n                            is_formattable<T, Char>>::value>> {\n private:\n  detail::range_formatter_type<Char, T> underlying_;\n  basic_string_view<Char> separator_ = detail::string_literal<Char, ',', ' '>{};\n  basic_string_view<Char> opening_bracket_ =\n      detail::string_literal<Char, '['>{};\n  basic_string_view<Char> closing_bracket_ =\n      detail::string_literal<Char, ']'>{};\n  bool is_debug = false;\n\n  template <typename Output, typename It, typename Sentinel, typename U = T,\n            FMT_ENABLE_IF(std::is_same<U, Char>::value)>\n  auto write_debug_string(Output& out, It it, Sentinel end) const -> Output {\n    auto buf = basic_memory_buffer<Char>();\n    for (; it != end; ++it) buf.push_back(*it);\n    auto specs = format_specs();\n    specs.set_type(presentation_type::debug);\n    return detail::write<Char>(\n        out, basic_string_view<Char>(buf.data(), buf.size()), specs);\n  }\n\n  template <typename Output, typename It, typename Sentinel, typename U = T,\n            FMT_ENABLE_IF(!std::is_same<U, Char>::value)>\n  auto write_debug_string(Output& out, It, Sentinel) const -> Output {\n    return out;\n  }\n\n public:\n  FMT_CONSTEXPR range_formatter() {}\n\n  FMT_CONSTEXPR auto underlying() -> detail::range_formatter_type<Char, T>& {\n    return underlying_;\n  }\n\n  FMT_CONSTEXPR void set_separator(basic_string_view<Char> sep) {\n    separator_ = sep;\n  }\n\n  FMT_CONSTEXPR void set_brackets(basic_string_view<Char> open,\n                                  basic_string_view<Char> close) {\n    opening_bracket_ = open;\n    closing_bracket_ = close;\n  }\n\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    auto it = ctx.begin();\n    auto end = ctx.end();\n    detail::maybe_set_debug_format(underlying_, true);\n    if (it == end) return underlying_.parse(ctx);\n\n    switch (detail::to_ascii(*it)) {\n    case 'n':\n      set_brackets({}, {});\n      ++it;\n      break;\n    case '?':\n      is_debug = true;\n      set_brackets({}, {});\n      ++it;\n      if (it == end || *it != 's') report_error(\"invalid format specifier\");\n      FMT_FALLTHROUGH;\n    case 's':\n      if (!std::is_same<T, Char>::value)\n        report_error(\"invalid format specifier\");\n      if (!is_debug) {\n        set_brackets(detail::string_literal<Char, '\"'>{},\n                     detail::string_literal<Char, '\"'>{});\n        set_separator({});\n        detail::maybe_set_debug_format(underlying_, false);\n      }\n      ++it;\n      return it;\n    }\n\n    if (it != end && *it != '}') {\n      if (*it != ':') report_error(\"invalid format specifier\");\n      detail::maybe_set_debug_format(underlying_, false);\n      ++it;\n    }\n\n    ctx.advance_to(it);\n    return underlying_.parse(ctx);\n  }\n\n  template <typename R, typename FormatContext>\n  auto format(R&& range, FormatContext& ctx) const -> decltype(ctx.out()) {\n    auto out = ctx.out();\n    auto it = detail::range_begin(range);\n    auto end = detail::range_end(range);\n    if (is_debug) return write_debug_string(out, std::move(it), end);\n\n    out = detail::copy<Char>(opening_bracket_, out);\n    int i = 0;\n    for (; it != end; ++it) {\n      if (i > 0) out = detail::copy<Char>(separator_, out);\n      ctx.advance_to(out);\n      auto&& item = *it;  // Need an lvalue\n      out = underlying_.format(item, ctx);\n      ++i;\n    }\n    out = detail::copy<Char>(closing_bracket_, out);\n    return out;\n  }\n};\n\nFMT_EXPORT\ntemplate <typename T, typename Char, typename Enable = void>\nstruct range_format_kind\n    : conditional_t<\n          is_range<T, Char>::value, detail::range_format_kind_<T>,\n          std::integral_constant<range_format, range_format::disabled>> {};\n\ntemplate <typename R, typename Char>\nstruct formatter<\n    R, Char,\n    enable_if_t<conjunction<\n        bool_constant<\n            range_format_kind<R, Char>::value != range_format::disabled &&\n            range_format_kind<R, Char>::value != range_format::map &&\n            range_format_kind<R, Char>::value != range_format::string &&\n            range_format_kind<R, Char>::value != range_format::debug_string>,\n        detail::is_formattable_delayed<R, Char>>::value>> {\n private:\n  using range_type = detail::maybe_const_range<R>;\n  range_formatter<detail::uncvref_type<range_type>, Char> range_formatter_;\n\n public:\n  using nonlocking = void;\n\n  FMT_CONSTEXPR formatter() {\n    if (detail::const_check(range_format_kind<R, Char>::value !=\n                            range_format::set))\n      return;\n    range_formatter_.set_brackets(detail::string_literal<Char, '{'>{},\n                                  detail::string_literal<Char, '}'>{});\n  }\n\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    return range_formatter_.parse(ctx);\n  }\n\n  template <typename FormatContext>\n  auto format(range_type& range, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    return range_formatter_.format(range, ctx);\n  }\n};\n\n// A map formatter.\ntemplate <typename R, typename Char>\nstruct formatter<\n    R, Char,\n    enable_if_t<conjunction<\n        bool_constant<range_format_kind<R, Char>::value == range_format::map>,\n        detail::is_formattable_delayed<R, Char>>::value>> {\n private:\n  using map_type = detail::maybe_const_range<R>;\n  using element_type = detail::uncvref_type<map_type>;\n\n  decltype(detail::tuple::get_formatters<element_type, Char>(\n      detail::tuple_index_sequence<element_type>())) formatters_;\n  bool no_delimiters_ = false;\n\n public:\n  FMT_CONSTEXPR formatter() {}\n\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    auto it = ctx.begin();\n    auto end = ctx.end();\n    if (it != end) {\n      if (detail::to_ascii(*it) == 'n') {\n        no_delimiters_ = true;\n        ++it;\n      }\n      if (it != end && *it != '}') {\n        if (*it != ':') report_error(\"invalid format specifier\");\n        ++it;\n      }\n      ctx.advance_to(it);\n    }\n    detail::for_each(formatters_, detail::parse_empty_specs<Char>{ctx});\n    return it;\n  }\n\n  template <typename FormatContext>\n  auto format(map_type& map, FormatContext& ctx) const -> decltype(ctx.out()) {\n    auto out = ctx.out();\n    basic_string_view<Char> open = detail::string_literal<Char, '{'>{};\n    if (!no_delimiters_) out = detail::copy<Char>(open, out);\n    int i = 0;\n    basic_string_view<Char> sep = detail::string_literal<Char, ',', ' '>{};\n    for (auto&& value : map) {\n      if (i > 0) out = detail::copy<Char>(sep, out);\n      ctx.advance_to(out);\n      detail::for_each2(formatters_, value,\n                        detail::format_tuple_element<FormatContext>{\n                            0, ctx, detail::string_literal<Char, ':', ' '>{}});\n      ++i;\n    }\n    basic_string_view<Char> close = detail::string_literal<Char, '}'>{};\n    if (!no_delimiters_) out = detail::copy<Char>(close, out);\n    return out;\n  }\n};\n\n// A (debug_)string formatter.\ntemplate <typename R, typename Char>\nstruct formatter<\n    R, Char,\n    enable_if_t<range_format_kind<R, Char>::value == range_format::string ||\n                range_format_kind<R, Char>::value ==\n                    range_format::debug_string>> {\n private:\n  using range_type = detail::maybe_const_range<R>;\n  using string_type =\n      conditional_t<std::is_constructible<\n                        detail::std_string_view<Char>,\n                        decltype(detail::range_begin(std::declval<R>())),\n                        decltype(detail::range_end(std::declval<R>()))>::value,\n                    detail::std_string_view<Char>, std::basic_string<Char>>;\n\n  formatter<string_type, Char> underlying_;\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    return underlying_.parse(ctx);\n  }\n\n  template <typename FormatContext>\n  auto format(range_type& range, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    auto out = ctx.out();\n    if (detail::const_check(range_format_kind<R, Char>::value ==\n                            range_format::debug_string))\n      *out++ = '\"';\n    out = underlying_.format(\n        string_type{detail::range_begin(range), detail::range_end(range)}, ctx);\n    if (detail::const_check(range_format_kind<R, Char>::value ==\n                            range_format::debug_string))\n      *out++ = '\"';\n    return out;\n  }\n};\n\ntemplate <typename It, typename Sentinel, typename Char = char>\nstruct join_view : detail::view {\n  It begin;\n  Sentinel end;\n  basic_string_view<Char> sep;\n\n  join_view(It b, Sentinel e, basic_string_view<Char> s)\n      : begin(std::move(b)), end(e), sep(s) {}\n};\n\ntemplate <typename It, typename Sentinel, typename Char>\nstruct formatter<join_view<It, Sentinel, Char>, Char> {\n private:\n  using value_type =\n#ifdef __cpp_lib_ranges\n      std::iter_value_t<It>;\n#else\n      typename std::iterator_traits<It>::value_type;\n#endif\n  formatter<remove_cvref_t<value_type>, Char> value_formatter_;\n\n  using view = conditional_t<std::is_copy_constructible<It>::value,\n                             const join_view<It, Sentinel, Char>,\n                             join_view<It, Sentinel, Char>>;\n\n public:\n  using nonlocking = void;\n\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    return value_formatter_.parse(ctx);\n  }\n\n  template <typename FormatContext>\n  auto format(view& value, FormatContext& ctx) const -> decltype(ctx.out()) {\n    using iter =\n        conditional_t<std::is_copy_constructible<view>::value, It, It&>;\n    iter it = value.begin;\n    auto out = ctx.out();\n    if (it == value.end) return out;\n    out = value_formatter_.format(*it, ctx);\n    ++it;\n    while (it != value.end) {\n      out = detail::copy<Char>(value.sep.begin(), value.sep.end(), out);\n      ctx.advance_to(out);\n      out = value_formatter_.format(*it, ctx);\n      ++it;\n    }\n    return out;\n  }\n};\n\nFMT_EXPORT\ntemplate <typename Tuple, typename Char> struct tuple_join_view : detail::view {\n  const Tuple& tuple;\n  basic_string_view<Char> sep;\n\n  tuple_join_view(const Tuple& t, basic_string_view<Char> s)\n      : tuple(t), sep{s} {}\n};\n\n// Define FMT_TUPLE_JOIN_SPECIFIERS to enable experimental format specifiers\n// support in tuple_join. It is disabled by default because of issues with\n// the dynamic width and precision.\n#ifndef FMT_TUPLE_JOIN_SPECIFIERS\n#  define FMT_TUPLE_JOIN_SPECIFIERS 0\n#endif\n\ntemplate <typename Tuple, typename Char>\nstruct formatter<tuple_join_view<Tuple, Char>, Char,\n                 enable_if_t<is_tuple_like<Tuple>::value>> {\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    return do_parse(ctx, std::tuple_size<Tuple>());\n  }\n\n  template <typename FormatContext>\n  auto format(const tuple_join_view<Tuple, Char>& value,\n              FormatContext& ctx) const -> typename FormatContext::iterator {\n    return do_format(value, ctx, std::tuple_size<Tuple>());\n  }\n\n private:\n  decltype(detail::tuple::get_formatters<Tuple, Char>(\n      detail::tuple_index_sequence<Tuple>())) formatters_;\n\n  FMT_CONSTEXPR auto do_parse(parse_context<Char>& ctx,\n                              std::integral_constant<size_t, 0>)\n      -> const Char* {\n    return ctx.begin();\n  }\n\n  template <size_t N>\n  FMT_CONSTEXPR auto do_parse(parse_context<Char>& ctx,\n                              std::integral_constant<size_t, N>)\n      -> const Char* {\n    auto end = ctx.begin();\n#if FMT_TUPLE_JOIN_SPECIFIERS\n    end = std::get<std::tuple_size<Tuple>::value - N>(formatters_).parse(ctx);\n    if (N > 1) {\n      auto end1 = do_parse(ctx, std::integral_constant<size_t, N - 1>());\n      if (end != end1)\n        report_error(\"incompatible format specs for tuple elements\");\n    }\n#endif\n    return end;\n  }\n\n  template <typename FormatContext>\n  auto do_format(const tuple_join_view<Tuple, Char>&, FormatContext& ctx,\n                 std::integral_constant<size_t, 0>) const ->\n      typename FormatContext::iterator {\n    return ctx.out();\n  }\n\n  template <typename FormatContext, size_t N>\n  auto do_format(const tuple_join_view<Tuple, Char>& value, FormatContext& ctx,\n                 std::integral_constant<size_t, N>) const ->\n      typename FormatContext::iterator {\n    using std::get;\n    auto out =\n        std::get<std::tuple_size<Tuple>::value - N>(formatters_)\n            .format(get<std::tuple_size<Tuple>::value - N>(value.tuple), ctx);\n    if (N <= 1) return out;\n    out = detail::copy<Char>(value.sep, out);\n    ctx.advance_to(out);\n    return do_format(value, ctx, std::integral_constant<size_t, N - 1>());\n  }\n};\n\nnamespace detail {\n// Check if T has an interface like a container adaptor (e.g. std::stack,\n// std::queue, std::priority_queue).\ntemplate <typename T> class is_container_adaptor_like {\n  template <typename U> static auto check(U* p) -> typename U::container_type;\n  template <typename> static void check(...);\n\n public:\n  static constexpr bool value =\n      !std::is_void<decltype(check<T>(nullptr))>::value;\n};\n\ntemplate <typename Container> struct all {\n  const Container& c;\n  auto begin() const -> typename Container::const_iterator { return c.begin(); }\n  auto end() const -> typename Container::const_iterator { return c.end(); }\n};\n}  // namespace detail\n\ntemplate <typename T, typename Char>\nstruct formatter<\n    T, Char,\n    enable_if_t<conjunction<detail::is_container_adaptor_like<T>,\n                            bool_constant<range_format_kind<T, Char>::value ==\n                                          range_format::disabled>>::value>>\n    : formatter<detail::all<typename T::container_type>, Char> {\n  using all = detail::all<typename T::container_type>;\n  template <typename FormatContext>\n  auto format(const T& value, FormatContext& ctx) const -> decltype(ctx.out()) {\n    struct getter : T {\n      static auto get(const T& v) -> all {\n        return {v.*(&getter::c)};  // Access c through the derived class.\n      }\n    };\n    return formatter<all>::format(getter::get(value), ctx);\n  }\n};\n\nFMT_BEGIN_EXPORT\n\n/// Returns a view that formats the iterator range `[begin, end)` with elements\n/// separated by `sep`.\ntemplate <typename It, typename Sentinel>\nauto join(It begin, Sentinel end, string_view sep) -> join_view<It, Sentinel> {\n  return {std::move(begin), end, sep};\n}\n\n/**\n * Returns a view that formats `range` with elements separated by `sep`.\n *\n * **Example**:\n *\n *     auto v = std::vector<int>{1, 2, 3};\n *     fmt::print(\"{}\", fmt::join(v, \", \"));\n *     // Output: 1, 2, 3\n *\n * `fmt::join` applies passed format specifiers to the range elements:\n *\n *     fmt::print(\"{:02}\", fmt::join(v, \", \"));\n *     // Output: 01, 02, 03\n */\ntemplate <typename Range, FMT_ENABLE_IF(!is_tuple_like<Range>::value)>\nauto join(Range&& r, string_view sep)\n    -> join_view<decltype(detail::range_begin(r)),\n                 decltype(detail::range_end(r))> {\n  return {detail::range_begin(r), detail::range_end(r), sep};\n}\n\n/**\n * Returns an object that formats `std::tuple` with elements separated by `sep`.\n *\n * **Example**:\n *\n *     auto t = std::tuple<int, char>{1, 'a'};\n *     fmt::print(\"{}\", fmt::join(t, \", \"));\n *     // Output: 1, a\n */\ntemplate <typename Tuple, FMT_ENABLE_IF(is_tuple_like<Tuple>::value)>\nFMT_CONSTEXPR auto join(const Tuple& tuple, string_view sep)\n    -> tuple_join_view<Tuple, char> {\n  return {tuple, sep};\n}\n\n/**\n * Returns an object that formats `std::initializer_list` with elements\n * separated by `sep`.\n *\n * **Example**:\n *\n *     fmt::print(\"{}\", fmt::join({1, 2, 3}, \", \"));\n *     // Output: \"1, 2, 3\"\n */\ntemplate <typename T>\nauto join(std::initializer_list<T> list, string_view sep)\n    -> join_view<const T*, const T*> {\n  return join(std::begin(list), std::end(list), sep);\n}\n\nFMT_END_EXPORT\nFMT_END_NAMESPACE\n\n#endif  // FMT_RANGES_H_\n"
  },
  {
    "path": "include/fmt/std.h",
    "content": "// Formatting library for C++ - formatters for standard library types\n//\n// Copyright (c) 2012 - present, Victor Zverovich\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_STD_H_\n#define FMT_STD_H_\n\n#include \"format.h\"\n#include \"ostream.h\"\n\n#ifndef FMT_MODULE\n#  include <atomic>\n#  include <bitset>\n#  include <complex>\n#  include <exception>\n#  include <functional>  // std::reference_wrapper\n#  include <memory>\n#  include <thread>\n#  include <type_traits>\n#  include <typeinfo>  // std::type_info\n#  include <utility>   // std::make_index_sequence\n\n// Check FMT_CPLUSPLUS to suppress a bogus warning in MSVC.\n#  if FMT_CPLUSPLUS >= 201703L\n#    if FMT_HAS_INCLUDE(<filesystem>) && \\\n        (!defined(FMT_CPP_LIB_FILESYSTEM) || FMT_CPP_LIB_FILESYSTEM != 0)\n#      include <filesystem>\n#    endif\n#    if FMT_HAS_INCLUDE(<variant>)\n#      include <variant>\n#    endif\n#    if FMT_HAS_INCLUDE(<optional>)\n#      include <optional>\n#    endif\n#  endif\n// Use > instead of >= in the version check because <source_location> may be\n// available after C++17 but before C++20 is marked as implemented.\n#  if FMT_CPLUSPLUS > 201703L && FMT_HAS_INCLUDE(<source_location>)\n#    include <source_location>\n#  endif\n#  if FMT_CPLUSPLUS > 202002L && FMT_HAS_INCLUDE(<expected>)\n#    include <expected>\n#  endif\n#endif  // FMT_MODULE\n\n#if FMT_HAS_INCLUDE(<version>)\n#  include <version>\n#endif\n\n// GCC 4 does not support FMT_HAS_INCLUDE.\n#if FMT_HAS_INCLUDE(<cxxabi.h>) || defined(__GLIBCXX__)\n#  include <cxxabi.h>\n// Android NDK with gabi++ library on some architectures does not implement\n// abi::__cxa_demangle().\n#  ifndef __GABIXX_CXXABI_H__\n#    define FMT_HAS_ABI_CXA_DEMANGLE\n#  endif\n#endif\n\n#ifdef FMT_CPP_LIB_FILESYSTEM\n// Use the provided definition.\n#elif defined(__cpp_lib_filesystem)\n#  define FMT_CPP_LIB_FILESYSTEM __cpp_lib_filesystem\n#else\n#  define FMT_CPP_LIB_FILESYSTEM 0\n#endif\n\n#ifdef FMT_CPP_LIB_VARIANT\n// Use the provided definition.\n#elif defined(__cpp_lib_variant)\n#  define FMT_CPP_LIB_VARIANT __cpp_lib_variant\n#else\n#  define FMT_CPP_LIB_VARIANT 0\n#endif\n\nFMT_BEGIN_NAMESPACE\nnamespace detail {\n\n#if FMT_CPP_LIB_FILESYSTEM\n\ntemplate <typename Char, typename PathChar>\nauto get_path_string(const std::filesystem::path& p,\n                     const std::basic_string<PathChar>& native) {\n  if constexpr (std::is_same_v<Char, char> && std::is_same_v<PathChar, wchar_t>)\n    return to_utf8<wchar_t>(native, to_utf8_error_policy::replace);\n  else\n    return p.string<Char>();\n}\n\ntemplate <typename Char, typename PathChar>\nvoid write_escaped_path(basic_memory_buffer<Char>& quoted,\n                        const std::filesystem::path& p,\n                        const std::basic_string<PathChar>& native) {\n  if constexpr (std::is_same_v<Char, char> &&\n                std::is_same_v<PathChar, wchar_t>) {\n    auto buf = basic_memory_buffer<wchar_t>();\n    write_escaped_string<wchar_t>(std::back_inserter(buf), native);\n    bool valid = to_utf8<wchar_t>::convert(quoted, {buf.data(), buf.size()});\n    FMT_ASSERT(valid, \"invalid utf16\");\n  } else if constexpr (std::is_same_v<Char, PathChar>) {\n    write_escaped_string<std::filesystem::path::value_type>(\n        std::back_inserter(quoted), native);\n  } else {\n    write_escaped_string<Char>(std::back_inserter(quoted), p.string<Char>());\n  }\n}\n\n#endif  // FMT_CPP_LIB_FILESYSTEM\n\n#if defined(__cpp_lib_expected) || FMT_CPP_LIB_VARIANT\ntemplate <typename Char, typename OutputIt, typename T>\nauto write_escaped_alternative(OutputIt out, const T& v) -> OutputIt {\n  if constexpr (has_to_string_view<T>::value)\n    return write_escaped_string<Char>(out, detail::to_string_view(v));\n  if constexpr (std::is_same_v<T, Char>) return write_escaped_char(out, v);\n  return write<Char>(out, v);\n}\n#endif\n\n#if FMT_CPP_LIB_VARIANT\n\ntemplate <typename> struct is_variant_like_ : std::false_type {};\ntemplate <typename... Types>\nstruct is_variant_like_<std::variant<Types...>> : std::true_type {};\n\ntemplate <typename Variant, typename Char> class is_variant_formattable {\n  template <size_t... Is>\n  static auto check(std::index_sequence<Is...>) -> std::conjunction<\n      is_formattable<std::variant_alternative_t<Is, Variant>, Char>...>;\n\n public:\n  static constexpr bool value = decltype(check(\n      std::make_index_sequence<std::variant_size<Variant>::value>()))::value;\n};\n\n#endif  // FMT_CPP_LIB_VARIANT\n\n#if FMT_USE_RTTI\n\ntemplate <typename OutputIt>\nauto write_demangled_name(OutputIt out, const std::type_info& ti) -> OutputIt {\n#  ifdef FMT_HAS_ABI_CXA_DEMANGLE\n  int status = 0;\n  size_t size = 0;\n  std::unique_ptr<char, void (*)(void*)> demangled_name_ptr(\n      abi::__cxa_demangle(ti.name(), nullptr, &size, &status), &std::free);\n\n  string_view demangled_name_view;\n  if (demangled_name_ptr) {\n    demangled_name_view = demangled_name_ptr.get();\n\n    // Normalization of stdlib inline namespace names.\n    // libc++ inline namespaces.\n    //  std::__1::*       -> std::*\n    //  std::__1::__fs::* -> std::*\n    // libstdc++ inline namespaces.\n    //  std::__cxx11::*             -> std::*\n    //  std::filesystem::__cxx11::* -> std::filesystem::*\n    if (demangled_name_view.starts_with(\"std::\")) {\n      char* begin = demangled_name_ptr.get();\n      char* to = begin + 5;  // std::\n      for (char *from = to, *end = begin + demangled_name_view.size();\n           from < end;) {\n        // This is safe, because demangled_name is NUL-terminated.\n        if (from[0] == '_' && from[1] == '_') {\n          char* next = from + 1;\n          while (next < end && *next != ':') next++;\n          if (next[0] == ':' && next[1] == ':') {\n            from = next + 2;\n            continue;\n          }\n        }\n        *to++ = *from++;\n      }\n      demangled_name_view = {begin, detail::to_unsigned(to - begin)};\n    }\n  } else {\n    demangled_name_view = string_view(ti.name());\n  }\n  return detail::write_bytes<char>(out, demangled_name_view);\n#  elif FMT_MSC_VERSION\n  const string_view demangled_name(ti.name());\n  for (size_t i = 0; i < demangled_name.size(); ++i) {\n    auto sub = demangled_name;\n    sub.remove_prefix(i);\n    if (sub.starts_with(\"enum \")) {\n      i += 4;\n      continue;\n    }\n    if (sub.starts_with(\"class \") || sub.starts_with(\"union \")) {\n      i += 5;\n      continue;\n    }\n    if (sub.starts_with(\"struct \")) {\n      i += 6;\n      continue;\n    }\n    if (*sub.begin() != ' ') *out++ = *sub.begin();\n  }\n  return out;\n#  else\n  return detail::write_bytes<char>(out, string_view(ti.name()));\n#  endif\n}\n\n#endif  // FMT_USE_RTTI\n\ntemplate <typename T, typename Enable = void>\nstruct has_flip : std::false_type {};\n\ntemplate <typename T>\nstruct has_flip<T, void_t<decltype(std::declval<T>().flip())>>\n    : std::true_type {};\n\ntemplate <typename T> struct is_bit_reference_like {\n  static constexpr bool value = std::is_convertible<T, bool>::value &&\n                                std::is_nothrow_assignable<T, bool>::value &&\n                                has_flip<T>::value;\n};\n\n// Workaround for libc++ incompatibility with C++ standard.\n// According to the Standard, `bitset::operator[] const` returns bool.\n#if defined(_LIBCPP_VERSION) && !defined(FMT_IMPORT_STD)\ntemplate <typename C>\nstruct is_bit_reference_like<std::__bit_const_reference<C>> {\n  static constexpr bool value = true;\n};\n#endif\n\ntemplate <typename T, typename Enable = void>\nstruct has_format_as : std::false_type {};\ntemplate <typename T>\nstruct has_format_as<T, void_t<decltype(format_as(std::declval<const T&>()))>>\n    : std::true_type {};\n\ntemplate <typename T, typename Enable = void>\nstruct has_format_as_member : std::false_type {};\ntemplate <typename T>\nstruct has_format_as_member<\n    T, void_t<decltype(formatter<T>::format_as(std::declval<const T&>()))>>\n    : std::true_type {};\n\n}  // namespace detail\n\ntemplate <typename T, typename Deleter>\nauto ptr(const std::unique_ptr<T, Deleter>& p) -> const void* {\n  return p.get();\n}\ntemplate <typename T> auto ptr(const std::shared_ptr<T>& p) -> const void* {\n  return p.get();\n}\n\n#if FMT_CPP_LIB_FILESYSTEM\n\nclass path : public std::filesystem::path {\n public:\n  auto display_string() const -> std::string {\n    const std::filesystem::path& base = *this;\n    return fmt::format(FMT_STRING(\"{}\"), base);\n  }\n  auto system_string() const -> std::string { return string(); }\n\n  auto generic_display_string() const -> std::string {\n    const std::filesystem::path& base = *this;\n    return fmt::format(FMT_STRING(\"{:g}\"), base);\n  }\n  auto generic_system_string() const -> std::string { return generic_string(); }\n};\n\ntemplate <typename Char> struct formatter<std::filesystem::path, Char> {\n private:\n  format_specs specs_;\n  detail::arg_ref<Char> width_ref_;\n  bool debug_ = false;\n  char path_type_ = 0;\n\n public:\n  FMT_CONSTEXPR void set_debug_format(bool set = true) { debug_ = set; }\n\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) {\n    auto it = ctx.begin(), end = ctx.end();\n    if (it == end) return it;\n\n    it = detail::parse_align(it, end, specs_);\n    if (it == end) return it;\n\n    Char c = *it;\n    if ((c >= '0' && c <= '9') || c == '{')\n      it = detail::parse_width(it, end, specs_, width_ref_, ctx);\n    if (it != end && *it == '?') {\n      debug_ = true;\n      ++it;\n    }\n    if (it != end && (*it == 'g')) path_type_ = detail::to_ascii(*it++);\n    return it;\n  }\n\n  template <typename FormatContext>\n  auto format(const std::filesystem::path& p, FormatContext& ctx) const {\n    auto specs = specs_;\n    auto path_string =\n        !path_type_ ? p.native()\n                    : p.generic_string<std::filesystem::path::value_type>();\n\n    detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,\n                                ctx);\n    if (!debug_) {\n      auto s = detail::get_path_string<Char>(p, path_string);\n      return detail::write(ctx.out(), basic_string_view<Char>(s), specs);\n    }\n    auto quoted = basic_memory_buffer<Char>();\n    detail::write_escaped_path(quoted, p, path_string);\n    return detail::write(ctx.out(),\n                         basic_string_view<Char>(quoted.data(), quoted.size()),\n                         specs);\n  }\n};\n\n#endif  // FMT_CPP_LIB_FILESYSTEM\n\ntemplate <size_t N, typename Char>\nstruct formatter<std::bitset<N>, Char>\n    : nested_formatter<basic_string_view<Char>, Char> {\n private:\n  // This is a functor because C++11 doesn't support generic lambdas.\n  struct writer {\n    const std::bitset<N>& bs;\n\n    template <typename OutputIt>\n    FMT_CONSTEXPR auto operator()(OutputIt out) -> OutputIt {\n      for (auto pos = N; pos > 0; --pos)\n        out = detail::write<Char>(out, bs[pos - 1] ? Char('1') : Char('0'));\n      return out;\n    }\n  };\n\n public:\n  template <typename FormatContext>\n  auto format(const std::bitset<N>& bs, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    return this->write_padded(ctx, writer{bs});\n  }\n};\n\ntemplate <typename Char>\nstruct formatter<std::thread::id, Char> : basic_ostream_formatter<Char> {};\n\n#ifdef __cpp_lib_optional\ntemplate <typename T, typename Char>\nstruct formatter<std::optional<T>, Char,\n                 std::enable_if_t<is_formattable<T, Char>::value>> {\n private:\n  formatter<T, Char> underlying_;\n  static constexpr basic_string_view<Char> optional =\n      detail::string_literal<Char, 'o', 'p', 't', 'i', 'o', 'n', 'a', 'l',\n                             '('>{};\n  static constexpr basic_string_view<Char> none =\n      detail::string_literal<Char, 'n', 'o', 'n', 'e'>{};\n\n  template <class U>\n  FMT_CONSTEXPR static auto maybe_set_debug_format(U& u, bool set)\n      -> decltype(u.set_debug_format(set)) {\n    u.set_debug_format(set);\n  }\n\n  template <class U>\n  FMT_CONSTEXPR static void maybe_set_debug_format(U&, ...) {}\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) {\n    maybe_set_debug_format(underlying_, true);\n    return underlying_.parse(ctx);\n  }\n\n  template <typename FormatContext>\n  auto format(const std::optional<T>& opt, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    if (!opt) return detail::write<Char>(ctx.out(), none);\n\n    auto out = ctx.out();\n    out = detail::write<Char>(out, optional);\n    ctx.advance_to(out);\n    out = underlying_.format(*opt, ctx);\n    return detail::write(out, ')');\n  }\n};\n#endif  // __cpp_lib_optional\n\n#ifdef __cpp_lib_expected\ntemplate <typename T, typename E, typename Char>\nstruct formatter<std::expected<T, E>, Char,\n                 std::enable_if_t<(std::is_void<T>::value ||\n                                   is_formattable<T, Char>::value) &&\n                                  is_formattable<E, Char>::value>> {\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    return ctx.begin();\n  }\n\n  template <typename FormatContext>\n  auto format(const std::expected<T, E>& value, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    auto out = ctx.out();\n\n    if (value.has_value()) {\n      out = detail::write<Char>(out, \"expected(\");\n      if constexpr (!std::is_void<T>::value)\n        out = detail::write_escaped_alternative<Char>(out, *value);\n    } else {\n      out = detail::write<Char>(out, \"unexpected(\");\n      out = detail::write_escaped_alternative<Char>(out, value.error());\n    }\n    *out++ = ')';\n    return out;\n  }\n};\n#endif  // __cpp_lib_expected\n\n#ifdef __cpp_lib_source_location\ntemplate <> struct formatter<std::source_location> {\n  FMT_CONSTEXPR auto parse(parse_context<>& ctx) { return ctx.begin(); }\n\n  template <typename FormatContext>\n  auto format(const std::source_location& loc, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    auto out = ctx.out();\n    out = detail::write(out, loc.file_name());\n    out = detail::write(out, ':');\n    out = detail::write<char>(out, loc.line());\n    out = detail::write(out, ':');\n    out = detail::write<char>(out, loc.column());\n    out = detail::write(out, \": \");\n    out = detail::write(out, loc.function_name());\n    return out;\n  }\n};\n#endif\n\n#if FMT_CPP_LIB_VARIANT\n\ntemplate <typename T> struct is_variant_like {\n  static constexpr bool value = detail::is_variant_like_<T>::value;\n};\n\ntemplate <typename Char> struct formatter<std::monostate, Char> {\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    return ctx.begin();\n  }\n\n  template <typename FormatContext>\n  auto format(const std::monostate&, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    return detail::write<Char>(ctx.out(), \"monostate\");\n  }\n};\n\ntemplate <typename Variant, typename Char>\nstruct formatter<Variant, Char,\n                 std::enable_if_t<std::conjunction_v<\n                     is_variant_like<Variant>,\n                     detail::is_variant_formattable<Variant, Char>>>> {\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    return ctx.begin();\n  }\n\n  template <typename FormatContext>\n  auto format(const Variant& value, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    auto out = ctx.out();\n\n    out = detail::write<Char>(out, \"variant(\");\n    FMT_TRY {\n      std::visit(\n          [&](const auto& v) {\n            out = detail::write_escaped_alternative<Char>(out, v);\n          },\n          value);\n    }\n    FMT_CATCH(const std::bad_variant_access&) {\n      detail::write<Char>(out, \"valueless by exception\");\n    }\n    *out++ = ')';\n    return out;\n  }\n};\n\n#endif  // FMT_CPP_LIB_VARIANT\n\ntemplate <> struct formatter<std::error_code> {\n private:\n  format_specs specs_;\n  detail::arg_ref<char> width_ref_;\n  bool debug_ = false;\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* {\n    auto it = ctx.begin(), end = ctx.end();\n    if (it == end) return it;\n\n    it = detail::parse_align(it, end, specs_);\n\n    char c = *it;\n    if (it != end && ((c >= '0' && c <= '9') || c == '{'))\n      it = detail::parse_width(it, end, specs_, width_ref_, ctx);\n\n    if (it != end && *it == '?') {\n      debug_ = true;\n      ++it;\n    }\n    if (it != end && *it == 's') {\n      specs_.set_type(presentation_type::string);\n      ++it;\n    }\n    return it;\n  }\n\n  template <typename FormatContext>\n  FMT_CONSTEXPR20 auto format(const std::error_code& ec,\n                              FormatContext& ctx) const -> decltype(ctx.out()) {\n    auto specs = specs_;\n    detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,\n                                ctx);\n    auto buf = memory_buffer();\n    if (specs_.type() == presentation_type::string) {\n      buf.append(ec.message());\n    } else {\n      buf.append(string_view(ec.category().name()));\n      buf.push_back(':');\n      detail::write<char>(appender(buf), ec.value());\n    }\n    auto quoted = memory_buffer();\n    auto str = string_view(buf.data(), buf.size());\n    if (debug_) {\n      detail::write_escaped_string<char>(std::back_inserter(quoted), str);\n      str = string_view(quoted.data(), quoted.size());\n    }\n    return detail::write<char>(ctx.out(), str, specs);\n  }\n};\n\n#if FMT_USE_RTTI\ntemplate <> struct formatter<std::type_info> {\n public:\n  FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* {\n    return ctx.begin();\n  }\n\n  template <typename Context>\n  auto format(const std::type_info& ti, Context& ctx) const\n      -> decltype(ctx.out()) {\n    return detail::write_demangled_name(ctx.out(), ti);\n  }\n};\n#endif  // FMT_USE_RTTI\n\ntemplate <typename T>\nstruct formatter<\n    T, char,\n    typename std::enable_if<std::is_base_of<std::exception, T>::value>::type> {\n private:\n  bool with_typename_ = false;\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* {\n    auto it = ctx.begin();\n    auto end = ctx.end();\n    if (it == end || *it == '}') return it;\n    if (*it == 't') {\n      ++it;\n      with_typename_ = FMT_USE_RTTI != 0;\n    }\n    return it;\n  }\n\n  template <typename Context>\n  auto format(const std::exception& ex, Context& ctx) const\n      -> decltype(ctx.out()) {\n    auto out = ctx.out();\n#if FMT_USE_RTTI\n    if (with_typename_) {\n      out = detail::write_demangled_name(out, typeid(ex));\n      *out++ = ':';\n      *out++ = ' ';\n    }\n#endif\n    return detail::write_bytes<char>(out, string_view(ex.what()));\n  }\n};\n\n// We can't use std::vector<bool, Allocator>::reference and\n// std::bitset<N>::reference because the compiler can't deduce Allocator and N\n// in partial specialization.\ntemplate <typename BitRef, typename Char>\nstruct formatter<BitRef, Char,\n                 enable_if_t<detail::is_bit_reference_like<BitRef>::value>>\n    : formatter<bool, Char> {\n  template <typename FormatContext>\n  FMT_CONSTEXPR auto format(const BitRef& v, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    return formatter<bool, Char>::format(v, ctx);\n  }\n};\n\ntemplate <typename T, typename Char>\nstruct formatter<std::atomic<T>, Char,\n                 enable_if_t<is_formattable<T, Char>::value>>\n    : formatter<T, Char> {\n  template <typename FormatContext>\n  auto format(const std::atomic<T>& v, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    return formatter<T, Char>::format(v.load(), ctx);\n  }\n};\n\n#ifdef __cpp_lib_atomic_flag_test\ntemplate <typename Char>\nstruct formatter<std::atomic_flag, Char> : formatter<bool, Char> {\n  template <typename FormatContext>\n  auto format(const std::atomic_flag& v, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    return formatter<bool, Char>::format(v.test(), ctx);\n  }\n};\n#endif  // __cpp_lib_atomic_flag_test\n\ntemplate <typename T, typename Char> struct formatter<std::complex<T>, Char> {\n private:\n  detail::dynamic_format_specs<Char> specs_;\n\n  template <typename FormatContext, typename OutputIt>\n  FMT_CONSTEXPR auto do_format(const std::complex<T>& c,\n                               detail::dynamic_format_specs<Char>& specs,\n                               FormatContext& ctx, OutputIt out) const\n      -> OutputIt {\n    if (c.real() != 0) {\n      *out++ = Char('(');\n      out = detail::write<Char>(out, c.real(), specs, ctx.locale());\n      specs.set_sign(sign::plus);\n      out = detail::write<Char>(out, c.imag(), specs, ctx.locale());\n      if (!detail::isfinite(c.imag())) *out++ = Char(' ');\n      *out++ = Char('i');\n      *out++ = Char(')');\n      return out;\n    }\n    out = detail::write<Char>(out, c.imag(), specs, ctx.locale());\n    if (!detail::isfinite(c.imag())) *out++ = Char(' ');\n    *out++ = Char('i');\n    return out;\n  }\n\n public:\n  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {\n    if (ctx.begin() == ctx.end() || *ctx.begin() == '}') return ctx.begin();\n    return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx,\n                              detail::type_constant<T, Char>::value);\n  }\n\n  template <typename FormatContext>\n  auto format(const std::complex<T>& c, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    auto specs = specs_;\n    if (specs.dynamic()) {\n      detail::handle_dynamic_spec(specs.dynamic_width(), specs.width,\n                                  specs.width_ref, ctx);\n      detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision,\n                                  specs.precision_ref, ctx);\n    }\n\n    if (specs.width == 0) return do_format(c, specs, ctx, ctx.out());\n    auto buf = basic_memory_buffer<Char>();\n\n    auto outer_specs = format_specs();\n    outer_specs.width = specs.width;\n    outer_specs.copy_fill_from(specs);\n    outer_specs.set_align(specs.align());\n\n    specs.width = 0;\n    specs.set_fill({});\n    specs.set_align(align::none);\n\n    do_format(c, specs, ctx, basic_appender<Char>(buf));\n    return detail::write<Char>(ctx.out(),\n                               basic_string_view<Char>(buf.data(), buf.size()),\n                               outer_specs);\n  }\n};\n\ntemplate <typename T, typename Char>\nstruct formatter<std::reference_wrapper<T>, Char,\n                 // Guard against format_as because reference_wrapper is\n                 // implicitly convertible to T&.\n                 enable_if_t<is_formattable<remove_cvref_t<T>, Char>::value &&\n                             !detail::has_format_as<T>::value &&\n                             !detail::has_format_as_member<T>::value>>\n    : formatter<remove_cvref_t<T>, Char> {\n  template <typename FormatContext>\n  auto format(std::reference_wrapper<T> ref, FormatContext& ctx) const\n      -> decltype(ctx.out()) {\n    return formatter<remove_cvref_t<T>, Char>::format(ref.get(), ctx);\n  }\n};\n\nFMT_END_NAMESPACE\n\n#endif  // FMT_STD_H_\n"
  },
  {
    "path": "include/fmt/xchar.h",
    "content": "// Formatting library for C++ - optional wchar_t and exotic character support\n//\n// Copyright (c) 2012 - present, Victor Zverovich\n// All rights reserved.\n//\n// For the license information refer to format.h.\n\n#ifndef FMT_XCHAR_H_\n#define FMT_XCHAR_H_\n\n#include \"color.h\"\n#include \"format.h\"\n#include \"ostream.h\"\n#include \"ranges.h\"\n\n#ifndef FMT_MODULE\n#  include <cwchar>\n#  if FMT_USE_LOCALE\n#    include <locale>\n#  endif\n#endif\n\nFMT_BEGIN_NAMESPACE\nnamespace detail {\n\ntemplate <typename T>\nusing is_exotic_char = bool_constant<!std::is_same<T, char>::value>;\n\ntemplate <typename S, typename = void> struct format_string_char {};\n\ntemplate <typename S>\nstruct format_string_char<\n    S, void_t<decltype(sizeof(detail::to_string_view(std::declval<S>())))>> {\n  using type = char_t<S>;\n};\n\ntemplate <typename S>\nstruct format_string_char<\n    S, enable_if_t<std::is_base_of<detail::compile_string, S>::value>> {\n  using type = typename S::char_type;\n};\n\ntemplate <typename S>\nusing format_string_char_t = typename format_string_char<S>::type;\n\ninline auto write_loc(basic_appender<wchar_t> out, loc_value value,\n                      const format_specs& specs, locale_ref loc) -> bool {\n#if FMT_USE_LOCALE\n  auto& numpunct =\n      std::use_facet<std::numpunct<wchar_t>>(loc.get<std::locale>());\n  auto separator = std::wstring();\n  auto grouping = numpunct.grouping();\n  if (!grouping.empty()) separator = std::wstring(1, numpunct.thousands_sep());\n  return value.visit(loc_writer<wchar_t>{out, specs, separator, grouping, {}});\n#endif\n  return false;\n}\n\ntemplate <typename Char>\nvoid vformat_to(buffer<Char>& buf, basic_string_view<Char> fmt,\n                basic_format_args<buffered_context<Char>> args,\n                locale_ref loc = {}) {\n  static_assert(!std::is_same<Char, char>::value, \"\");\n  auto out = basic_appender<Char>(buf);\n  parse_format_string(\n      fmt, format_handler<Char>{parse_context<Char>(fmt), {out, args, loc}});\n}\n}  // namespace detail\n\nFMT_BEGIN_EXPORT\n\nusing wstring_view = basic_string_view<wchar_t>;\nusing wformat_parse_context = parse_context<wchar_t>;\nusing wformat_context = buffered_context<wchar_t>;\nusing wformat_args = basic_format_args<wformat_context>;\nusing wmemory_buffer = basic_memory_buffer<wchar_t>;\n\ntemplate <typename Char, typename... T> struct basic_fstring {\n private:\n  basic_string_view<Char> str_;\n\n  static constexpr int num_static_named_args =\n      detail::count_static_named_args<T...>();\n\n  using checker = detail::format_string_checker<\n      Char, static_cast<int>(sizeof...(T)), num_static_named_args,\n      num_static_named_args != detail::count_named_args<T...>()>;\n\n  using arg_pack = detail::arg_pack<T...>;\n\n public:\n  using t = basic_fstring;\n\n  template <typename S,\n            FMT_ENABLE_IF(\n                std::is_convertible<const S&, basic_string_view<Char>>::value)>\n  FMT_CONSTEVAL FMT_ALWAYS_INLINE basic_fstring(const S& s) : str_(s) {\n    if (FMT_USE_CONSTEVAL)\n      detail::parse_format_string<Char>(s, checker(s, arg_pack()));\n  }\n  template <typename S,\n            FMT_ENABLE_IF(std::is_base_of<detail::compile_string, S>::value&&\n                              std::is_same<typename S::char_type, Char>::value)>\n  FMT_ALWAYS_INLINE basic_fstring(const S&) : str_(S()) {\n    FMT_CONSTEXPR auto sv = basic_string_view<Char>(S());\n    FMT_CONSTEXPR int ignore =\n        (parse_format_string(sv, checker(sv, arg_pack())), 0);\n    detail::ignore_unused(ignore);\n  }\n  basic_fstring(runtime_format_string<Char> fmt) : str_(fmt.str) {}\n\n  operator basic_string_view<Char>() const { return str_; }\n  auto get() const -> basic_string_view<Char> { return str_; }\n};\n\ntemplate <typename Char, typename... T>\nusing basic_format_string = basic_fstring<Char, T...>;\n\ntemplate <typename... T>\nusing wformat_string = typename basic_format_string<wchar_t, T...>::t;\ninline auto runtime(wstring_view s) -> runtime_format_string<wchar_t> {\n  return {{s}};\n}\n\ntemplate <typename... T>\nconstexpr auto make_wformat_args(T&... args)\n    -> decltype(fmt::make_format_args<wformat_context>(args...)) {\n  return fmt::make_format_args<wformat_context>(args...);\n}\n\n#if !FMT_USE_NONTYPE_TEMPLATE_ARGS\ninline namespace literals {\ninline auto operator\"\"_a(const wchar_t* s, size_t) -> detail::udl_arg<wchar_t> {\n  return {s};\n}\n}  // namespace literals\n#endif\n\ntemplate <typename It, typename Sentinel>\nauto join(It begin, Sentinel end, wstring_view sep)\n    -> join_view<It, Sentinel, wchar_t> {\n  return {begin, end, sep};\n}\n\ntemplate <typename Range, FMT_ENABLE_IF(!is_tuple_like<Range>::value)>\nauto join(Range&& range, wstring_view sep)\n    -> join_view<decltype(std::begin(range)), decltype(std::end(range)),\n                 wchar_t> {\n  return join(std::begin(range), std::end(range), sep);\n}\n\ntemplate <typename T>\nauto join(std::initializer_list<T> list, wstring_view sep)\n    -> join_view<const T*, const T*, wchar_t> {\n  return join(std::begin(list), std::end(list), sep);\n}\n\ntemplate <typename Tuple, FMT_ENABLE_IF(is_tuple_like<Tuple>::value)>\nauto join(const Tuple& tuple, basic_string_view<wchar_t> sep)\n    -> tuple_join_view<Tuple, wchar_t> {\n  return {tuple, sep};\n}\n\ntemplate <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>\nauto vformat(basic_string_view<Char> fmt,\n             basic_format_args<buffered_context<Char>> args)\n    -> std::basic_string<Char> {\n  auto buf = basic_memory_buffer<Char>();\n  detail::vformat_to(buf, fmt, args);\n  return {buf.data(), buf.size()};\n}\n\ntemplate <typename... T>\nauto format(wformat_string<T...> fmt, T&&... args) -> std::wstring {\n  return vformat(fmt::wstring_view(fmt), fmt::make_wformat_args(args...));\n}\n\ntemplate <typename OutputIt, typename... T>\nauto format_to(OutputIt out, wformat_string<T...> fmt, T&&... args)\n    -> OutputIt {\n  return vformat_to(out, fmt::wstring_view(fmt),\n                    fmt::make_wformat_args(args...));\n}\n\n// Pass char_t as a default template parameter instead of using\n// std::basic_string<char_t<S>> to reduce the symbol size.\ntemplate <typename S, typename... T,\n          typename Char = detail::format_string_char_t<S>,\n          FMT_ENABLE_IF(!std::is_same<Char, char>::value &&\n                        !std::is_same<Char, wchar_t>::value)>\nauto format(const S& fmt, T&&... args) -> std::basic_string<Char> {\n  return vformat(detail::to_string_view(fmt),\n                 fmt::make_format_args<buffered_context<Char>>(args...));\n}\n\ntemplate <typename S, typename Char = detail::format_string_char_t<S>,\n          FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>\ninline auto vformat(locale_ref loc, const S& fmt,\n                    basic_format_args<buffered_context<Char>> args)\n    -> std::basic_string<Char> {\n  auto buf = basic_memory_buffer<Char>();\n  detail::vformat_to(buf, detail::to_string_view(fmt), args, loc);\n  return {buf.data(), buf.size()};\n}\n\ntemplate <typename S, typename... T,\n          typename Char = detail::format_string_char_t<S>,\n          FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>\ninline auto format(locale_ref loc, const S& fmt, T&&... args)\n    -> std::basic_string<Char> {\n  return vformat(loc, detail::to_string_view(fmt),\n                 fmt::make_format_args<buffered_context<Char>>(args...));\n}\n\ntemplate <typename OutputIt, typename S,\n          typename Char = detail::format_string_char_t<S>,\n          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&\n                            detail::is_exotic_char<Char>::value)>\nauto vformat_to(OutputIt out, const S& fmt,\n                basic_format_args<buffered_context<Char>> args) -> OutputIt {\n  auto&& buf = detail::get_buffer<Char>(out);\n  detail::vformat_to(buf, detail::to_string_view(fmt), args);\n  return detail::get_iterator(buf, out);\n}\n\ntemplate <typename OutputIt, typename S, typename... T,\n          typename Char = detail::format_string_char_t<S>,\n          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value &&\n                        !std::is_same<Char, char>::value &&\n                        !std::is_same<Char, wchar_t>::value)>\ninline auto format_to(OutputIt out, const S& fmt, T&&... args) -> OutputIt {\n  return vformat_to(out, detail::to_string_view(fmt),\n                    fmt::make_format_args<buffered_context<Char>>(args...));\n}\n\ntemplate <typename S, typename OutputIt, typename... Args,\n          typename Char = detail::format_string_char_t<S>,\n          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&\n                            detail::is_exotic_char<Char>::value)>\ninline auto vformat_to(OutputIt out, locale_ref loc, const S& fmt,\n                       basic_format_args<buffered_context<Char>> args)\n    -> OutputIt {\n  auto&& buf = detail::get_buffer<Char>(out);\n  vformat_to(buf, detail::to_string_view(fmt), args, loc);\n  return detail::get_iterator(buf, out);\n}\n\ntemplate <typename OutputIt, typename S, typename... T,\n          typename Char = detail::format_string_char_t<S>,\n          bool enable = detail::is_output_iterator<OutputIt, Char>::value &&\n                        detail::is_exotic_char<Char>::value>\ninline auto format_to(OutputIt out, locale_ref loc, const S& fmt, T&&... args)\n    -> typename std::enable_if<enable, OutputIt>::type {\n  return vformat_to(out, loc, detail::to_string_view(fmt),\n                    fmt::make_format_args<buffered_context<Char>>(args...));\n}\n\ntemplate <typename OutputIt, typename Char, typename... Args,\n          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&\n                            detail::is_exotic_char<Char>::value)>\ninline auto vformat_to_n(OutputIt out, size_t n, basic_string_view<Char> fmt,\n                         basic_format_args<buffered_context<Char>> args)\n    -> format_to_n_result<OutputIt> {\n  using traits = detail::fixed_buffer_traits;\n  auto buf = detail::iterator_buffer<OutputIt, Char, traits>(out, n);\n  detail::vformat_to(buf, fmt, args);\n  return {buf.out(), buf.count()};\n}\n\ntemplate <typename OutputIt, typename S, typename... T,\n          typename Char = detail::format_string_char_t<S>,\n          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&\n                            detail::is_exotic_char<Char>::value)>\ninline auto format_to_n(OutputIt out, size_t n, const S& fmt, T&&... args)\n    -> format_to_n_result<OutputIt> {\n  return vformat_to_n(out, n, fmt::basic_string_view<Char>(fmt),\n                      fmt::make_format_args<buffered_context<Char>>(args...));\n}\n\ntemplate <typename S, typename... T,\n          typename Char = detail::format_string_char_t<S>,\n          FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>\ninline auto formatted_size(const S& fmt, T&&... args) -> size_t {\n  auto buf = detail::counting_buffer<Char>();\n  detail::vformat_to(buf, detail::to_string_view(fmt),\n                     fmt::make_format_args<buffered_context<Char>>(args...));\n  return buf.count();\n}\n\ninline void vprint(std::FILE* f, wstring_view fmt, wformat_args args) {\n  auto buf = wmemory_buffer();\n  detail::vformat_to(buf, fmt, args);\n  buf.push_back(L'\\0');\n  if (std::fputws(buf.data(), f) == -1)\n    FMT_THROW(system_error(errno, FMT_STRING(\"cannot write to file\")));\n}\n\ninline void vprint(wstring_view fmt, wformat_args args) {\n  vprint(stdout, fmt, args);\n}\n\ntemplate <typename... T>\nvoid print(std::FILE* f, wformat_string<T...> fmt, T&&... args) {\n  return vprint(f, wstring_view(fmt), fmt::make_wformat_args(args...));\n}\n\ntemplate <typename... T> void print(wformat_string<T...> fmt, T&&... args) {\n  return vprint(wstring_view(fmt), fmt::make_wformat_args(args...));\n}\n\ntemplate <typename... T>\nvoid println(std::FILE* f, wformat_string<T...> fmt, T&&... args) {\n  return print(f, L\"{}\\n\", fmt::format(fmt, std::forward<T>(args)...));\n}\n\ntemplate <typename... T> void println(wformat_string<T...> fmt, T&&... args) {\n  return print(L\"{}\\n\", fmt::format(fmt, std::forward<T>(args)...));\n}\n\ninline auto vformat(text_style ts, wstring_view fmt, wformat_args args)\n    -> std::wstring {\n  auto buf = wmemory_buffer();\n  detail::vformat_to(buf, ts, fmt, args);\n  return {buf.data(), buf.size()};\n}\n\ntemplate <typename... T>\ninline auto format(text_style ts, wformat_string<T...> fmt, T&&... args)\n    -> std::wstring {\n  return fmt::vformat(ts, fmt, fmt::make_wformat_args(args...));\n}\n\ninline void vprint(std::wostream& os, wstring_view fmt, wformat_args args) {\n  auto buffer = basic_memory_buffer<wchar_t>();\n  detail::vformat_to(buffer, fmt, args);\n  detail::write_buffer(os, buffer);\n}\n\ntemplate <typename... T>\nvoid print(std::wostream& os, wformat_string<T...> fmt, T&&... args) {\n  vprint(os, fmt, fmt::make_format_args<buffered_context<wchar_t>>(args...));\n}\n\ntemplate <typename... T>\nvoid println(std::wostream& os, wformat_string<T...> fmt, T&&... args) {\n  print(os, L\"{}\\n\", fmt::format(fmt, std::forward<T>(args)...));\n}\n\n/// Converts `value` to `std::wstring` using the default format for type `T`.\ntemplate <typename T> inline auto to_wstring(const T& value) -> std::wstring {\n  return format(FMT_STRING(L\"{}\"), value);\n}\nFMT_END_EXPORT\nFMT_END_NAMESPACE\n\n#endif  // FMT_XCHAR_H_\n"
  },
  {
    "path": "include/widechar_width.hpp",
    "content": "/**\n * widechar_width.h for Unicode 17.0.0\n * See https://github.com/ridiculousfish/widecharwidth/\n *\n * SHA1 file hashes:\n *  (\n *  the hashes for generate.py and the template are git object hashes,\n *  use `git log --all --find-object=<hash>` in the widecharwidth repository\n *  to see which commit they correspond to,\n *  or run `git hash-object` on the file to compare.\n *  The other hashes are simple `sha1sum` style hashes.\n *  )\n *\n *  generate.py:         b35da43f176cc0d5880c67356ebb064048c5bac4\n *  template.js:         1249763c5b7c1e308aeb4ca64f1e15bce1fab9b3\n *  UnicodeData.txt:     50dffef1b7d1f97b72e4c2adceb9b2245f0f34ba\n *  EastAsianWidth.txt:  2cadc5034b6206ad84b75898a1d4186bb38fc12b\n *  emoji-data.txt:      3d123e12f70f63e609c4281ce83dfdd9ac7443d2\n */\n\n#ifndef WIDECHAR_WIDTH_H\n#define WIDECHAR_WIDTH_H\n\n#include <algorithm>\n#include <iterator>\n#include <cstddef>\n#include <cstdint>\n\nnamespace {\n\n/* Special width values */\nenum {\n  widechar_nonprint = 0,     // The character is not printable.\n  widechar_combining = 0,    // The character is a zero-width combiner.\n  widechar_ambiguous = 1,    // The character is East-Asian ambiguous width.\n  widechar_private_use = 1,  // The character is for private use.\n  widechar_unassigned = 0,   // The character is unassigned.\n  widechar_widened_in_9 = 2, // Width is 1 in Unicode 8, 2 in Unicode 9+.\n  widechar_non_character = 0 // The character is a noncharacter.\n};\n\n/* An inclusive range of characters. */\nstruct widechar_range {\n  uint32_t lo;\n  uint32_t hi;\n};\n\n/* Simple ASCII characters - used a lot, so we check them first. */\nstatic const struct widechar_range widechar_ascii_table[] = {\n    {0x00020, 0x0007E}\n};\n\n/* Private usage range. */\nstatic const struct widechar_range widechar_private_table[] = {\n    {0x0E000, 0x0F8FF},\n    {0xF0000, 0xFFFFD},\n    {0x100000, 0x10FFFD}\n};\n\n/* Nonprinting characters. */\nstatic const struct widechar_range widechar_nonprint_table[] = {\n    {0x00000, 0x0001F},\n    {0x0007F, 0x0009F},\n    {0x000AD, 0x000AD},\n    {0x00600, 0x00605},\n    {0x0061C, 0x0061C},\n    {0x006DD, 0x006DD},\n    {0x0070F, 0x0070F},\n    {0x00890, 0x00891},\n    {0x008E2, 0x008E2},\n    {0x0180E, 0x0180E},\n    {0x0200B, 0x0200F},\n    {0x02028, 0x0202E},\n    {0x02060, 0x02064},\n    {0x02066, 0x0206F},\n    {0x0D800, 0x0DFFF},\n    {0x0FEFF, 0x0FEFF},\n    {0x0FFF9, 0x0FFFB},\n    {0x110BD, 0x110BD},\n    {0x110CD, 0x110CD},\n    {0x13430, 0x1343F},\n    {0x1BCA0, 0x1BCA3},\n    {0x1D173, 0x1D17A},\n    {0xE0001, 0xE0001},\n    {0xE0020, 0xE007F}\n};\n\n/* Width 0 combining marks. */\nstatic const struct widechar_range widechar_combining_table[] = {\n    {0x00300, 0x0036F},\n    {0x00483, 0x00489},\n    {0x00591, 0x005BD},\n    {0x005BF, 0x005BF},\n    {0x005C1, 0x005C2},\n    {0x005C4, 0x005C5},\n    {0x005C7, 0x005C7},\n    {0x00610, 0x0061A},\n    {0x0064B, 0x0065F},\n    {0x00670, 0x00670},\n    {0x006D6, 0x006DC},\n    {0x006DF, 0x006E4},\n    {0x006E7, 0x006E8},\n    {0x006EA, 0x006ED},\n    {0x00711, 0x00711},\n    {0x00730, 0x0074A},\n    {0x007A6, 0x007B0},\n    {0x007EB, 0x007F3},\n    {0x007FD, 0x007FD},\n    {0x00816, 0x00819},\n    {0x0081B, 0x00823},\n    {0x00825, 0x00827},\n    {0x00829, 0x0082D},\n    {0x00859, 0x0085B},\n    {0x00897, 0x0089F},\n    {0x008CA, 0x008E1},\n    {0x008E3, 0x00903},\n    {0x0093A, 0x0093C},\n    {0x0093E, 0x0094F},\n    {0x00951, 0x00957},\n    {0x00962, 0x00963},\n    {0x00981, 0x00983},\n    {0x009BC, 0x009BC},\n    {0x009BE, 0x009C4},\n    {0x009C7, 0x009C8},\n    {0x009CB, 0x009CD},\n    {0x009D7, 0x009D7},\n    {0x009E2, 0x009E3},\n    {0x009FE, 0x009FE},\n    {0x00A01, 0x00A03},\n    {0x00A3C, 0x00A3C},\n    {0x00A3E, 0x00A42},\n    {0x00A47, 0x00A48},\n    {0x00A4B, 0x00A4D},\n    {0x00A51, 0x00A51},\n    {0x00A70, 0x00A71},\n    {0x00A75, 0x00A75},\n    {0x00A81, 0x00A83},\n    {0x00ABC, 0x00ABC},\n    {0x00ABE, 0x00AC5},\n    {0x00AC7, 0x00AC9},\n    {0x00ACB, 0x00ACD},\n    {0x00AE2, 0x00AE3},\n    {0x00AFA, 0x00AFF},\n    {0x00B01, 0x00B03},\n    {0x00B3C, 0x00B3C},\n    {0x00B3E, 0x00B44},\n    {0x00B47, 0x00B48},\n    {0x00B4B, 0x00B4D},\n    {0x00B55, 0x00B57},\n    {0x00B62, 0x00B63},\n    {0x00B82, 0x00B82},\n    {0x00BBE, 0x00BC2},\n    {0x00BC6, 0x00BC8},\n    {0x00BCA, 0x00BCD},\n    {0x00BD7, 0x00BD7},\n    {0x00C00, 0x00C04},\n    {0x00C3C, 0x00C3C},\n    {0x00C3E, 0x00C44},\n    {0x00C46, 0x00C48},\n    {0x00C4A, 0x00C4D},\n    {0x00C55, 0x00C56},\n    {0x00C62, 0x00C63},\n    {0x00C81, 0x00C83},\n    {0x00CBC, 0x00CBC},\n    {0x00CBE, 0x00CC4},\n    {0x00CC6, 0x00CC8},\n    {0x00CCA, 0x00CCD},\n    {0x00CD5, 0x00CD6},\n    {0x00CE2, 0x00CE3},\n    {0x00CF3, 0x00CF3},\n    {0x00D00, 0x00D03},\n    {0x00D3B, 0x00D3C},\n    {0x00D3E, 0x00D44},\n    {0x00D46, 0x00D48},\n    {0x00D4A, 0x00D4D},\n    {0x00D57, 0x00D57},\n    {0x00D62, 0x00D63},\n    {0x00D81, 0x00D83},\n    {0x00DCA, 0x00DCA},\n    {0x00DCF, 0x00DD4},\n    {0x00DD6, 0x00DD6},\n    {0x00DD8, 0x00DDF},\n    {0x00DF2, 0x00DF3},\n    {0x00E31, 0x00E31},\n    {0x00E34, 0x00E3A},\n    {0x00E47, 0x00E4E},\n    {0x00EB1, 0x00EB1},\n    {0x00EB4, 0x00EBC},\n    {0x00EC8, 0x00ECE},\n    {0x00F18, 0x00F19},\n    {0x00F35, 0x00F35},\n    {0x00F37, 0x00F37},\n    {0x00F39, 0x00F39},\n    {0x00F3E, 0x00F3F},\n    {0x00F71, 0x00F84},\n    {0x00F86, 0x00F87},\n    {0x00F8D, 0x00F97},\n    {0x00F99, 0x00FBC},\n    {0x00FC6, 0x00FC6},\n    {0x0102B, 0x0103E},\n    {0x01056, 0x01059},\n    {0x0105E, 0x01060},\n    {0x01062, 0x01064},\n    {0x01067, 0x0106D},\n    {0x01071, 0x01074},\n    {0x01082, 0x0108D},\n    {0x0108F, 0x0108F},\n    {0x0109A, 0x0109D},\n    {0x0135D, 0x0135F},\n    {0x01712, 0x01715},\n    {0x01732, 0x01734},\n    {0x01752, 0x01753},\n    {0x01772, 0x01773},\n    {0x017B4, 0x017D3},\n    {0x017DD, 0x017DD},\n    {0x0180B, 0x0180D},\n    {0x0180F, 0x0180F},\n    {0x01885, 0x01886},\n    {0x018A9, 0x018A9},\n    {0x01920, 0x0192B},\n    {0x01930, 0x0193B},\n    {0x01A17, 0x01A1B},\n    {0x01A55, 0x01A5E},\n    {0x01A60, 0x01A7C},\n    {0x01A7F, 0x01A7F},\n    {0x01AB0, 0x01ADD},\n    {0x01AE0, 0x01AEB},\n    {0x01B00, 0x01B04},\n    {0x01B34, 0x01B44},\n    {0x01B6B, 0x01B73},\n    {0x01B80, 0x01B82},\n    {0x01BA1, 0x01BAD},\n    {0x01BE6, 0x01BF3},\n    {0x01C24, 0x01C37},\n    {0x01CD0, 0x01CD2},\n    {0x01CD4, 0x01CE8},\n    {0x01CED, 0x01CED},\n    {0x01CF4, 0x01CF4},\n    {0x01CF7, 0x01CF9},\n    {0x01DC0, 0x01DFF},\n    {0x020D0, 0x020F0},\n    {0x02CEF, 0x02CF1},\n    {0x02D7F, 0x02D7F},\n    {0x02DE0, 0x02DFF},\n    {0x0302A, 0x0302F},\n    {0x03099, 0x0309A},\n    {0x0A66F, 0x0A672},\n    {0x0A674, 0x0A67D},\n    {0x0A69E, 0x0A69F},\n    {0x0A6F0, 0x0A6F1},\n    {0x0A802, 0x0A802},\n    {0x0A806, 0x0A806},\n    {0x0A80B, 0x0A80B},\n    {0x0A823, 0x0A827},\n    {0x0A82C, 0x0A82C},\n    {0x0A880, 0x0A881},\n    {0x0A8B4, 0x0A8C5},\n    {0x0A8E0, 0x0A8F1},\n    {0x0A8FF, 0x0A8FF},\n    {0x0A926, 0x0A92D},\n    {0x0A947, 0x0A953},\n    {0x0A980, 0x0A983},\n    {0x0A9B3, 0x0A9C0},\n    {0x0A9E5, 0x0A9E5},\n    {0x0AA29, 0x0AA36},\n    {0x0AA43, 0x0AA43},\n    {0x0AA4C, 0x0AA4D},\n    {0x0AA7B, 0x0AA7D},\n    {0x0AAB0, 0x0AAB0},\n    {0x0AAB2, 0x0AAB4},\n    {0x0AAB7, 0x0AAB8},\n    {0x0AABE, 0x0AABF},\n    {0x0AAC1, 0x0AAC1},\n    {0x0AAEB, 0x0AAEF},\n    {0x0AAF5, 0x0AAF6},\n    {0x0ABE3, 0x0ABEA},\n    {0x0ABEC, 0x0ABED},\n    {0x0FB1E, 0x0FB1E},\n    {0x0FE00, 0x0FE0F},\n    {0x0FE20, 0x0FE2F},\n    {0x101FD, 0x101FD},\n    {0x102E0, 0x102E0},\n    {0x10376, 0x1037A},\n    {0x10A01, 0x10A03},\n    {0x10A05, 0x10A06},\n    {0x10A0C, 0x10A0F},\n    {0x10A38, 0x10A3A},\n    {0x10A3F, 0x10A3F},\n    {0x10AE5, 0x10AE6},\n    {0x10D24, 0x10D27},\n    {0x10D69, 0x10D6D},\n    {0x10EAB, 0x10EAC},\n    {0x10EFA, 0x10EFF},\n    {0x10F46, 0x10F50},\n    {0x10F82, 0x10F85},\n    {0x11000, 0x11002},\n    {0x11038, 0x11046},\n    {0x11070, 0x11070},\n    {0x11073, 0x11074},\n    {0x1107F, 0x11082},\n    {0x110B0, 0x110BA},\n    {0x110C2, 0x110C2},\n    {0x11100, 0x11102},\n    {0x11127, 0x11134},\n    {0x11145, 0x11146},\n    {0x11173, 0x11173},\n    {0x11180, 0x11182},\n    {0x111B3, 0x111C0},\n    {0x111C9, 0x111CC},\n    {0x111CE, 0x111CF},\n    {0x1122C, 0x11237},\n    {0x1123E, 0x1123E},\n    {0x11241, 0x11241},\n    {0x112DF, 0x112EA},\n    {0x11300, 0x11303},\n    {0x1133B, 0x1133C},\n    {0x1133E, 0x11344},\n    {0x11347, 0x11348},\n    {0x1134B, 0x1134D},\n    {0x11357, 0x11357},\n    {0x11362, 0x11363},\n    {0x11366, 0x1136C},\n    {0x11370, 0x11374},\n    {0x113B8, 0x113C0},\n    {0x113C2, 0x113C2},\n    {0x113C5, 0x113C5},\n    {0x113C7, 0x113CA},\n    {0x113CC, 0x113D0},\n    {0x113D2, 0x113D2},\n    {0x113E1, 0x113E2},\n    {0x11435, 0x11446},\n    {0x1145E, 0x1145E},\n    {0x114B0, 0x114C3},\n    {0x115AF, 0x115B5},\n    {0x115B8, 0x115C0},\n    {0x115DC, 0x115DD},\n    {0x11630, 0x11640},\n    {0x116AB, 0x116B7},\n    {0x1171D, 0x1172B},\n    {0x1182C, 0x1183A},\n    {0x11930, 0x11935},\n    {0x11937, 0x11938},\n    {0x1193B, 0x1193E},\n    {0x11940, 0x11940},\n    {0x11942, 0x11943},\n    {0x119D1, 0x119D7},\n    {0x119DA, 0x119E0},\n    {0x119E4, 0x119E4},\n    {0x11A01, 0x11A0A},\n    {0x11A33, 0x11A39},\n    {0x11A3B, 0x11A3E},\n    {0x11A47, 0x11A47},\n    {0x11A51, 0x11A5B},\n    {0x11A8A, 0x11A99},\n    {0x11B60, 0x11B67},\n    {0x11C2F, 0x11C36},\n    {0x11C38, 0x11C3F},\n    {0x11C92, 0x11CA7},\n    {0x11CA9, 0x11CB6},\n    {0x11D31, 0x11D36},\n    {0x11D3A, 0x11D3A},\n    {0x11D3C, 0x11D3D},\n    {0x11D3F, 0x11D45},\n    {0x11D47, 0x11D47},\n    {0x11D8A, 0x11D8E},\n    {0x11D90, 0x11D91},\n    {0x11D93, 0x11D97},\n    {0x11EF3, 0x11EF6},\n    {0x11F00, 0x11F01},\n    {0x11F03, 0x11F03},\n    {0x11F34, 0x11F3A},\n    {0x11F3E, 0x11F42},\n    {0x11F5A, 0x11F5A},\n    {0x13440, 0x13440},\n    {0x13447, 0x13455},\n    {0x1611E, 0x1612F},\n    {0x16AF0, 0x16AF4},\n    {0x16B30, 0x16B36},\n    {0x16F4F, 0x16F4F},\n    {0x16F51, 0x16F87},\n    {0x16F8F, 0x16F92},\n    {0x16FE4, 0x16FE4},\n    {0x16FF0, 0x16FF1},\n    {0x1BC9D, 0x1BC9E},\n    {0x1CF00, 0x1CF2D},\n    {0x1CF30, 0x1CF46},\n    {0x1D165, 0x1D169},\n    {0x1D16D, 0x1D172},\n    {0x1D17B, 0x1D182},\n    {0x1D185, 0x1D18B},\n    {0x1D1AA, 0x1D1AD},\n    {0x1D242, 0x1D244},\n    {0x1DA00, 0x1DA36},\n    {0x1DA3B, 0x1DA6C},\n    {0x1DA75, 0x1DA75},\n    {0x1DA84, 0x1DA84},\n    {0x1DA9B, 0x1DA9F},\n    {0x1DAA1, 0x1DAAF},\n    {0x1E000, 0x1E006},\n    {0x1E008, 0x1E018},\n    {0x1E01B, 0x1E021},\n    {0x1E023, 0x1E024},\n    {0x1E026, 0x1E02A},\n    {0x1E08F, 0x1E08F},\n    {0x1E130, 0x1E136},\n    {0x1E2AE, 0x1E2AE},\n    {0x1E2EC, 0x1E2EF},\n    {0x1E4EC, 0x1E4EF},\n    {0x1E5EE, 0x1E5EF},\n    {0x1E6E3, 0x1E6E3},\n    {0x1E6E6, 0x1E6E6},\n    {0x1E6EE, 0x1E6EF},\n    {0x1E6F5, 0x1E6F5},\n    {0x1E8D0, 0x1E8D6},\n    {0x1E944, 0x1E94A},\n    {0xE0100, 0xE01EF}\n};\n\n/* Width 0 combining letters. */\nstatic const struct widechar_range widechar_combiningletters_table[] = {\n    {0x01160, 0x011FF},\n    {0x0D7B0, 0x0D7FF}\n};\n\n/* Width 2 characters. */\nstatic const struct widechar_range widechar_doublewide_table[] = {\n    {0x01100, 0x0115F},\n    {0x02329, 0x0232A},\n    {0x02630, 0x02637},\n    {0x0268A, 0x0268F},\n    {0x02E80, 0x02E99},\n    {0x02E9B, 0x02EF3},\n    {0x02F00, 0x02FD5},\n    {0x02FF0, 0x0303E},\n    {0x03041, 0x03096},\n    {0x03099, 0x030FF},\n    {0x03105, 0x0312F},\n    {0x03131, 0x0318E},\n    {0x03190, 0x031E5},\n    {0x031EF, 0x0321E},\n    {0x03220, 0x03247},\n    {0x03250, 0x0A48C},\n    {0x0A490, 0x0A4C6},\n    {0x0A960, 0x0A97C},\n    {0x0AC00, 0x0D7A3},\n    {0x0F900, 0x0FAFF},\n    {0x0FE10, 0x0FE19},\n    {0x0FE30, 0x0FE52},\n    {0x0FE54, 0x0FE66},\n    {0x0FE68, 0x0FE6B},\n    {0x0FF01, 0x0FF60},\n    {0x0FFE0, 0x0FFE6},\n    {0x16FE0, 0x16FE4},\n    {0x16FF0, 0x16FF6},\n    {0x17000, 0x18CD5},\n    {0x18CFF, 0x18D1E},\n    {0x18D80, 0x18DF2},\n    {0x1AFF0, 0x1AFF3},\n    {0x1AFF5, 0x1AFFB},\n    {0x1AFFD, 0x1AFFE},\n    {0x1B000, 0x1B122},\n    {0x1B132, 0x1B132},\n    {0x1B150, 0x1B152},\n    {0x1B155, 0x1B155},\n    {0x1B164, 0x1B167},\n    {0x1B170, 0x1B2FB},\n    {0x1D300, 0x1D356},\n    {0x1D360, 0x1D376},\n    {0x1F200, 0x1F200},\n    {0x1F202, 0x1F202},\n    {0x1F210, 0x1F219},\n    {0x1F21B, 0x1F22E},\n    {0x1F230, 0x1F231},\n    {0x1F237, 0x1F237},\n    {0x1F23B, 0x1F23B},\n    {0x1F240, 0x1F248},\n    {0x1F260, 0x1F265},\n    {0x1F57A, 0x1F57A},\n    {0x1F5A4, 0x1F5A4},\n    {0x1F6D1, 0x1F6D2},\n    {0x1F6D5, 0x1F6D8},\n    {0x1F6DC, 0x1F6DF},\n    {0x1F6F4, 0x1F6FC},\n    {0x1F7E0, 0x1F7EB},\n    {0x1F7F0, 0x1F7F0},\n    {0x1F90C, 0x1F90F},\n    {0x1F919, 0x1F93A},\n    {0x1F93C, 0x1F945},\n    {0x1F947, 0x1F97F},\n    {0x1F985, 0x1F9BF},\n    {0x1F9C1, 0x1F9FF},\n    {0x1FA70, 0x1FA7C},\n    {0x1FA80, 0x1FA8A},\n    {0x1FA8E, 0x1FAC6},\n    {0x1FAC8, 0x1FAC8},\n    {0x1FACD, 0x1FADC},\n    {0x1FADF, 0x1FAEA},\n    {0x1FAEF, 0x1FAF8},\n    {0x20000, 0x2FFFD},\n    {0x30000, 0x3FFFD}\n};\n\n/* Ambiguous-width characters. */\nstatic const struct widechar_range widechar_ambiguous_table[] = {\n    {0x000A1, 0x000A1},\n    {0x000A4, 0x000A4},\n    {0x000A7, 0x000A8},\n    {0x000AA, 0x000AA},\n    {0x000AD, 0x000AE},\n    {0x000B0, 0x000B4},\n    {0x000B6, 0x000BA},\n    {0x000BC, 0x000BF},\n    {0x000C6, 0x000C6},\n    {0x000D0, 0x000D0},\n    {0x000D7, 0x000D8},\n    {0x000DE, 0x000E1},\n    {0x000E6, 0x000E6},\n    {0x000E8, 0x000EA},\n    {0x000EC, 0x000ED},\n    {0x000F0, 0x000F0},\n    {0x000F2, 0x000F3},\n    {0x000F7, 0x000FA},\n    {0x000FC, 0x000FC},\n    {0x000FE, 0x000FE},\n    {0x00101, 0x00101},\n    {0x00111, 0x00111},\n    {0x00113, 0x00113},\n    {0x0011B, 0x0011B},\n    {0x00126, 0x00127},\n    {0x0012B, 0x0012B},\n    {0x00131, 0x00133},\n    {0x00138, 0x00138},\n    {0x0013F, 0x00142},\n    {0x00144, 0x00144},\n    {0x00148, 0x0014B},\n    {0x0014D, 0x0014D},\n    {0x00152, 0x00153},\n    {0x00166, 0x00167},\n    {0x0016B, 0x0016B},\n    {0x001CE, 0x001CE},\n    {0x001D0, 0x001D0},\n    {0x001D2, 0x001D2},\n    {0x001D4, 0x001D4},\n    {0x001D6, 0x001D6},\n    {0x001D8, 0x001D8},\n    {0x001DA, 0x001DA},\n    {0x001DC, 0x001DC},\n    {0x00251, 0x00251},\n    {0x00261, 0x00261},\n    {0x002C4, 0x002C4},\n    {0x002C7, 0x002C7},\n    {0x002C9, 0x002CB},\n    {0x002CD, 0x002CD},\n    {0x002D0, 0x002D0},\n    {0x002D8, 0x002DB},\n    {0x002DD, 0x002DD},\n    {0x002DF, 0x002DF},\n    {0x00300, 0x0036F},\n    {0x00391, 0x003A1},\n    {0x003A3, 0x003A9},\n    {0x003B1, 0x003C1},\n    {0x003C3, 0x003C9},\n    {0x00401, 0x00401},\n    {0x00410, 0x0044F},\n    {0x00451, 0x00451},\n    {0x02010, 0x02010},\n    {0x02013, 0x02016},\n    {0x02018, 0x02019},\n    {0x0201C, 0x0201D},\n    {0x02020, 0x02022},\n    {0x02024, 0x02027},\n    {0x02030, 0x02030},\n    {0x02032, 0x02033},\n    {0x02035, 0x02035},\n    {0x0203B, 0x0203B},\n    {0x0203E, 0x0203E},\n    {0x02074, 0x02074},\n    {0x0207F, 0x0207F},\n    {0x02081, 0x02084},\n    {0x020AC, 0x020AC},\n    {0x02103, 0x02103},\n    {0x02105, 0x02105},\n    {0x02109, 0x02109},\n    {0x02113, 0x02113},\n    {0x02116, 0x02116},\n    {0x02121, 0x02122},\n    {0x02126, 0x02126},\n    {0x0212B, 0x0212B},\n    {0x02153, 0x02154},\n    {0x0215B, 0x0215E},\n    {0x02160, 0x0216B},\n    {0x02170, 0x02179},\n    {0x02189, 0x02189},\n    {0x02190, 0x02199},\n    {0x021B8, 0x021B9},\n    {0x021D2, 0x021D2},\n    {0x021D4, 0x021D4},\n    {0x021E7, 0x021E7},\n    {0x02200, 0x02200},\n    {0x02202, 0x02203},\n    {0x02207, 0x02208},\n    {0x0220B, 0x0220B},\n    {0x0220F, 0x0220F},\n    {0x02211, 0x02211},\n    {0x02215, 0x02215},\n    {0x0221A, 0x0221A},\n    {0x0221D, 0x02220},\n    {0x02223, 0x02223},\n    {0x02225, 0x02225},\n    {0x02227, 0x0222C},\n    {0x0222E, 0x0222E},\n    {0x02234, 0x02237},\n    {0x0223C, 0x0223D},\n    {0x02248, 0x02248},\n    {0x0224C, 0x0224C},\n    {0x02252, 0x02252},\n    {0x02260, 0x02261},\n    {0x02264, 0x02267},\n    {0x0226A, 0x0226B},\n    {0x0226E, 0x0226F},\n    {0x02282, 0x02283},\n    {0x02286, 0x02287},\n    {0x02295, 0x02295},\n    {0x02299, 0x02299},\n    {0x022A5, 0x022A5},\n    {0x022BF, 0x022BF},\n    {0x02312, 0x02312},\n    {0x02460, 0x024E9},\n    {0x024EB, 0x0254B},\n    {0x02550, 0x02573},\n    {0x02580, 0x0258F},\n    {0x02592, 0x02595},\n    {0x025A0, 0x025A1},\n    {0x025A3, 0x025A9},\n    {0x025B2, 0x025B3},\n    {0x025B6, 0x025B7},\n    {0x025BC, 0x025BD},\n    {0x025C0, 0x025C1},\n    {0x025C6, 0x025C8},\n    {0x025CB, 0x025CB},\n    {0x025CE, 0x025D1},\n    {0x025E2, 0x025E5},\n    {0x025EF, 0x025EF},\n    {0x02605, 0x02606},\n    {0x02609, 0x02609},\n    {0x0260E, 0x0260F},\n    {0x0261C, 0x0261C},\n    {0x0261E, 0x0261E},\n    {0x02640, 0x02640},\n    {0x02642, 0x02642},\n    {0x02660, 0x02661},\n    {0x02663, 0x02665},\n    {0x02667, 0x0266A},\n    {0x0266C, 0x0266D},\n    {0x0266F, 0x0266F},\n    {0x0269E, 0x0269F},\n    {0x026BF, 0x026BF},\n    {0x026C6, 0x026CD},\n    {0x026CF, 0x026D3},\n    {0x026D5, 0x026E1},\n    {0x026E3, 0x026E3},\n    {0x026E8, 0x026E9},\n    {0x026EB, 0x026F1},\n    {0x026F4, 0x026F4},\n    {0x026F6, 0x026F9},\n    {0x026FB, 0x026FC},\n    {0x026FE, 0x026FF},\n    {0x0273D, 0x0273D},\n    {0x02776, 0x0277F},\n    {0x02B56, 0x02B59},\n    {0x03248, 0x0324F},\n    {0x0E000, 0x0F8FF},\n    {0x0FE00, 0x0FE0F},\n    {0x0FFFD, 0x0FFFD},\n    {0x1F100, 0x1F10A},\n    {0x1F110, 0x1F12D},\n    {0x1F130, 0x1F169},\n    {0x1F170, 0x1F18D},\n    {0x1F18F, 0x1F190},\n    {0x1F19B, 0x1F1AC},\n    {0xE0100, 0xE01EF},\n    {0xF0000, 0xFFFFD},\n    {0x100000, 0x10FFFD}\n};\n\n/* Unassigned characters. */\nstatic const struct widechar_range widechar_unassigned_table[] = {\n    {0x00378, 0x00379},\n    {0x00380, 0x00383},\n    {0x0038B, 0x0038B},\n    {0x0038D, 0x0038D},\n    {0x003A2, 0x003A2},\n    {0x00530, 0x00530},\n    {0x00557, 0x00558},\n    {0x0058B, 0x0058C},\n    {0x00590, 0x00590},\n    {0x005C8, 0x005CF},\n    {0x005EB, 0x005EE},\n    {0x005F5, 0x005FF},\n    {0x0070E, 0x0070E},\n    {0x0074B, 0x0074C},\n    {0x007B2, 0x007BF},\n    {0x007FB, 0x007FC},\n    {0x0082E, 0x0082F},\n    {0x0083F, 0x0083F},\n    {0x0085C, 0x0085D},\n    {0x0085F, 0x0085F},\n    {0x0086B, 0x0086F},\n    {0x00892, 0x00896},\n    {0x00984, 0x00984},\n    {0x0098D, 0x0098E},\n    {0x00991, 0x00992},\n    {0x009A9, 0x009A9},\n    {0x009B1, 0x009B1},\n    {0x009B3, 0x009B5},\n    {0x009BA, 0x009BB},\n    {0x009C5, 0x009C6},\n    {0x009C9, 0x009CA},\n    {0x009CF, 0x009D6},\n    {0x009D8, 0x009DB},\n    {0x009DE, 0x009DE},\n    {0x009E4, 0x009E5},\n    {0x009FF, 0x00A00},\n    {0x00A04, 0x00A04},\n    {0x00A0B, 0x00A0E},\n    {0x00A11, 0x00A12},\n    {0x00A29, 0x00A29},\n    {0x00A31, 0x00A31},\n    {0x00A34, 0x00A34},\n    {0x00A37, 0x00A37},\n    {0x00A3A, 0x00A3B},\n    {0x00A3D, 0x00A3D},\n    {0x00A43, 0x00A46},\n    {0x00A49, 0x00A4A},\n    {0x00A4E, 0x00A50},\n    {0x00A52, 0x00A58},\n    {0x00A5D, 0x00A5D},\n    {0x00A5F, 0x00A65},\n    {0x00A77, 0x00A80},\n    {0x00A84, 0x00A84},\n    {0x00A8E, 0x00A8E},\n    {0x00A92, 0x00A92},\n    {0x00AA9, 0x00AA9},\n    {0x00AB1, 0x00AB1},\n    {0x00AB4, 0x00AB4},\n    {0x00ABA, 0x00ABB},\n    {0x00AC6, 0x00AC6},\n    {0x00ACA, 0x00ACA},\n    {0x00ACE, 0x00ACF},\n    {0x00AD1, 0x00ADF},\n    {0x00AE4, 0x00AE5},\n    {0x00AF2, 0x00AF8},\n    {0x00B00, 0x00B00},\n    {0x00B04, 0x00B04},\n    {0x00B0D, 0x00B0E},\n    {0x00B11, 0x00B12},\n    {0x00B29, 0x00B29},\n    {0x00B31, 0x00B31},\n    {0x00B34, 0x00B34},\n    {0x00B3A, 0x00B3B},\n    {0x00B45, 0x00B46},\n    {0x00B49, 0x00B4A},\n    {0x00B4E, 0x00B54},\n    {0x00B58, 0x00B5B},\n    {0x00B5E, 0x00B5E},\n    {0x00B64, 0x00B65},\n    {0x00B78, 0x00B81},\n    {0x00B84, 0x00B84},\n    {0x00B8B, 0x00B8D},\n    {0x00B91, 0x00B91},\n    {0x00B96, 0x00B98},\n    {0x00B9B, 0x00B9B},\n    {0x00B9D, 0x00B9D},\n    {0x00BA0, 0x00BA2},\n    {0x00BA5, 0x00BA7},\n    {0x00BAB, 0x00BAD},\n    {0x00BBA, 0x00BBD},\n    {0x00BC3, 0x00BC5},\n    {0x00BC9, 0x00BC9},\n    {0x00BCE, 0x00BCF},\n    {0x00BD1, 0x00BD6},\n    {0x00BD8, 0x00BE5},\n    {0x00BFB, 0x00BFF},\n    {0x00C0D, 0x00C0D},\n    {0x00C11, 0x00C11},\n    {0x00C29, 0x00C29},\n    {0x00C3A, 0x00C3B},\n    {0x00C45, 0x00C45},\n    {0x00C49, 0x00C49},\n    {0x00C4E, 0x00C54},\n    {0x00C57, 0x00C57},\n    {0x00C5B, 0x00C5B},\n    {0x00C5E, 0x00C5F},\n    {0x00C64, 0x00C65},\n    {0x00C70, 0x00C76},\n    {0x00C8D, 0x00C8D},\n    {0x00C91, 0x00C91},\n    {0x00CA9, 0x00CA9},\n    {0x00CB4, 0x00CB4},\n    {0x00CBA, 0x00CBB},\n    {0x00CC5, 0x00CC5},\n    {0x00CC9, 0x00CC9},\n    {0x00CCE, 0x00CD4},\n    {0x00CD7, 0x00CDB},\n    {0x00CDF, 0x00CDF},\n    {0x00CE4, 0x00CE5},\n    {0x00CF0, 0x00CF0},\n    {0x00CF4, 0x00CFF},\n    {0x00D0D, 0x00D0D},\n    {0x00D11, 0x00D11},\n    {0x00D45, 0x00D45},\n    {0x00D49, 0x00D49},\n    {0x00D50, 0x00D53},\n    {0x00D64, 0x00D65},\n    {0x00D80, 0x00D80},\n    {0x00D84, 0x00D84},\n    {0x00D97, 0x00D99},\n    {0x00DB2, 0x00DB2},\n    {0x00DBC, 0x00DBC},\n    {0x00DBE, 0x00DBF},\n    {0x00DC7, 0x00DC9},\n    {0x00DCB, 0x00DCE},\n    {0x00DD5, 0x00DD5},\n    {0x00DD7, 0x00DD7},\n    {0x00DE0, 0x00DE5},\n    {0x00DF0, 0x00DF1},\n    {0x00DF5, 0x00E00},\n    {0x00E3B, 0x00E3E},\n    {0x00E5C, 0x00E80},\n    {0x00E83, 0x00E83},\n    {0x00E85, 0x00E85},\n    {0x00E8B, 0x00E8B},\n    {0x00EA4, 0x00EA4},\n    {0x00EA6, 0x00EA6},\n    {0x00EBE, 0x00EBF},\n    {0x00EC5, 0x00EC5},\n    {0x00EC7, 0x00EC7},\n    {0x00ECF, 0x00ECF},\n    {0x00EDA, 0x00EDB},\n    {0x00EE0, 0x00EFF},\n    {0x00F48, 0x00F48},\n    {0x00F6D, 0x00F70},\n    {0x00F98, 0x00F98},\n    {0x00FBD, 0x00FBD},\n    {0x00FCD, 0x00FCD},\n    {0x00FDB, 0x00FFF},\n    {0x010C6, 0x010C6},\n    {0x010C8, 0x010CC},\n    {0x010CE, 0x010CF},\n    {0x01249, 0x01249},\n    {0x0124E, 0x0124F},\n    {0x01257, 0x01257},\n    {0x01259, 0x01259},\n    {0x0125E, 0x0125F},\n    {0x01289, 0x01289},\n    {0x0128E, 0x0128F},\n    {0x012B1, 0x012B1},\n    {0x012B6, 0x012B7},\n    {0x012BF, 0x012BF},\n    {0x012C1, 0x012C1},\n    {0x012C6, 0x012C7},\n    {0x012D7, 0x012D7},\n    {0x01311, 0x01311},\n    {0x01316, 0x01317},\n    {0x0135B, 0x0135C},\n    {0x0137D, 0x0137F},\n    {0x0139A, 0x0139F},\n    {0x013F6, 0x013F7},\n    {0x013FE, 0x013FF},\n    {0x0169D, 0x0169F},\n    {0x016F9, 0x016FF},\n    {0x01716, 0x0171E},\n    {0x01737, 0x0173F},\n    {0x01754, 0x0175F},\n    {0x0176D, 0x0176D},\n    {0x01771, 0x01771},\n    {0x01774, 0x0177F},\n    {0x017DE, 0x017DF},\n    {0x017EA, 0x017EF},\n    {0x017FA, 0x017FF},\n    {0x0181A, 0x0181F},\n    {0x01879, 0x0187F},\n    {0x018AB, 0x018AF},\n    {0x018F6, 0x018FF},\n    {0x0191F, 0x0191F},\n    {0x0192C, 0x0192F},\n    {0x0193C, 0x0193F},\n    {0x01941, 0x01943},\n    {0x0196E, 0x0196F},\n    {0x01975, 0x0197F},\n    {0x019AC, 0x019AF},\n    {0x019CA, 0x019CF},\n    {0x019DB, 0x019DD},\n    {0x01A1C, 0x01A1D},\n    {0x01A5F, 0x01A5F},\n    {0x01A7D, 0x01A7E},\n    {0x01A8A, 0x01A8F},\n    {0x01A9A, 0x01A9F},\n    {0x01AAE, 0x01AAF},\n    {0x01ADE, 0x01ADF},\n    {0x01AEC, 0x01AFF},\n    {0x01B4D, 0x01B4D},\n    {0x01BF4, 0x01BFB},\n    {0x01C38, 0x01C3A},\n    {0x01C4A, 0x01C4C},\n    {0x01C8B, 0x01C8F},\n    {0x01CBB, 0x01CBC},\n    {0x01CC8, 0x01CCF},\n    {0x01CFB, 0x01CFF},\n    {0x01F16, 0x01F17},\n    {0x01F1E, 0x01F1F},\n    {0x01F46, 0x01F47},\n    {0x01F4E, 0x01F4F},\n    {0x01F58, 0x01F58},\n    {0x01F5A, 0x01F5A},\n    {0x01F5C, 0x01F5C},\n    {0x01F5E, 0x01F5E},\n    {0x01F7E, 0x01F7F},\n    {0x01FB5, 0x01FB5},\n    {0x01FC5, 0x01FC5},\n    {0x01FD4, 0x01FD5},\n    {0x01FDC, 0x01FDC},\n    {0x01FF0, 0x01FF1},\n    {0x01FF5, 0x01FF5},\n    {0x01FFF, 0x01FFF},\n    {0x02065, 0x02065},\n    {0x02072, 0x02073},\n    {0x0208F, 0x0208F},\n    {0x0209D, 0x0209F},\n    {0x020C2, 0x020CF},\n    {0x020F1, 0x020FF},\n    {0x0218C, 0x0218F},\n    {0x0242A, 0x0243F},\n    {0x0244B, 0x0245F},\n    {0x02B74, 0x02B75},\n    {0x02CF4, 0x02CF8},\n    {0x02D26, 0x02D26},\n    {0x02D28, 0x02D2C},\n    {0x02D2E, 0x02D2F},\n    {0x02D68, 0x02D6E},\n    {0x02D71, 0x02D7E},\n    {0x02D97, 0x02D9F},\n    {0x02DA7, 0x02DA7},\n    {0x02DAF, 0x02DAF},\n    {0x02DB7, 0x02DB7},\n    {0x02DBF, 0x02DBF},\n    {0x02DC7, 0x02DC7},\n    {0x02DCF, 0x02DCF},\n    {0x02DD7, 0x02DD7},\n    {0x02DDF, 0x02DDF},\n    {0x02E5E, 0x02E7F},\n    {0x02E9A, 0x02E9A},\n    {0x02EF4, 0x02EFF},\n    {0x02FD6, 0x02FEF},\n    {0x03040, 0x03040},\n    {0x03097, 0x03098},\n    {0x03100, 0x03104},\n    {0x03130, 0x03130},\n    {0x0318F, 0x0318F},\n    {0x031E6, 0x031EE},\n    {0x0321F, 0x0321F},\n    {0x03401, 0x04DBE},\n    {0x04E01, 0x09FFE},\n    {0x0A48D, 0x0A48F},\n    {0x0A4C7, 0x0A4CF},\n    {0x0A62C, 0x0A63F},\n    {0x0A6F8, 0x0A6FF},\n    {0x0A7DD, 0x0A7F0},\n    {0x0A82D, 0x0A82F},\n    {0x0A83A, 0x0A83F},\n    {0x0A878, 0x0A87F},\n    {0x0A8C6, 0x0A8CD},\n    {0x0A8DA, 0x0A8DF},\n    {0x0A954, 0x0A95E},\n    {0x0A97D, 0x0A97F},\n    {0x0A9CE, 0x0A9CE},\n    {0x0A9DA, 0x0A9DD},\n    {0x0A9FF, 0x0A9FF},\n    {0x0AA37, 0x0AA3F},\n    {0x0AA4E, 0x0AA4F},\n    {0x0AA5A, 0x0AA5B},\n    {0x0AAC3, 0x0AADA},\n    {0x0AAF7, 0x0AB00},\n    {0x0AB07, 0x0AB08},\n    {0x0AB0F, 0x0AB10},\n    {0x0AB17, 0x0AB1F},\n    {0x0AB27, 0x0AB27},\n    {0x0AB2F, 0x0AB2F},\n    {0x0AB6C, 0x0AB6F},\n    {0x0ABEE, 0x0ABEF},\n    {0x0ABFA, 0x0ABFF},\n    {0x0AC01, 0x0D7A2},\n    {0x0D7A4, 0x0D7AF},\n    {0x0D7C7, 0x0D7CA},\n    {0x0D7FC, 0x0D7FF},\n    {0x0FA6E, 0x0FA6F},\n    {0x0FADA, 0x0FAFF},\n    {0x0FB07, 0x0FB12},\n    {0x0FB18, 0x0FB1C},\n    {0x0FB37, 0x0FB37},\n    {0x0FB3D, 0x0FB3D},\n    {0x0FB3F, 0x0FB3F},\n    {0x0FB42, 0x0FB42},\n    {0x0FB45, 0x0FB45},\n    {0x0FE1A, 0x0FE1F},\n    {0x0FE53, 0x0FE53},\n    {0x0FE67, 0x0FE67},\n    {0x0FE6C, 0x0FE6F},\n    {0x0FE75, 0x0FE75},\n    {0x0FEFD, 0x0FEFE},\n    {0x0FF00, 0x0FF00},\n    {0x0FFBF, 0x0FFC1},\n    {0x0FFC8, 0x0FFC9},\n    {0x0FFD0, 0x0FFD1},\n    {0x0FFD8, 0x0FFD9},\n    {0x0FFDD, 0x0FFDF},\n    {0x0FFE7, 0x0FFE7},\n    {0x0FFEF, 0x0FFF8},\n    {0x1000C, 0x1000C},\n    {0x10027, 0x10027},\n    {0x1003B, 0x1003B},\n    {0x1003E, 0x1003E},\n    {0x1004E, 0x1004F},\n    {0x1005E, 0x1007F},\n    {0x100FB, 0x100FF},\n    {0x10103, 0x10106},\n    {0x10134, 0x10136},\n    {0x1018F, 0x1018F},\n    {0x1019D, 0x1019F},\n    {0x101A1, 0x101CF},\n    {0x101FE, 0x1027F},\n    {0x1029D, 0x1029F},\n    {0x102D1, 0x102DF},\n    {0x102FC, 0x102FF},\n    {0x10324, 0x1032C},\n    {0x1034B, 0x1034F},\n    {0x1037B, 0x1037F},\n    {0x1039E, 0x1039E},\n    {0x103C4, 0x103C7},\n    {0x103D6, 0x103FF},\n    {0x1049E, 0x1049F},\n    {0x104AA, 0x104AF},\n    {0x104D4, 0x104D7},\n    {0x104FC, 0x104FF},\n    {0x10528, 0x1052F},\n    {0x10564, 0x1056E},\n    {0x1057B, 0x1057B},\n    {0x1058B, 0x1058B},\n    {0x10593, 0x10593},\n    {0x10596, 0x10596},\n    {0x105A2, 0x105A2},\n    {0x105B2, 0x105B2},\n    {0x105BA, 0x105BA},\n    {0x105BD, 0x105BF},\n    {0x105F4, 0x105FF},\n    {0x10737, 0x1073F},\n    {0x10756, 0x1075F},\n    {0x10768, 0x1077F},\n    {0x10786, 0x10786},\n    {0x107B1, 0x107B1},\n    {0x107BB, 0x107FF},\n    {0x10806, 0x10807},\n    {0x10809, 0x10809},\n    {0x10836, 0x10836},\n    {0x10839, 0x1083B},\n    {0x1083D, 0x1083E},\n    {0x10856, 0x10856},\n    {0x1089F, 0x108A6},\n    {0x108B0, 0x108DF},\n    {0x108F3, 0x108F3},\n    {0x108F6, 0x108FA},\n    {0x1091C, 0x1091E},\n    {0x1093A, 0x1093E},\n    {0x1095A, 0x1097F},\n    {0x109B8, 0x109BB},\n    {0x109D0, 0x109D1},\n    {0x10A04, 0x10A04},\n    {0x10A07, 0x10A0B},\n    {0x10A14, 0x10A14},\n    {0x10A18, 0x10A18},\n    {0x10A36, 0x10A37},\n    {0x10A3B, 0x10A3E},\n    {0x10A49, 0x10A4F},\n    {0x10A59, 0x10A5F},\n    {0x10AA0, 0x10ABF},\n    {0x10AE7, 0x10AEA},\n    {0x10AF7, 0x10AFF},\n    {0x10B36, 0x10B38},\n    {0x10B56, 0x10B57},\n    {0x10B73, 0x10B77},\n    {0x10B92, 0x10B98},\n    {0x10B9D, 0x10BA8},\n    {0x10BB0, 0x10BFF},\n    {0x10C49, 0x10C7F},\n    {0x10CB3, 0x10CBF},\n    {0x10CF3, 0x10CF9},\n    {0x10D28, 0x10D2F},\n    {0x10D3A, 0x10D3F},\n    {0x10D66, 0x10D68},\n    {0x10D86, 0x10D8D},\n    {0x10D90, 0x10E5F},\n    {0x10E7F, 0x10E7F},\n    {0x10EAA, 0x10EAA},\n    {0x10EAE, 0x10EAF},\n    {0x10EB2, 0x10EC1},\n    {0x10EC8, 0x10ECF},\n    {0x10ED9, 0x10EF9},\n    {0x10F28, 0x10F2F},\n    {0x10F5A, 0x10F6F},\n    {0x10F8A, 0x10FAF},\n    {0x10FCC, 0x10FDF},\n    {0x10FF7, 0x10FFF},\n    {0x1104E, 0x11051},\n    {0x11076, 0x1107E},\n    {0x110C3, 0x110CC},\n    {0x110CE, 0x110CF},\n    {0x110E9, 0x110EF},\n    {0x110FA, 0x110FF},\n    {0x11135, 0x11135},\n    {0x11148, 0x1114F},\n    {0x11177, 0x1117F},\n    {0x111E0, 0x111E0},\n    {0x111F5, 0x111FF},\n    {0x11212, 0x11212},\n    {0x11242, 0x1127F},\n    {0x11287, 0x11287},\n    {0x11289, 0x11289},\n    {0x1128E, 0x1128E},\n    {0x1129E, 0x1129E},\n    {0x112AA, 0x112AF},\n    {0x112EB, 0x112EF},\n    {0x112FA, 0x112FF},\n    {0x11304, 0x11304},\n    {0x1130D, 0x1130E},\n    {0x11311, 0x11312},\n    {0x11329, 0x11329},\n    {0x11331, 0x11331},\n    {0x11334, 0x11334},\n    {0x1133A, 0x1133A},\n    {0x11345, 0x11346},\n    {0x11349, 0x1134A},\n    {0x1134E, 0x1134F},\n    {0x11351, 0x11356},\n    {0x11358, 0x1135C},\n    {0x11364, 0x11365},\n    {0x1136D, 0x1136F},\n    {0x11375, 0x1137F},\n    {0x1138A, 0x1138A},\n    {0x1138C, 0x1138D},\n    {0x1138F, 0x1138F},\n    {0x113B6, 0x113B6},\n    {0x113C1, 0x113C1},\n    {0x113C3, 0x113C4},\n    {0x113C6, 0x113C6},\n    {0x113CB, 0x113CB},\n    {0x113D6, 0x113D6},\n    {0x113D9, 0x113E0},\n    {0x113E3, 0x113FF},\n    {0x1145C, 0x1145C},\n    {0x11462, 0x1147F},\n    {0x114C8, 0x114CF},\n    {0x114DA, 0x1157F},\n    {0x115B6, 0x115B7},\n    {0x115DE, 0x115FF},\n    {0x11645, 0x1164F},\n    {0x1165A, 0x1165F},\n    {0x1166D, 0x1167F},\n    {0x116BA, 0x116BF},\n    {0x116CA, 0x116CF},\n    {0x116E4, 0x116FF},\n    {0x1171B, 0x1171C},\n    {0x1172C, 0x1172F},\n    {0x11747, 0x117FF},\n    {0x1183C, 0x1189F},\n    {0x118F3, 0x118FE},\n    {0x11907, 0x11908},\n    {0x1190A, 0x1190B},\n    {0x11914, 0x11914},\n    {0x11917, 0x11917},\n    {0x11936, 0x11936},\n    {0x11939, 0x1193A},\n    {0x11947, 0x1194F},\n    {0x1195A, 0x1199F},\n    {0x119A8, 0x119A9},\n    {0x119D8, 0x119D9},\n    {0x119E5, 0x119FF},\n    {0x11A48, 0x11A4F},\n    {0x11AA3, 0x11AAF},\n    {0x11AF9, 0x11AFF},\n    {0x11B0A, 0x11B5F},\n    {0x11B68, 0x11BBF},\n    {0x11BE2, 0x11BEF},\n    {0x11BFA, 0x11BFF},\n    {0x11C09, 0x11C09},\n    {0x11C37, 0x11C37},\n    {0x11C46, 0x11C4F},\n    {0x11C6D, 0x11C6F},\n    {0x11C90, 0x11C91},\n    {0x11CA8, 0x11CA8},\n    {0x11CB7, 0x11CFF},\n    {0x11D07, 0x11D07},\n    {0x11D0A, 0x11D0A},\n    {0x11D37, 0x11D39},\n    {0x11D3B, 0x11D3B},\n    {0x11D3E, 0x11D3E},\n    {0x11D48, 0x11D4F},\n    {0x11D5A, 0x11D5F},\n    {0x11D66, 0x11D66},\n    {0x11D69, 0x11D69},\n    {0x11D8F, 0x11D8F},\n    {0x11D92, 0x11D92},\n    {0x11D99, 0x11D9F},\n    {0x11DAA, 0x11DAF},\n    {0x11DDC, 0x11DDF},\n    {0x11DEA, 0x11EDF},\n    {0x11EF9, 0x11EFF},\n    {0x11F11, 0x11F11},\n    {0x11F3B, 0x11F3D},\n    {0x11F5B, 0x11FAF},\n    {0x11FB1, 0x11FBF},\n    {0x11FF2, 0x11FFE},\n    {0x1239A, 0x123FF},\n    {0x1246F, 0x1246F},\n    {0x12475, 0x1247F},\n    {0x12544, 0x12F8F},\n    {0x12FF3, 0x12FFF},\n    {0x13456, 0x1345F},\n    {0x143FB, 0x143FF},\n    {0x14647, 0x160FF},\n    {0x1613A, 0x167FF},\n    {0x16A39, 0x16A3F},\n    {0x16A5F, 0x16A5F},\n    {0x16A6A, 0x16A6D},\n    {0x16ABF, 0x16ABF},\n    {0x16ACA, 0x16ACF},\n    {0x16AEE, 0x16AEF},\n    {0x16AF6, 0x16AFF},\n    {0x16B46, 0x16B4F},\n    {0x16B5A, 0x16B5A},\n    {0x16B62, 0x16B62},\n    {0x16B78, 0x16B7C},\n    {0x16B90, 0x16D3F},\n    {0x16D7A, 0x16E3F},\n    {0x16E9B, 0x16E9F},\n    {0x16EB9, 0x16EBA},\n    {0x16ED4, 0x16EFF},\n    {0x16F4B, 0x16F4E},\n    {0x16F88, 0x16F8E},\n    {0x16FA0, 0x16FDF},\n    {0x16FE5, 0x16FEF},\n    {0x16FF7, 0x16FFF},\n    {0x17001, 0x187FE},\n    {0x18CD6, 0x18CFE},\n    {0x18D01, 0x18D1D},\n    {0x18D1F, 0x18D7F},\n    {0x18DF3, 0x1AFEF},\n    {0x1AFF4, 0x1AFF4},\n    {0x1AFFC, 0x1AFFC},\n    {0x1AFFF, 0x1AFFF},\n    {0x1B123, 0x1B131},\n    {0x1B133, 0x1B14F},\n    {0x1B153, 0x1B154},\n    {0x1B156, 0x1B163},\n    {0x1B168, 0x1B16F},\n    {0x1B2FC, 0x1BBFF},\n    {0x1BC6B, 0x1BC6F},\n    {0x1BC7D, 0x1BC7F},\n    {0x1BC89, 0x1BC8F},\n    {0x1BC9A, 0x1BC9B},\n    {0x1BCA4, 0x1CBFF},\n    {0x1CCFD, 0x1CCFF},\n    {0x1CEB4, 0x1CEB9},\n    {0x1CED1, 0x1CEDF},\n    {0x1CEF1, 0x1CEFF},\n    {0x1CF2E, 0x1CF2F},\n    {0x1CF47, 0x1CF4F},\n    {0x1CFC4, 0x1CFFF},\n    {0x1D0F6, 0x1D0FF},\n    {0x1D127, 0x1D128},\n    {0x1D1EB, 0x1D1FF},\n    {0x1D246, 0x1D2BF},\n    {0x1D2D4, 0x1D2DF},\n    {0x1D2F4, 0x1D2FF},\n    {0x1D357, 0x1D35F},\n    {0x1D379, 0x1D3FF},\n    {0x1D455, 0x1D455},\n    {0x1D49D, 0x1D49D},\n    {0x1D4A0, 0x1D4A1},\n    {0x1D4A3, 0x1D4A4},\n    {0x1D4A7, 0x1D4A8},\n    {0x1D4AD, 0x1D4AD},\n    {0x1D4BA, 0x1D4BA},\n    {0x1D4BC, 0x1D4BC},\n    {0x1D4C4, 0x1D4C4},\n    {0x1D506, 0x1D506},\n    {0x1D50B, 0x1D50C},\n    {0x1D515, 0x1D515},\n    {0x1D51D, 0x1D51D},\n    {0x1D53A, 0x1D53A},\n    {0x1D53F, 0x1D53F},\n    {0x1D545, 0x1D545},\n    {0x1D547, 0x1D549},\n    {0x1D551, 0x1D551},\n    {0x1D6A6, 0x1D6A7},\n    {0x1D7CC, 0x1D7CD},\n    {0x1DA8C, 0x1DA9A},\n    {0x1DAA0, 0x1DAA0},\n    {0x1DAB0, 0x1DEFF},\n    {0x1DF1F, 0x1DF24},\n    {0x1DF2B, 0x1DFFF},\n    {0x1E007, 0x1E007},\n    {0x1E019, 0x1E01A},\n    {0x1E022, 0x1E022},\n    {0x1E025, 0x1E025},\n    {0x1E02B, 0x1E02F},\n    {0x1E06E, 0x1E08E},\n    {0x1E090, 0x1E0FF},\n    {0x1E12D, 0x1E12F},\n    {0x1E13E, 0x1E13F},\n    {0x1E14A, 0x1E14D},\n    {0x1E150, 0x1E28F},\n    {0x1E2AF, 0x1E2BF},\n    {0x1E2FA, 0x1E2FE},\n    {0x1E300, 0x1E4CF},\n    {0x1E4FA, 0x1E5CF},\n    {0x1E5FB, 0x1E5FE},\n    {0x1E600, 0x1E6BF},\n    {0x1E6DF, 0x1E6DF},\n    {0x1E6F6, 0x1E6FD},\n    {0x1E700, 0x1E7DF},\n    {0x1E7E7, 0x1E7E7},\n    {0x1E7EC, 0x1E7EC},\n    {0x1E7EF, 0x1E7EF},\n    {0x1E7FF, 0x1E7FF},\n    {0x1E8C5, 0x1E8C6},\n    {0x1E8D7, 0x1E8FF},\n    {0x1E94C, 0x1E94F},\n    {0x1E95A, 0x1E95D},\n    {0x1E960, 0x1EC70},\n    {0x1ECB5, 0x1ED00},\n    {0x1ED3E, 0x1EDFF},\n    {0x1EE04, 0x1EE04},\n    {0x1EE20, 0x1EE20},\n    {0x1EE23, 0x1EE23},\n    {0x1EE25, 0x1EE26},\n    {0x1EE28, 0x1EE28},\n    {0x1EE33, 0x1EE33},\n    {0x1EE38, 0x1EE38},\n    {0x1EE3A, 0x1EE3A},\n    {0x1EE3C, 0x1EE41},\n    {0x1EE43, 0x1EE46},\n    {0x1EE48, 0x1EE48},\n    {0x1EE4A, 0x1EE4A},\n    {0x1EE4C, 0x1EE4C},\n    {0x1EE50, 0x1EE50},\n    {0x1EE53, 0x1EE53},\n    {0x1EE55, 0x1EE56},\n    {0x1EE58, 0x1EE58},\n    {0x1EE5A, 0x1EE5A},\n    {0x1EE5C, 0x1EE5C},\n    {0x1EE5E, 0x1EE5E},\n    {0x1EE60, 0x1EE60},\n    {0x1EE63, 0x1EE63},\n    {0x1EE65, 0x1EE66},\n    {0x1EE6B, 0x1EE6B},\n    {0x1EE73, 0x1EE73},\n    {0x1EE78, 0x1EE78},\n    {0x1EE7D, 0x1EE7D},\n    {0x1EE7F, 0x1EE7F},\n    {0x1EE8A, 0x1EE8A},\n    {0x1EE9C, 0x1EEA0},\n    {0x1EEA4, 0x1EEA4},\n    {0x1EEAA, 0x1EEAA},\n    {0x1EEBC, 0x1EEEF},\n    {0x1EEF2, 0x1EFFF},\n    {0x1F02C, 0x1F02F},\n    {0x1F094, 0x1F09F},\n    {0x1F0AF, 0x1F0B0},\n    {0x1F0C0, 0x1F0C0},\n    {0x1F0D0, 0x1F0D0},\n    {0x1F0F6, 0x1F0FF},\n    {0x1F1AE, 0x1F1E5},\n    {0x1F203, 0x1F20F},\n    {0x1F23C, 0x1F23F},\n    {0x1F249, 0x1F24F},\n    {0x1F252, 0x1F25F},\n    {0x1F266, 0x1F2FF},\n    {0x1F6D9, 0x1F6DB},\n    {0x1F6ED, 0x1F6EF},\n    {0x1F6FD, 0x1F6FF},\n    {0x1F7DA, 0x1F7DF},\n    {0x1F7EC, 0x1F7EF},\n    {0x1F7F1, 0x1F7FF},\n    {0x1F80C, 0x1F80F},\n    {0x1F848, 0x1F84F},\n    {0x1F85A, 0x1F85F},\n    {0x1F888, 0x1F88F},\n    {0x1F8AE, 0x1F8AF},\n    {0x1F8BC, 0x1F8BF},\n    {0x1F8C2, 0x1F8CF},\n    {0x1F8D9, 0x1F8FF},\n    {0x1FA58, 0x1FA5F},\n    {0x1FA6E, 0x1FA6F},\n    {0x1FA7D, 0x1FA7F},\n    {0x1FA8B, 0x1FA8D},\n    {0x1FAC7, 0x1FAC7},\n    {0x1FAC9, 0x1FACC},\n    {0x1FADD, 0x1FADE},\n    {0x1FAEB, 0x1FAEE},\n    {0x1FAF9, 0x1FAFF},\n    {0x1FB93, 0x1FB93},\n    {0x1FBFB, 0x1FFFD},\n    {0x20001, 0x2A6DE},\n    {0x2A6E0, 0x2A6FF},\n    {0x2A701, 0x2B73E},\n    {0x2B741, 0x2B81C},\n    {0x2B81E, 0x2B81F},\n    {0x2B821, 0x2CEAC},\n    {0x2CEAE, 0x2CEAF},\n    {0x2CEB1, 0x2EBDF},\n    {0x2EBE1, 0x2EBEF},\n    {0x2EBF1, 0x2EE5C},\n    {0x2EE5E, 0x2F7FF},\n    {0x2FA1E, 0x2FFFD},\n    {0x30001, 0x31349},\n    {0x3134B, 0x3134F},\n    {0x31351, 0x323AE},\n    {0x323B1, 0x33478},\n    {0x3347A, 0x3FFFD},\n    {0x40000, 0x4FFFD},\n    {0x50000, 0x5FFFD},\n    {0x60000, 0x6FFFD},\n    {0x70000, 0x7FFFD},\n    {0x80000, 0x8FFFD},\n    {0x90000, 0x9FFFD},\n    {0xA0000, 0xAFFFD},\n    {0xB0000, 0xBFFFD},\n    {0xC0000, 0xCFFFD},\n    {0xD0000, 0xDFFFD},\n    {0xE0000, 0xE0000},\n    {0xE0002, 0xE001F},\n    {0xE0080, 0xE00FF},\n    {0xE01F0, 0xEFFFD}\n};\n\n/* Non-characters. */\nstatic const struct widechar_range widechar_nonchar_table[] = {\n    {0x0FDD0, 0x0FDEF},\n    {0x0FFFE, 0x0FFFF},\n    {0x1FFFE, 0x1FFFF},\n    {0x2FFFE, 0x2FFFF},\n    {0x3FFFE, 0x3FFFF},\n    {0x4FFFE, 0x4FFFF},\n    {0x5FFFE, 0x5FFFF},\n    {0x6FFFE, 0x6FFFF},\n    {0x7FFFE, 0x7FFFF},\n    {0x8FFFE, 0x8FFFF},\n    {0x9FFFE, 0x9FFFF},\n    {0xAFFFE, 0xAFFFF},\n    {0xBFFFE, 0xBFFFF},\n    {0xCFFFE, 0xCFFFF},\n    {0xDFFFE, 0xDFFFF},\n    {0xEFFFE, 0xEFFFF},\n    {0xFFFFE, 0xFFFFF},\n    {0x10FFFE, 0x10FFFF}\n};\n\n/* Characters that were widened from width 1 to 2 in Unicode 9. */\nstatic const struct widechar_range widechar_widened_table[] = {\n    {0x0231A, 0x0231B},\n    {0x023E9, 0x023EC},\n    {0x023F0, 0x023F0},\n    {0x023F3, 0x023F3},\n    {0x025FD, 0x025FE},\n    {0x02614, 0x02615},\n    {0x02648, 0x02653},\n    {0x0267F, 0x0267F},\n    {0x02693, 0x02693},\n    {0x026A1, 0x026A1},\n    {0x026AA, 0x026AB},\n    {0x026BD, 0x026BE},\n    {0x026C4, 0x026C5},\n    {0x026CE, 0x026CE},\n    {0x026D4, 0x026D4},\n    {0x026EA, 0x026EA},\n    {0x026F2, 0x026F3},\n    {0x026F5, 0x026F5},\n    {0x026FA, 0x026FA},\n    {0x026FD, 0x026FD},\n    {0x02705, 0x02705},\n    {0x0270A, 0x0270B},\n    {0x02728, 0x02728},\n    {0x0274C, 0x0274C},\n    {0x0274E, 0x0274E},\n    {0x02753, 0x02755},\n    {0x02757, 0x02757},\n    {0x02795, 0x02797},\n    {0x027B0, 0x027B0},\n    {0x027BF, 0x027BF},\n    {0x02B1B, 0x02B1C},\n    {0x02B50, 0x02B50},\n    {0x02B55, 0x02B55},\n    {0x1F004, 0x1F004},\n    {0x1F0CF, 0x1F0CF},\n    {0x1F18E, 0x1F18E},\n    {0x1F191, 0x1F19A},\n    {0x1F201, 0x1F201},\n    {0x1F21A, 0x1F21A},\n    {0x1F22F, 0x1F22F},\n    {0x1F232, 0x1F236},\n    {0x1F238, 0x1F23A},\n    {0x1F250, 0x1F251},\n    {0x1F300, 0x1F320},\n    {0x1F32D, 0x1F335},\n    {0x1F337, 0x1F37C},\n    {0x1F37E, 0x1F393},\n    {0x1F3A0, 0x1F3CA},\n    {0x1F3CF, 0x1F3D3},\n    {0x1F3E0, 0x1F3F0},\n    {0x1F3F4, 0x1F3F4},\n    {0x1F3F8, 0x1F43E},\n    {0x1F440, 0x1F440},\n    {0x1F442, 0x1F4FC},\n    {0x1F4FF, 0x1F53D},\n    {0x1F54B, 0x1F54E},\n    {0x1F550, 0x1F567},\n    {0x1F595, 0x1F596},\n    {0x1F5FB, 0x1F64F},\n    {0x1F680, 0x1F6C5},\n    {0x1F6CC, 0x1F6CC},\n    {0x1F6D0, 0x1F6D0},\n    {0x1F6EB, 0x1F6EC},\n    {0x1F910, 0x1F918},\n    {0x1F980, 0x1F984},\n    {0x1F9C0, 0x1F9C0}\n};\n\ntemplate<typename Collection>\nbool widechar_in_table(const Collection &arr, uint32_t c) {\n    auto where = std::lower_bound(std::begin(arr), std::end(arr), c,\n        [](widechar_range p, uint32_t c) { return p.hi < c; });\n    return where != std::end(arr) && where->lo <= c;\n}\n\n/* Return the width of character c, or a special negative value. */\nint widechar_wcwidth(uint32_t c) {\n    if (widechar_in_table(widechar_ascii_table, c))\n        return 1;\n    if (widechar_in_table(widechar_private_table, c))\n        return widechar_private_use;\n    if (widechar_in_table(widechar_nonprint_table, c))\n        return widechar_nonprint;\n    if (widechar_in_table(widechar_nonchar_table, c))\n        return widechar_non_character;\n    if (widechar_in_table(widechar_combining_table, c))\n        return widechar_combining;\n    if (widechar_in_table(widechar_combiningletters_table, c))\n        return widechar_combining;\n    if (widechar_in_table(widechar_doublewide_table, c))\n        return 2;\n    if (widechar_in_table(widechar_ambiguous_table, c))\n        return widechar_ambiguous;\n    if (widechar_in_table(widechar_unassigned_table, c))\n        return widechar_unassigned;\n    if (widechar_in_table(widechar_widened_table, c))\n        return widechar_widened_in_9;\n    return 1;\n}\n\n} // namespace\n#endif // WIDECHAR_WIDTH_H"
  },
  {
    "path": "manpage.md",
    "content": "% btop(1) | User Commands\n%\n% 2025-05-01\n\n# NAME\n\nbtop - Resource monitor that shows usage and stats for processor, memory, disks, network, and processes.\n\n# SYNOPSIS\n\n**btop** [**-c** _file_] [**-d**] [**-f** _filter_] [**-l**] [**-p** _id_] [**-t**] [**-u** _ms_] [**\\-\\-force-utf**] [**\\-\\-themes-dir** _dir_]\n\n**btop** [**\\-\\-default-config** | {**-h** | **\\-\\-help**} | {**-V** | **\\-\\-version**}]\n\n# DESCRIPTION\n\n**btop** is a program that shows usage and stats for processor, memory, disks, network, and processes.\n\n# OPTIONS\n\nThe program follows the usual GNU command line syntax, with long options\nstarting with two dashes ('-'). A summary of options is included below.\n\n**-c**, **\\-\\-config _file_**\n:   Path to a config file.\n\n**-d**, **\\-\\-debug**\n:   Start in debug mode with additional logs and metrics.\n\n**-f**, **\\-\\-filter _filter_**\n:   Set an initial process filter.\n\n**\\-\\-force-utf**\n:   Force start even if no UTF-8 locale was detected.\n\n**-l**, **\\-\\-low-color**\n:   Disable true color, 256 colors only.\n\n**-p**, **\\-\\-preset _id_**\n:   Start with a preset (0-9).\n\n**-t**, **\\-\\-tty**\n:   Force tty mode with ANSI graph symbols and 16 colors only.\n\n**\\-\\-no-tty**\n:   Force disable tty mode.\n\n**\\-\\-themes-dir _dir_**\n:   Path to a custom themes directory. When specified, this directory takes priority over the default theme search paths.\n\n**-u**, **\\-\\-update _ms_**\n:   Set an initial update rate in milliseconds.\n\n**\\-\\-default-config**\n:   Print default config to standard output.\n\n**-h**, **\\-\\-help**\n:   Show summary of options.\n\n**-V**, **\\-\\-version**\n:   Show version of program.\n\n# BUGS\n\nThe upstream bug tracker can be found at https://github.com/aristocratos/btop/issues.\n\n# SEE ALSO\n\n**top**(1), **htop**(1)\n\n# AUTHOR\n\n**btop** was written by Jakob P. Liljenberg a.k.a. \"Aristocratos\".\n"
  },
  {
    "path": "snap/snapcraft.yaml",
    "content": "name: btop\nadopt-info: btop\nsummary: Resource monitor that shows usage and stats\ndescription: |\n  Resource monitor that shows usage and stats for processor, memory, disks, network and processes.\n  C++ version and continuation of bashtop and bpytop.\nlicense: Apache-2.0\n\nbase: core24\ngrade: stable\nconfinement: strict\ncompression: lzo\n\ncontact: https://github.com/kz6fittycent/btop/issues\nissues: https://github.com/kz6fittycent/btop/issues\nsource-code: https://github.com/aristocratos/btop\n\nplatforms:\n  amd64:\n    build-on: [amd64]\n    build-for: [amd64]\n  arm64:\n    build-on: [arm64]\n    build-for: [arm64]\n\napps:\n  btop:\n    command: usr/local/bin/btop\n    environment:\n      LC_ALL: C.UTF-8\n      LANG: C.UTF-8\n    plugs:\n      - mount-observe\n      - process-control\n      - system-observe\n      - hardware-observe\n      - network\n      - network-observe\n      - home\n      - removable-media\n      - opengl\n\nparts:\n  btop:\n    source: https://github.com/aristocratos/btop\n    source-type: git\n    plugin: make\n    make-parameters:\n      - CC=gcc-14\n      - CXX=g++-14\n      - PREFIX=/usr/local\n      - STATIC=true #required\n      - ADDFLAGS=\"-D SNAPPED\" #required\n    build-packages:\n      - coreutils\n      - sed\n      - git\n      - build-essential\n      - gcc-14\n      - g++-14\n    \n    override-pull: |\n      craftctl default\n      craftctl set version=\"$(git describe --tags | sed 's/^v//' | cut -d \"-\" -f1)\"\n"
  },
  {
    "path": "src/btop.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include \"btop.hpp\"\n\n#include <algorithm>\n#include <atomic>\n#include <csignal>\n#include <clocale>\n#include <filesystem>\n#include <iterator>\n#include <mutex>\n#include <optional>\n#include <pthread.h>\n#include <span>\n#include <string_view>\n#ifdef __FreeBSD__\n\t#include <pthread_np.h>\n#endif\n#include <thread>\n#include <numeric>\n#include <ranges>\n#include <unistd.h>\n#include <cmath>\n#include <iostream>\n#include <exception>\n#include <tuple>\n#include <regex>\n#include <chrono>\n#include <utility>\n#include <semaphore>\n\n#ifdef __APPLE__\n\t#include <CoreFoundation/CoreFoundation.h>\n\t#include <mach-o/dyld.h>\n\t#include <limits.h>\n#endif\n\n#ifdef __NetBSD__\n\t#include <sys/param.h>\n\t#include <sys/sysctl.h>\n\t#include <unistd.h>\n#endif\n\n#include <fmt/core.h>\n#include <fmt/ostream.h>\n\n#include \"btop_cli.hpp\"\n#include \"btop_config.hpp\"\n#include \"btop_draw.hpp\"\n#include \"btop_input.hpp\"\n#include \"btop_log.hpp\"\n#include \"btop_menu.hpp\"\n#include \"btop_shared.hpp\"\n#include \"btop_theme.hpp\"\n#include \"btop_tools.hpp\"\n\nusing std::atomic;\nusing std::cout;\nusing std::flush;\nusing std::min;\nusing std::string;\nusing std::string_view;\nusing std::to_string;\nusing std::vector;\n\nnamespace fs = std::filesystem;\n\nusing namespace Tools;\nusing namespace std::chrono_literals;\nusing namespace std::literals;\n\nnamespace Global {\n\tconst vector<array<string, 2>> Banner_src = {\n\t\t{\"#E62525\", \"██████╗ ████████╗ ██████╗ ██████╗\"},\n\t\t{\"#CD2121\", \"██╔══██╗╚══██╔══╝██╔═══██╗██╔══██╗   ██╗    ██╗\"},\n\t\t{\"#B31D1D\", \"██████╔╝   ██║   ██║   ██║██████╔╝ ██████╗██████╗\"},\n\t\t{\"#9A1919\", \"██╔══██╗   ██║   ██║   ██║██╔═══╝  ╚═██╔═╝╚═██╔═╝\"},\n\t\t{\"#801414\", \"██████╔╝   ██║   ╚██████╔╝██║        ╚═╝    ╚═╝\"},\n\t\t{\"#000000\", \"╚═════╝    ╚═╝    ╚═════╝ ╚═╝\"},\n\t};\n\tconst string Version = \"1.4.6\";\n\n\tint coreCount;\n\tstring overlay;\n\tstring clock;\n\n\tstring bg_black = \"\\x1b[0;40m\";\n\tstring fg_white = \"\\x1b[1;97m\";\n\tstring fg_green = \"\\x1b[1;92m\";\n\tstring fg_red = \"\\x1b[0;91m\";\n\n\tuid_t real_uid, set_uid;\n\n\tfs::path self_path;\n\n\tstring exit_error_msg;\n\tatomic<bool> thread_exception (false);\n\n\tbool debug{};\n\n\tuint64_t start_time;\n\n\tatomic<bool> resized (false);\n\tatomic<bool> quitting (false);\n\tatomic<bool> should_quit (false);\n\tatomic<bool> should_sleep (false);\n\tatomic<bool> _runner_started (false);\n\tatomic<bool> init_conf (false);\n\tatomic<bool> reload_conf (false);\n}\n\nnamespace Runner {\n\tstatic pthread_t runner_id;\n} // namespace Runner\n\n//* Handler for SIGWINCH and general resizing events, does nothing if terminal hasn't been resized unless force=true\nvoid term_resize(bool force) {\n\tstatic atomic<bool> resizing (false);\n\tif (Input::polling) {\n\t\tGlobal::resized = true;\n\t\tInput::interrupt();\n\t\treturn;\n\t}\n\tatomic_lock lck(resizing, true);\n\tif (auto refreshed = Term::refresh(true); refreshed or force) {\n\t\tif (force and refreshed) force = false;\n\t}\n\telse return;\n#ifdef GPU_SUPPORT\n\tstatic const array<string, 10> all_boxes = {\"gpu5\", \"cpu\", \"mem\", \"net\", \"proc\", \"gpu0\", \"gpu1\", \"gpu2\", \"gpu3\", \"gpu4\"};\n#else\n\tstatic const array<string, 5> all_boxes = {\"\", \"cpu\", \"mem\", \"net\", \"proc\"};\n#endif\n\tGlobal::resized = true;\n\tif (Runner::active) Runner::stop();\n\tTerm::refresh();\n\tConfig::unlock();\n\n\tauto boxes = Config::getS(\"shown_boxes\");\n\tauto min_size = Term::get_min_size(boxes);\n\tauto minWidth = min_size.at(0), minHeight = min_size.at(1);\n\n\twhile (not force or (Term::width < minWidth or Term::height < minHeight)) {\n\t\tsleep_ms(100);\n\t\tif (Term::width < minWidth or Term::height < minHeight) {\n\t\t\tint width = Term::width, height = Term::height;\n\t\t\tcout << fmt::format(\"{clear}{bg_black}{fg_white}\"\n\t\t\t\t\t\"{mv1}Terminal size too small:\"\n\t\t\t\t\t\"{mv2} Width = {fg_width}{width} {fg_white}Height = {fg_height}{height}\"\n\t\t\t\t\t\"{mv3}{fg_white}Needed for current config:\"\n\t\t\t\t\t\"{mv4}Width = {minWidth} Height = {minHeight}\",\n\t\t\t\t\t\"clear\"_a = Term::clear, \"bg_black\"_a = Global::bg_black, \"fg_white\"_a = Global::fg_white,\n\t\t\t\t\t\"mv1\"_a = Mv::to((height / 2) - 2, (width / 2) - 11),\n\t\t\t\t\t\"mv2\"_a = Mv::to((height / 2) - 1, (width / 2) - 10),\n\t\t\t\t\t\t\"fg_width\"_a = (width < minWidth ? Global::fg_red : Global::fg_green),\n\t\t\t\t\t\t\"width\"_a = width,\n\t\t\t\t\t\t\"fg_height\"_a = (height < minHeight ? Global::fg_red : Global::fg_green),\n\t\t\t\t\t\t\"height\"_a = height,\n\t\t\t\t\t\"mv3\"_a = Mv::to((height / 2) + 1, (width / 2) - 12),\n\t\t\t\t\t\"mv4\"_a = Mv::to((height / 2) + 2, (width / 2) - 10),\n\t\t\t\t\t\t\"minWidth\"_a = minWidth,\n\t\t\t\t\t\t\"minHeight\"_a = minHeight\n\t\t\t) << std::flush;\n\n\t\t\tbool got_key = false;\n\t\t\tfor (; not Term::refresh() and not got_key; got_key = Input::poll(10));\n\t\t\tif (got_key) {\n\t\t\t\tauto key = Input::get();\n\t\t\t\tif (key == \"q\")\n\t\t\t\t\tclean_quit(0);\n\t\t\t\telse if (key.size() == 1 and isint(key)) {\n\t\t\t\t\tauto intKey = stoi(key);\n\t\t\t\t#ifdef GPU_SUPPORT\n\t\t\t\t\tif ((intKey == 0 and Gpu::count >= 5) or (intKey >= 5 and intKey - 4 <= Gpu::count)) {\n\t\t\t\t#else\n\t\t\t\t\tif (intKey > 0 and intKey < 5) {\n\t\t\t\t#endif\n\t\t\t\t\t\tconst auto& box = all_boxes.at(intKey);\n\t\t\t\t\t\tConfig::current_preset.reset();\n\t\t\t\t\t\tConfig::toggle_box(box);\n\t\t\t\t\t\tboxes = Config::getS(\"shown_boxes\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tmin_size = Term::get_min_size(boxes);\n\t\t\tminWidth = min_size.at(0);\n\t\t\tminHeight = min_size.at(1);\n\t\t}\n\t\telse if (not Term::refresh()) break;\n\t}\n\n\tInput::interrupt();\n}\n\n//* Exit handler; stops threads, restores terminal and saves config changes\nvoid clean_quit(int sig) {\n\tif (Global::quitting) return;\n\tGlobal::quitting = true;\n\tRunner::stop();\n\tif (Global::_runner_started) {\n\t#if defined __APPLE__ || defined __OpenBSD__ || defined __NetBSD__\n\t\tif (pthread_join(Runner::runner_id, nullptr) != 0) {\n\t\t\tLogger::warning(\"Failed to join _runner thread on exit!\");\n\t\t\tpthread_cancel(Runner::runner_id);\n\t\t}\n\t#else\n\t\tconstexpr struct timespec ts { .tv_sec = 5, .tv_nsec = 0 };\n\t\tif (pthread_timedjoin_np(Runner::runner_id, nullptr, &ts) != 0) {\n\t\t\tLogger::warning(\"Failed to join _runner thread on exit!\");\n\t\t\tpthread_cancel(Runner::runner_id);\n\t\t}\n\t#endif\n\t}\n\n#ifdef GPU_SUPPORT\n\tGpu::Nvml::shutdown();\n\tGpu::Rsmi::shutdown();\n\t#ifdef __APPLE__\n\tGpu::AppleSilicon::shutdown();\n\t#endif\n#endif\n\n\n\tif (Config::getB(\"save_config_on_exit\")) {\n\t\tConfig::write();\n\t}\n\n\tif (Term::initialized) {\n\t\tInput::clear();\n\t\tTerm::restore();\n\t}\n\n\tif (not Global::exit_error_msg.empty()) {\n\t\tsig = 1;\n\t\tLogger::error(\"{}\", Global::exit_error_msg);\n\t\tfmt::println(std::cerr, \"{}ERROR: {}{}{}\", Global::fg_red, Global::fg_white, Global::exit_error_msg, Fx::reset);\n\t}\n\tLogger::info(\"Quitting! Runtime: {}\", sec_to_dhms(time_s() - Global::start_time));\n\n\tconst auto excode = (sig != -1 ? sig : 0);\n\n#if defined __APPLE__ || defined __OpenBSD__ || defined __NetBSD__\n\t_Exit(excode);\n#else\n\tquick_exit(excode);\n#endif\n}\n\n//* Handler for SIGTSTP; stops threads, restores terminal and sends SIGSTOP\nstatic void _sleep() {\n\tRunner::stop();\n\tTerm::restore();\n\tstd::raise(SIGSTOP);\n}\n\n//* Handler for SIGCONT; re-initialize terminal and force a resize event\nstatic void _resume() {\n\tTerm::init();\n\tterm_resize(true);\n}\n\nstatic void _exit_handler() {\n\tclean_quit(-1);\n}\n\nstatic void _crash_handler(const int sig) {\n\t// Restore terminal before crashing\n\tif (Term::initialized) {\n\t\tTerm::restore();\n\t}\n\t// Re-raise the signal to get default behavior (core dump)\n\tstd::signal(sig, SIG_DFL);\n\tstd::raise(sig);\n}\n\nstatic void _signal_handler(const int sig) {\n\tswitch (sig) {\n\t\tcase SIGINT:\n\t\t\tif (Runner::active) {\n\t\t\t\tGlobal::should_quit = true;\n\t\t\t\tRunner::stopping = true;\n\t\t\t\tInput::interrupt();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tclean_quit(0);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SIGTSTP:\n\t\t\tif (Runner::active) {\n\t\t\t\tGlobal::should_sleep = true;\n\t\t\t\tRunner::stopping = true;\n\t\t\t\tInput::interrupt();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t_sleep();\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SIGCONT:\n\t\t\t_resume();\n\t\t\tbreak;\n\t\tcase SIGWINCH:\n\t\t\tterm_resize();\n\t\t\tbreak;\n\t\tcase SIGUSR1:\n\t\t\t// Input::poll interrupt\n\t\t\tbreak;\n\t\tcase SIGUSR2:\n\t\t\tGlobal::reload_conf = true;\n\t\t\tInput::interrupt();\n\t\t\tbreak;\n\t}\n}\n\n//* Config init\nvoid init_config(bool low_color, std::optional<std::string>& filter) {\n\tatomic_lock lck(Global::init_conf);\n\tvector<string> load_warnings;\n\tConfig::load(Config::conf_file, load_warnings);\n\tConfig::set(\"lowcolor\", (low_color ? true : not Config::getB(\"truecolor\")));\n\n\tstatic bool first_init = true;\n\n\tif (Global::debug and first_init) {\n\t\tLogger::set_log_level(Logger::Level::DEBUG);\n\t\tLogger::debug(\"Running in DEBUG mode!\");\n\t}\n\telse Logger::set_log_level(Config::getS(\"log_level\"));\n\n\tif (filter.has_value()) {\n\t\tConfig::set(\"proc_filter\", filter.value());\n\t}\n\n\tstatic string log_level;\n\tif (const string current_level = Config::getS(\"log_level\"); log_level != current_level) {\n\t\tlog_level = current_level;\n\t\tLogger::info(\"Logger set to {}\", (Global::debug ? \"DEBUG\" : log_level));\n\t}\n\n\tfor (const auto& err_str : load_warnings) Logger::warning(\"{}\", err_str);\n\tfirst_init = false;\n}\n\n//* Manages secondary thread for collection and drawing of boxes\nnamespace Runner {\n\tatomic<bool> active (false);\n\tatomic<bool> stopping (false);\n\tatomic<bool> waiting (false);\n\tatomic<bool> redraw (false);\n\tatomic<bool> coreNum_reset (false);\n\n\tstatic inline auto set_active(bool value) noexcept {\n\t\tactive.store(value, std::memory_order_relaxed);\n\t\tactive.notify_all();\n\t}\n\n\t//* Setup semaphore for triggering thread to do work\n\t// TODO: This can be made a local without too much effort.\n\tstd::binary_semaphore do_work { 0 };\n\tinline void thread_wait() { do_work.acquire(); }\n\tinline void thread_trigger() { do_work.release(); }\n\n\t//* Wrapper for raising privileges when using SUID bit\n\tclass gain_priv {\n\t\tint status = -1;\n\tpublic:\n\t\tgain_priv() {\n\t\t\tif (Global::real_uid != Global::set_uid)\n\t\t\t\tthis->status = seteuid(Global::set_uid);\n\t\t}\n\t\t~gain_priv() noexcept {\n\t\t\tif (status == 0)\n\t\t\t\tstatus = seteuid(Global::real_uid);\n\t\t}\n\t\tgain_priv(const gain_priv& other) = delete;\n\t\tgain_priv& operator=(const gain_priv& other) = delete;\n\t\tgain_priv(gain_priv&& other) = delete;\n\t\tgain_priv& operator=(gain_priv&& other) = delete;\n\t};\n\n\tstring output;\n\tstring empty_bg;\n\tbool pause_output{};\n\tsigset_t mask;\n\tstd::mutex mtx;\n\n\tenum debug_actions {\n\t\tcollect_begin,\n\t\tcollect_done,\n\t\tdraw_begin,\n\t\tdraw_begin_only,\n\t\tdraw_done\n\t};\n\n\tenum debug_array {\n\t\tcollect,\n\t\tdraw\n\t};\n\n\tstring debug_bg;\n\tstd::unordered_map<string, array<uint64_t, 2>> debug_times;\n\n\tclass MyNumPunct : public std::numpunct<char>\n\t{\n\tprotected:\n\t\tvirtual char do_thousands_sep() const override { return '\\''; }\n\t\tvirtual std::string do_grouping() const override { return \"\\03\"; }\n\t};\n\n\n\tstruct runner_conf {\n\t\tvector<string> boxes;\n\t\tbool no_update;\n\t\tbool force_redraw;\n\t\tbool background_update;\n\t\tstring overlay;\n\t\tstring clock;\n\t};\n\n\tstruct runner_conf current_conf;\n\n\tstatic void debug_timer(const char* name, const int action) {\n\t\tswitch (action) {\n\t\t\tcase collect_begin:\n\t\t\t\tdebug_times[name].at(collect) = time_micros();\n\t\t\t\treturn;\n\t\t\tcase collect_done:\n\t\t\t\tdebug_times[name].at(collect) = time_micros() - debug_times[name].at(collect);\n\t\t\t\tdebug_times[\"total\"].at(collect) += debug_times[name].at(collect);\n\t\t\t\treturn;\n\t\t\tcase draw_begin_only:\n\t\t\t\tdebug_times[name].at(draw) = time_micros();\n\t\t\t\treturn;\n\t\t\tcase draw_begin:\n\t\t\t\tdebug_times[name].at(draw) = time_micros();\n\t\t\t\tdebug_times[name].at(collect) = debug_times[name].at(draw) - debug_times[name].at(collect);\n\t\t\t\tdebug_times[\"total\"].at(collect) += debug_times[name].at(collect);\n\t\t\t\treturn;\n\t\t\tcase draw_done:\n\t\t\t\tdebug_times[name].at(draw) = time_micros() - debug_times[name].at(draw);\n\t\t\t\tdebug_times[\"total\"].at(draw) += debug_times[name].at(draw);\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\t//? ------------------------------- Secondary thread: async launcher and drawing ----------------------------------\n\tstatic void * _runner(void *) {\n\t\t//? Block some signals in this thread to avoid deadlock from any signal handlers trying to stop this thread\n\t\tsigemptyset(&mask);\n\t\t// sigaddset(&mask, SIGINT);\n\t\t// sigaddset(&mask, SIGTSTP);\n\t\tsigaddset(&mask, SIGWINCH);\n\t\tsigaddset(&mask, SIGTERM);\n\t\tpthread_sigmask(SIG_BLOCK, &mask, nullptr);\n\n\t\t// TODO: On first glance it looks redudant with `Runner::active`. \n\t\tstd::lock_guard lock {mtx};\n\n\t\t//* ----------------------------------------------- THREAD LOOP -----------------------------------------------\n\t\twhile (not Global::quitting) {\n\t\t\tthread_wait();\n\t\t\tatomic_wait_for(active, true, 5000);\n\t\t\tif (active) {\n\t\t\t\tGlobal::exit_error_msg = \"Runner thread failed to get active lock!\";\n\t\t\t\tGlobal::thread_exception = true;\n\t\t\t\tInput::interrupt();\n\t\t\t\tstopping = true;\n\t\t\t}\n\t\t\tif (stopping or Global::resized) {\n\t\t\t\tsleep_ms(1);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t//? Atomic lock used for blocking non thread-safe actions in main thread\n\t\t\tatomic_lock lck(active);\n\n\t\t\t//? Set effective user if SUID bit is set\n\t\t\tgain_priv powers{};\n\n\t\t\tauto& conf = current_conf;\n\n\t\t\t//! DEBUG stats\n\t\t\tif (Global::debug) {\n                if (debug_bg.empty() or redraw)\n                    Runner::debug_bg = Draw::createBox(2, 2, 33,\n\t\t\t\t\t#ifdef GPU_SUPPORT\n\t\t\t\t\t\t9,\n\t\t\t\t\t#else\n\t\t\t\t\t\t8,\n\t\t\t\t\t#endif\n\t\t\t\t\t\"\", true, \"μs\");\n\n\t\t\t\tdebug_times.clear();\n\t\t\t\tdebug_times[\"total\"] = {0, 0};\n\t\t\t}\n\n\t\t\toutput.clear();\n\n\t\t\t//* Run collection and draw functions for all boxes\n\t\t\ttry {\n#if defined(GPU_SUPPORT)\n\t\t\t\t//? GPU data collection\n\t\t\t\tconst bool gpu_in_cpu_panel = Gpu::gpu_names.size() > 0 and (\n\t\t\t\t\tConfig::getS(\"cpu_graph_lower\").starts_with(\"gpu-\")\n\t\t\t\t\tor (Config::getS(\"cpu_graph_lower\") == \"Auto\")\n\t\t\t\t\tor Config::getS(\"cpu_graph_upper\").starts_with(\"gpu-\")\n\t\t\t\t\tor (Gpu::shown == 0 and Config::getS(\"show_gpu_info\") != \"Off\")\n\t\t\t\t);\n\n\t\t\t\tvector<unsigned int> gpu_panels = {};\n\t\t\t\tfor (auto& box : conf.boxes)\n\t\t\t\t\tif (box.starts_with(\"gpu\"))\n\t\t\t\t\t\tgpu_panels.push_back(box.back()-'0');\n\n\t\t\t\tvector<Gpu::gpu_info> gpus;\n\t\t\t\tif (gpu_in_cpu_panel or not gpu_panels.empty()) {\n\t\t\t\t\tif (Global::debug) debug_timer(\"gpu\", collect_begin);\n\t\t\t\t\tgpus = Gpu::collect(conf.no_update);\n\t\t\t\t\tif (Global::debug) debug_timer(\"gpu\", collect_done);\n\t\t\t\t}\n\t\t\t\tauto& gpus_ref = gpus;\n#endif // GPU_SUPPORT\n\n\t\t\t\t//? CPU\n\t\t\t\tif (v_contains(conf.boxes, \"cpu\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"cpu\", collect_begin);\n\n\t\t\t\t\t\t//? Start collect\n\t\t\t\t\t\tauto cpu = Cpu::collect(conf.no_update);\n\n\t\t\t\t\t\tif (coreNum_reset) {\n\t\t\t\t\t\t\tcoreNum_reset = false;\n\t\t\t\t\t\t\tCpu::core_mapping = Cpu::get_core_mapping();\n\t\t\t\t\t\t\tGlobal::resized = true;\n\t\t\t\t\t\t\tInput::interrupt();\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"cpu\", draw_begin);\n\n\t\t\t\t\t\t//? Draw box\n\t\t\t\t\t\tif (not pause_output) {\n\t\t\t\t\t\t\toutput += Cpu::draw(\n\t\t\t\t\t\t\t\tcpu,\n#if defined(GPU_SUPPORT)\n\t\t\t\t\t\t\t\tgpus_ref,\n#endif // GPU_SUPPORT\n\t\t\t\t\t\t\t\tconf.force_redraw,\n\t\t\t\t\t\t\t\tconf.no_update\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"cpu\", draw_done);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::exception& e) {\n\t\t\t\t\t\tthrow std::runtime_error(\"Cpu:: -> \" + string{e.what()});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t#ifdef GPU_SUPPORT\n\t\t\t\t//? GPU\n\t\t\t\tif (not gpu_panels.empty() and not gpus_ref.empty()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"gpu\", draw_begin_only);\n\n\t\t\t\t\t\t//? Draw box\n\t\t\t\t\t\tif (not pause_output)\n\t\t\t\t\t\t\tfor (unsigned long i = 0; i < gpu_panels.size(); ++i)\n\t\t\t\t\t\t\t\toutput += Gpu::draw(gpus_ref[gpu_panels[i]], i, conf.force_redraw, conf.no_update);\n\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"gpu\", draw_done);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::exception& e) {\n                        throw std::runtime_error(\"Gpu:: -> \" + string{e.what()});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t#endif\n\t\t\t\t//? MEM\n\t\t\t\tif (v_contains(conf.boxes, \"mem\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"mem\", collect_begin);\n\n\t\t\t\t\t\t//? Start collect\n\t\t\t\t\t\tauto mem = Mem::collect(conf.no_update);\n\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"mem\", draw_begin);\n\n\t\t\t\t\t\t//? Draw box\n\t\t\t\t\t\tif (not pause_output) output += Mem::draw(mem, conf.force_redraw, conf.no_update);\n\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"mem\", draw_done);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::exception& e) {\n\t\t\t\t\t\tthrow std::runtime_error(\"Mem:: -> \" + string{e.what()});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//? NET\n\t\t\t\tif (v_contains(conf.boxes, \"net\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"net\", collect_begin);\n\n\t\t\t\t\t\t//? Start collect\n\t\t\t\t\t\tauto net = Net::collect(conf.no_update);\n\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"net\", draw_begin);\n\n\t\t\t\t\t\t//? Draw box\n\t\t\t\t\t\tif (not pause_output) output += Net::draw(net, conf.force_redraw, conf.no_update);\n\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"net\", draw_done);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::exception& e) {\n\t\t\t\t\t\tthrow std::runtime_error(\"Net:: -> \" + string{e.what()});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//? PROC\n\t\t\t\tif (v_contains(conf.boxes, \"proc\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"proc\", collect_begin);\n\n\t\t\t\t\t\t//? Start collect\n\t\t\t\t\t\tauto proc = Proc::collect(conf.no_update);\n\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"proc\", draw_begin);\n\n\t\t\t\t\t\t//? Draw box\n\t\t\t\t\t\tif (not pause_output) output += Proc::draw(proc, conf.force_redraw, conf.no_update);\n\n\t\t\t\t\t\tif (Global::debug) debug_timer(\"proc\", draw_done);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::exception& e) {\n\t\t\t\t\t\tthrow std::runtime_error(\"Proc:: -> \" + string{e.what()});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tcatch (const std::exception& e) {\n\t\t\t\tGlobal::exit_error_msg = fmt::format(\"Exception in runner thread -> {}\", e.what());\n\t\t\t\tGlobal::thread_exception = true;\n\t\t\t\tInput::interrupt();\n\t\t\t\tstopping = true;\n\t\t\t}\n\n\t\t\tif (stopping) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (redraw or conf.force_redraw) {\n\t\t\t\tempty_bg.clear();\n\t\t\t\tredraw = false;\n\t\t\t}\n\n\t\t\tif (not pause_output) output += conf.clock;\n\t\t\tif (not conf.overlay.empty() and not conf.background_update) pause_output = true;\n\t\t\tif (output.empty() and not pause_output) {\n\t\t\t\tif (empty_bg.empty()) {\n\t\t\t\t\tconst int x = Term::width / 2 - 10, y = Term::height / 2 - 10;\n\t\t\t\t\toutput += Term::clear;\n\t\t\t\t\tempty_bg = fmt::format(\n\t\t\t\t\t\t\"{banner}\"\n\t\t\t\t\t\t\"{mv1}{titleFg}{b}No boxes shown!\"\n\t\t\t\t\t\t\"{mv2}{hiFg}1 {mainFg}| Show CPU box\"\n\t\t\t\t\t\t\"{mv3}{hiFg}2 {mainFg}| Show MEM box\"\n\t\t\t\t\t\t\"{mv4}{hiFg}3 {mainFg}| Show NET box\"\n\t\t\t\t\t\t\"{mv5}{hiFg}4 {mainFg}| Show PROC box\"\n\t\t\t\t\t\t\"{mv6}{hiFg}5-0 {mainFg}| Show GPU boxes\"\n\t\t\t\t\t\t\"{mv7}{hiFg}esc {mainFg}| Show menu\"\n\t\t\t\t\t\t\"{mv8}{hiFg}q {mainFg}| Quit\",\n\t\t\t\t\t\t\"banner\"_a = Draw::banner_gen(y, 0, true),\n\t\t\t\t\t\t\"titleFg\"_a = Theme::c(\"title\"), \"b\"_a = Fx::b, \"hiFg\"_a = Theme::c(\"hi_fg\"), \"mainFg\"_a = Theme::c(\"main_fg\"),\n\t\t\t\t\t\t\"mv1\"_a = Mv::to(y+6, x),\n\t\t\t\t\t\t\"mv2\"_a = Mv::to(y+8, x),\n\t\t\t\t\t\t\"mv3\"_a = Mv::to(y+9, x),\n\t\t\t\t\t\t\"mv4\"_a = Mv::to(y+10, x),\n\t\t\t\t\t\t\"mv5\"_a = Mv::to(y+11, x),\n\t\t\t\t\t\t\"mv6\"_a = Mv::to(y+12, x-2),\n\t\t\t\t\t\t\"mv7\"_a = Mv::to(y+13, x-2),\n\t\t\t\t\t\t\"mv8\"_a = Mv::to(y+14, x)\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\toutput += empty_bg;\n\t\t\t}\n\n\t\t\t//! DEBUG stats -->\n\t\t\tif (Global::debug and not Menu::active) {\n\t\t\t\toutput += fmt::format(\"{pre}{box:5.5} {collect:>12.12} {draw:>12.12}{post}\",\n\t\t\t\t\t\"pre\"_a = debug_bg + Theme::c(\"title\") + Fx::b,\n\t\t\t\t\t\"box\"_a = \"box\", \"collect\"_a = \"collect\", \"draw\"_a = \"draw\",\n\t\t\t\t\t\"post\"_a = Theme::c(\"main_fg\") + Fx::ub\n\t\t\t\t);\n\t\t\t\tstatic auto loc = std::locale(std::locale::classic(), new MyNumPunct);\n\t\t\t#ifdef GPU_SUPPORT\n\t\t\t\tfor (const string name : {\"cpu\", \"mem\", \"net\", \"proc\", \"gpu\", \"total\"}) {\n\t\t\t#else\n\t\t\t\tfor (const string name : {\"cpu\", \"mem\", \"net\", \"proc\", \"total\"}) {\n\t\t\t#endif\n\t\t\t\t\tif (not debug_times.contains(name)) debug_times[name] = {0,0};\n\t\t\t\t\tconst auto& [time_collect, time_draw] = debug_times.at(name);\n\t\t\t\t\tif (name == \"total\") output += Fx::b;\n\t\t\t\t\toutput += fmt::format(loc, \"{mvLD}{name:5.5} {collect:12L} {draw:12L}\",\n\t\t\t\t\t\t\"mvLD\"_a = Mv::l(31) + Mv::d(1),\n\t\t\t\t\t\t\"name\"_a = name,\n\t\t\t\t\t\t\"collect\"_a = time_collect,\n\t\t\t\t\t\t\"draw\"_a = time_draw\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? If overlay isn't empty, print output without color and then print overlay on top\n\t\t\tconst bool term_sync = Config::getB(\"terminal_sync\");\n\t\t\tcout << (term_sync ? Term::sync_start : \"\") << (conf.overlay.empty()\n\t\t\t\t\t? output\n\t\t\t\t\t: (output.empty() ? \"\" : Fx::ub + Theme::c(\"inactive_fg\") + Fx::uncolor(output)) + conf.overlay)\n\t\t\t\t<< (term_sync ? Term::sync_end : \"\") << flush;\n\t\t}\n\t\t//* ----------------------------------------------- THREAD LOOP -----------------------------------------------\n\t\treturn {};\n\t}\n\t//? ------------------------------------------ Secondary thread end -----------------------------------------------\n\n\t//* Runs collect and draw in a secondary thread, unlocks and locks config to update cached values\n\tvoid run(const string& box, bool no_update, bool force_redraw) {\n\t\tatomic_wait_for(active, true, 5000);\n\t\tif (active) {\n\t\t\tLogger::error(\"Stall in Runner thread, restarting!\");\n\t\t\tset_active(false);\n\t\t\t// exit(1);\n\t\t\tpthread_cancel(Runner::runner_id);\n\n\t\t\t// Wait for the thread to actually terminate before creating a new one\n\t\t\tvoid* thread_result;\n\t\t\tint join_result = pthread_join(Runner::runner_id, &thread_result);\n\t\t\tif (join_result != 0) {\n\t\t\t\tLogger::warning(\"Failed to join cancelled thread: {}\", strerror(join_result));\n\t\t\t}\n\n\t\t\tif (pthread_create(&Runner::runner_id, nullptr, &Runner::_runner, nullptr) != 0) {\n\t\t\t\tGlobal::exit_error_msg = \"Failed to re-create _runner thread!\";\n\t\t\t\tclean_quit(1);\n\t\t\t}\n\t\t}\n\t\tif (stopping or Global::resized) return;\n\n\t\tif (box == \"overlay\") {\n\t\t\tconst bool term_sync = Config::getB(\"terminal_sync\");\n\t\t\tcout << (term_sync ? Term::sync_start : \"\") << Global::overlay << (term_sync ? Term::sync_end : \"\") << flush;\n\t\t}\n\t\telse if (box == \"clock\") {\n\t\t\tconst bool term_sync = Config::getB(\"terminal_sync\");\n\t\t\tcout << (term_sync ? Term::sync_start : \"\") << Global::clock << (term_sync ? Term::sync_end : \"\") << flush;\n\t\t}\n\t\telse {\n\t\t\tConfig::unlock();\n\t\t\tConfig::lock();\n\n\t\t\tcurrent_conf = {\n\t\t\t\t(box == \"all\" ? Config::current_boxes : vector{box}),\n\t\t\t\tno_update, force_redraw,\n\t\t\t\t(not Config::getB(\"tty_mode\") and Config::getB(\"background_update\")),\n\t\t\t\tGlobal::overlay,\n\t\t\t\tGlobal::clock\n\t\t\t};\n\n\t\t\tif (Menu::active and not current_conf.background_update) Global::overlay.clear();\n\n\t\t\tthread_trigger();\n\t\t\tatomic_wait_for(active, false, 10);\n\t\t}\n\n\n\t}\n\n\t//* Stops any work being done in runner thread and checks for thread errors\n\tvoid stop() {\n\t\tstopping = true;\n\t\tauto lock = std::unique_lock {mtx, std::defer_lock};\n\t\tconst auto is_runner_busy = !lock.try_lock();\n\t\tif (!is_runner_busy and not Global::quitting) {\n\t\t\tif (active) {\n\t\t\t\tset_active(false);\n\t\t\t}\n\t\t\tGlobal::exit_error_msg = \"Runner thread died unexpectedly!\";\n\t\t\tclean_quit(1);\n\t\t} else if (is_runner_busy) {\n\t\t\tatomic_wait_for(active, true, 5000);\n\t\t\tif (active) {\n\t\t\t\tset_active(false);\n\t\t\t\tif (Global::quitting) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tGlobal::exit_error_msg = \"No response from Runner thread, quitting!\";\n\t\t\t\t\tclean_quit(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthread_trigger();\n\t\t\tatomic_wait_for(active, false, 100);\n\t\t\tatomic_wait_for(active, true, 100);\n\t\t}\n\t\tstopping = false;\n\t}\n\n}\n\nstatic auto configure_tty_mode(std::optional<bool> force_tty) {\n\tif (force_tty.has_value()) {\n\t\tConfig::set(\"tty_mode\", force_tty.value());\n\t\tLogger::debug(\"TTY mode set via command line\");\n\t}\n\telse if (Config::getB(\"force_tty\")) {\n\t\tConfig::set(\"tty_mode\", true);\n\t\tLogger::debug(\"TTY mode set via config\");\n\t}\n\n#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__NetBSD__)\n\telse if (Term::current_tty.starts_with(\"/dev/tty\")) {\n\t\tConfig::set(\"tty_mode\", true);\n\t\tLogger::debug(\"Auto detect real TTY\");\n\t}\n#endif\n\n\tLogger::debug(\"TTY mode enabled: {}\", Config::getB(\"tty_mode\"));\n}\n\n\n//* --------------------------------------------- Main starts here! ---------------------------------------------------\n[[nodiscard]] auto btop_main(const std::span<const std::string_view> args) -> int {\n\n\t//? ------------------------------------------------ INIT ---------------------------------------------------------\n\n\tGlobal::start_time = time_s();\n\n\t//? Save real and effective userid's and drop privileges until needed if running with SUID bit set\n\tGlobal::real_uid = getuid();\n\tGlobal::set_uid = geteuid();\n\tif (Global::real_uid != Global::set_uid) {\n\t\tif (seteuid(Global::real_uid) != 0) {\n\t\t\tGlobal::real_uid = Global::set_uid;\n\t\t\tGlobal::exit_error_msg = \"Failed to change effective user ID. Unset btop SUID bit to ensure security on this system. Quitting!\";\n\t\t\tclean_quit(1);\n\t\t}\n\t}\n\n\tCli::Cli cli;\n\t{\n\t\t// Get the cli options or return with an exit code\n\t\tauto result = Cli::parse(args);\n\t\tif (result.has_value()) {\n\t\t\tcli = result.value();\n\t\t} else {\n\t\t\tauto error = result.error();\n\t\t\tif (error != 0) {\n\t\t\t\tCli::usage();\n\t\t\t\tCli::help_hint();\n\t\t\t}\n\t\t\treturn error;\n\t\t}\n\t}\n\n\tGlobal::debug = cli.debug;\n\n\t{\n\t\tconst auto config_dir = Config::get_config_dir();\n\t\tif (config_dir.has_value()) {\n\t\t\tConfig::conf_dir = config_dir.value();\n\t\t\tif (cli.config_file.has_value()) {\n\t\t\t\tConfig::conf_file = cli.config_file.value();\n\t\t\t} else {\n\t\t\t\tConfig::conf_file = Config::conf_dir / \"btop.conf\";\n\t\t\t}\n\n\t\t\tauto log_file = Config::get_log_file();\n\t\t\tif (log_file.has_value()) {\n\t\t\t\tLogger::init(log_file.value());\n\t\t\t}\n\n\t\t\tTheme::user_theme_dir = Config::conf_dir / \"themes\";\n\n\t\t\t// If necessary create the user theme directory\n\t\t\tstd::error_code error;\n\t\t\tif (not fs::exists(Theme::user_theme_dir, error) and not fs::create_directories(Theme::user_theme_dir, error)) {\n\t\t\t\tTheme::user_theme_dir.clear();\n\t\t\t\tLogger::warning(\"Failed to create user theme directory: {}\", error.message());\n\t\t\t}\n\t\t}\n\t}\n\n\t//? Try to find global btop theme path relative to binary path\n#ifdef __linux__\n\t{ \tstd::error_code ec;\n\t\tGlobal::self_path = fs::read_symlink(\"/proc/self/exe\", ec).remove_filename();\n\t}\n#elif __APPLE__\n\t{\n\t\tchar buf [PATH_MAX];\n\t\tuint32_t bufsize = PATH_MAX;\n\t\tif(!_NSGetExecutablePath(buf, &bufsize))\n\t\t\tGlobal::self_path = fs::path(buf).remove_filename();\n\t}\n#elif __NetBSD__\n\t{\n\t\tint mib[4];\n\t\tchar buf[PATH_MAX];\n\t\tsize_t bufsize = sizeof buf;\n\n\t\tmib[0] = CTL_KERN;\n\t\tmib[1] = KERN_PROC_ARGS;\n\t\tmib[2] = getpid();\n\t\tmib[3] = KERN_PROC_PATHNAME;\n\t\tif (sysctl(mib, 4, buf, &bufsize, NULL, 0) == 0)\n\t\t\tGlobal::self_path = fs::path(buf).remove_filename();\n\t}\n#endif\n\tif (std::error_code ec; not Global::self_path.empty()) {\n\t\tTheme::theme_dir = fs::canonical(Global::self_path / \"../share/btop/themes\", ec);\n\t\tif (ec or not fs::is_directory(Theme::theme_dir) or access(Theme::theme_dir.c_str(), R_OK) == -1) Theme::theme_dir.clear();\n\t}\n\t//? If relative path failed, check two most common absolute paths\n\tif (Theme::theme_dir.empty()) {\n\t\tfor (auto theme_path : {\"/usr/local/share/btop/themes\", \"/usr/share/btop/themes\"}) {\n\t\t\tif (fs::is_directory(fs::path(theme_path)) and access(theme_path, R_OK) != -1) {\n\t\t\t\tTheme::theme_dir = fs::path(theme_path);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t//? Set custom themes directory from command line if provided\n\tif (cli.themes_dir.has_value()) {\n\t\tTheme::custom_theme_dir = cli.themes_dir.value();\n\t\tLogger::info(\"Using custom themes directory: {}\", Theme::custom_theme_dir.string());\n\t}\n\n\t//? Config init\n\tinit_config(cli.low_color, cli.filter);\n\n\t//? Try to find and set a UTF-8 locale\n\tif (std::setlocale(LC_ALL, \"\") != nullptr and not std::string_view { std::setlocale(LC_ALL, \"\") }.contains(\";\")\n\tand str_to_upper(s_replace((string)std::setlocale(LC_ALL, \"\"), \"-\", \"\")).ends_with(\"UTF8\")) {\n\t\tLogger::debug(\"Using locale {}\", std::locale().name());\n\t}\n\telse {\n\t\tstring found;\n\t\tbool set_failure{};\n\t\tfor (const auto loc_env : array{\"LANG\", \"LC_ALL\", \"LC_CTYPE\"}) {\n\t\t\tif (std::getenv(loc_env) != nullptr and str_to_upper(s_replace((string)std::getenv(loc_env), \"-\", \"\")).ends_with(\"UTF8\")) {\n\t\t\t\tfound = std::getenv(loc_env);\n\t\t\t\tif (std::setlocale(LC_ALL, found.c_str()) == nullptr) {\n\t\t\t\t\tset_failure = true;\n\t\t\t\t\tLogger::warning(\"Failed to set locale {} continuing anyway.\", found);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (found.empty()) {\n\t\t\tif (setenv(\"LC_ALL\", \"\", 1) == 0 and setenv(\"LANG\", \"\", 1) == 0) {\n\t\t\t\ttry {\n\t\t\t\t\tif (const auto loc = std::locale(\"\").name(); not loc.empty() and loc != \"*\") {\n\t\t\t\t\t\tfor (auto& l : ssplit(loc, ';')) {\n\t\t\t\t\t\t\tif (str_to_upper(s_replace(l, \"-\", \"\")).ends_with(\"UTF8\")) {\n\t\t\t\t\t\t\t\tfound = l.substr(l.find('=') + 1);\n\t\t\t\t\t\t\t\tif (std::setlocale(LC_ALL, found.c_str()) != nullptr) {\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch (...) { found.clear(); }\n\t\t\t}\n\t\t}\n\t//\n\t#ifdef __APPLE__\n\t\tif (found.empty()) {\n\t\t\tCFLocaleRef cflocale = CFLocaleCopyCurrent();\n\t\t\tCFStringRef id_value = (CFStringRef)CFLocaleGetValue(cflocale, kCFLocaleIdentifier);\n\t\t\tauto loc_id = CFStringGetCStringPtr(id_value, kCFStringEncodingUTF8);\n\t\t\tCFRelease(cflocale);\n\t\t\tstd::string cur_locale = (loc_id != nullptr ? loc_id : \"\");\n\t\t\tif (cur_locale.empty()) {\n\t\t\t\tLogger::warning(\"No UTF-8 locale detected! Some symbols might not display correctly.\");\n\t\t\t}\n\t\t\telse if (std::setlocale(LC_ALL, string(cur_locale + \".UTF-8\").c_str()) != nullptr) {\n\t\t\t\tLogger::debug(\"Setting LC_ALL={}.UTF-8\", cur_locale);\n\t\t\t}\n\t\t\telse if(std::setlocale(LC_ALL, \"en_US.UTF-8\") != nullptr) {\n\t\t\t\tLogger::debug(\"Setting LC_ALL=en_US.UTF-8\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tLogger::warning(\"Failed to set macos locale, continuing anyway.\");\n\t\t\t}\n\t\t}\n\t#else\n\t\tif (found.empty() and cli.force_utf) {\n\t\t\tLogger::warning(\"No UTF-8 locale detected! Forcing start with --force-utf argument.\");\n\t\t} else if (found.empty()) {\n\t\t\tGlobal::exit_error_msg = \"No UTF-8 locale detected!\\nUse --force-utf argument to force start if you're sure your terminal can handle it.\";\n\t\t\tclean_quit(1);\n\t\t}\n\t#endif\n\t\telse if (not set_failure) {\n\t\t\tLogger::debug(\"Setting LC_ALL={}\", found);\n\t\t}\n\t}\n\n\t//? Initialize terminal and set options\n\tif (not Term::init()) {\n\t\tGlobal::exit_error_msg = \"No tty detected!\\nbtop++ needs an interactive shell to run.\";\n\t\tclean_quit(1);\n\t}\n\n\tif (Term::current_tty != \"unknown\") {\n\t\tLogger::info(\"Running on {}\", Term::current_tty);\n\t}\n\n\tconfigure_tty_mode(cli.force_tty);\n\n\t//? Check for valid terminal dimensions\n\t{\n\t\tint t_count = 0;\n\t\twhile (Term::width <= 0 or Term::width > 10000 or Term::height <= 0 or Term::height > 10000) {\n\t\t\tsleep_ms(10);\n\t\t\tTerm::refresh();\n\t\t\tif (++t_count == 100) {\n\t\t\t\tGlobal::exit_error_msg = \"Failed to get size of terminal!\";\n\t\t\t\tclean_quit(1);\n\t\t\t}\n\t\t}\n\t}\n\n\t//? Platform dependent init and error check\n\ttry {\n\t\tShared::init();\n\t}\n\tcatch (const std::exception& e) {\n\t\tGlobal::exit_error_msg = fmt::format(\"Exception in Shared::init() -> {}\", e.what());\n\t\tclean_quit(1);\n\t}\n\n\tif (not Config::set_boxes(Config::getS(\"shown_boxes\"))) {\n\t\tConfig::set_boxes(\"cpu mem net proc\");\n\t\tConfig::set(\"shown_boxes\", \"cpu mem net proc\"s);\n\t}\n\n\t//? Update list of available themes and generate the selected theme\n\tTheme::updateThemes();\n\tTheme::setTheme();\n\n\t//? Setup signal handlers for CTRL-C, CTRL-Z, resume and terminal resize\n\tstd::atexit(_exit_handler);\n\tstd::signal(SIGINT, _signal_handler);\n\tstd::signal(SIGTSTP, _signal_handler);\n\tstd::signal(SIGCONT, _signal_handler);\n\tstd::signal(SIGWINCH, _signal_handler);\n\tstd::signal(SIGUSR1, _signal_handler);\n\tstd::signal(SIGUSR2, _signal_handler);\n\t// Add crash handlers to restore terminal on crash\n\tstd::signal(SIGSEGV, _crash_handler);\n\tstd::signal(SIGABRT, _crash_handler);\n\tstd::signal(SIGTRAP, _crash_handler);\n\tstd::signal(SIGBUS, _crash_handler);\n\tstd::signal(SIGILL, _crash_handler);\n\n\tsigset_t mask;\n\tsigemptyset(&mask);\n\tsigaddset(&mask, SIGUSR1);\n\tpthread_sigmask(SIG_BLOCK, &mask, &Input::signal_mask);\n\n\tif (pthread_create(&Runner::runner_id, nullptr, &Runner::_runner, nullptr) != 0) {\n\t\tGlobal::exit_error_msg = \"Failed to create _runner thread!\";\n\t\tclean_quit(1);\n\t}\n\telse {\n\t\tGlobal::_runner_started = true;\n\t}\n\n\t//? Calculate sizes of all boxes\n\tConfig::presetsValid(Config::getS(\"presets\"));\n\tif (cli.preset.has_value()) {\n\t\tConfig::current_preset = min(static_cast<std::int32_t>(cli.preset.value()), static_cast<std::int32_t>(Config::preset_list.size() - 1));\n\t\tConfig::apply_preset(Config::preset_list.at(Config::current_preset.value()));\n\t}\n\n\t{\n\t\tconst auto [x, y] = Term::get_min_size(Config::getS(\"shown_boxes\"));\n\t\tif (Term::height < y or Term::width < x) {\n\t\t\tpthread_sigmask(SIG_SETMASK, &Input::signal_mask, &mask);\n\t\t\tterm_resize(true);\n\t\t\tpthread_sigmask(SIG_SETMASK, &mask, nullptr);\n\t\t\tGlobal::resized = false;\n\t\t}\n\n\t}\n\n\tDraw::calcSizes();\n\n\t//? Print out box outlines\n\tconst bool term_sync = Config::getB(\"terminal_sync\");\n\tcout << (term_sync ? Term::sync_start : \"\") << Cpu::box << Mem::box << Net::box << Proc::box << (term_sync ? Term::sync_end : \"\") << flush;\n\n\n\t//? ------------------------------------------------ MAIN LOOP ----------------------------------------------------\n\n\tif (cli.updates.has_value()) {\n\t\tConfig::set(\"update_ms\", static_cast<int>(cli.updates.value()));\n\t}\n\tuint64_t update_ms = Config::getI(\"update_ms\");\n\tauto future_time = time_ms();\n\n\ttry {\n\t\twhile (not true not_eq not false) {\n\t\t\t//? Check for exceptions in secondary thread and exit with fail signal if true\n\t\t\tif (Global::thread_exception) {\n\t\t\t\tclean_quit(1);\n\t\t\t}\n\t\t\telse if (Global::should_quit) {\n\t\t\t\tclean_quit(0);\n\t\t\t}\n\t\t\telse if (Global::should_sleep) {\n\t\t\t\tGlobal::should_sleep = false;\n\t\t\t\t_sleep();\n\t\t\t}\n\t\t\t//? Hot reload config from CTRL + R or SIGUSR2\n\t\t\telse if (Global::reload_conf) {\n\t\t\t\tGlobal::reload_conf = false;\n\t\t\t\tif (Runner::active) Runner::stop();\n\t\t\t\tConfig::unlock();\n\t\t\t\tinit_config(cli.low_color, cli.filter);\n\t\t\t\tTheme::updateThemes();\n\t\t\t\tTheme::setTheme();\n\t\t\t\tDraw::banner_gen(0, 0, false, true);\n\t\t\t\tGlobal::resized = true;\n\t\t\t}\n\n\t\t\t//? Make sure terminal size hasn't changed (in case of SIGWINCH not working properly)\n\t\t\tterm_resize(Global::resized);\n\n\t\t\t//? Trigger secondary thread to redraw if terminal has been resized\n\t\t\tif (Global::resized) {\n\t\t\t\tDraw::calcSizes();\n\t\t\t\tDraw::update_clock(true);\n\t\t\t\tGlobal::resized = false;\n\t\t\t\tif (Menu::active) Menu::process();\n\t\t\t\telse Runner::run(\"all\", true, true);\n\t\t\t\tatomic_wait_for(Runner::active, true, 1000);\n\t\t\t}\n\n\t\t\t//? Update clock if needed\n\t\t\tif (Draw::update_clock() and not Menu::active) {\n\t\t\t\tRunner::run(\"clock\");\n\t\t\t}\n\n\t\t\t//? Start secondary collect & draw thread at the interval set by <update_ms> config value\n\t\t\tif (time_ms() >= future_time and not Global::resized) {\n\t\t\t\tRunner::run(\"all\");\n\t\t\t\tupdate_ms = Config::getI(\"update_ms\");\n\t\t\t\tfuture_time = time_ms() + update_ms;\n\t\t\t}\n\n\t\t\t//? Loop over input polling and input action processing\n\t\t\tfor (auto current_time = time_ms(); current_time < future_time; current_time = time_ms()) {\n\n\t\t\t\t//? Check for external clock changes and for changes to the update timer\n\t\t\t\tif (std::cmp_not_equal(update_ms, Config::getI(\"update_ms\"))) {\n\t\t\t\t\tupdate_ms = Config::getI(\"update_ms\");\n\t\t\t\t\tfuture_time = time_ms() + update_ms;\n\t\t\t\t}\n\t\t\t\telse if (future_time - current_time > update_ms) {\n\t\t\t\t\tfuture_time = current_time;\n\t\t\t\t}\n\t\t\t\t//? Poll for input and process any input detected\n\t\t\t\telse if (Input::poll(min((uint64_t)1000, future_time - current_time))) {\n\t\t\t\t\tif (not Runner::active) Config::unlock();\n\n\t\t\t\t\tif (Menu::active) Menu::process(Input::get());\n\t\t\t\t\telse Input::process(Input::get());\n\t\t\t\t}\n\n\t\t\t\t//? Break the loop at 1000ms intervals or if input polling was interrupted\n\t\t\t\telse break;\n\n\t\t\t}\n\n\t\t}\n\t}\n\tcatch (const std::exception& e) {\n\t\tGlobal::exit_error_msg = fmt::format(\"Exception in main loop -> {}\", e.what());\n\t\tclean_quit(1);\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "src/btop.hpp",
    "content": "#include <span>\n#include <string_view>\n\n[[nodiscard]] auto btop_main(std::span<const std::string_view> args) -> int;\n"
  },
  {
    "path": "src/btop_cli.cpp",
    "content": "// SPDX-License-Identifier: Apache-2.0\n\n#include \"btop_cli.hpp\"\n\n#include <algorithm>\n#include <expected>\n#include <filesystem>\n#include <iterator>\n#include <optional>\n#include <ranges>\n#include <span>\n#include <stdexcept>\n#include <string>\n#include <string_view>\n\n#include <unistd.h>\n\n#include <fmt/base.h>\n#include <fmt/format.h>\n\n#include \"btop_config.hpp\"\n#include \"btop_shared.hpp\"\n#include \"config.h\"\n\nusing namespace std::string_view_literals;\n\nstatic constexpr auto BOLD = \"\\033[1m\"sv;\nstatic constexpr auto BOLD_UNDERLINE = \"\\033[1;4m\"sv;\nstatic constexpr auto BOLD_RED = \"\\033[1;31m\"sv;\nstatic constexpr auto BOLD_GREEN = \"\\033[1;32m\"sv;\nstatic constexpr auto BOLD_YELLOW = \"\\033[1;33m\"sv;\nstatic constexpr auto BOLD_BRIGHT_BLACK = \"\\033[1;90m\"sv;\nstatic constexpr auto YELLOW = \"\\033[33m\"sv;\nstatic constexpr auto RESET = \"\\033[0m\"sv;\n\nstatic void version() noexcept {\n\tif constexpr (GIT_COMMIT.empty()) {\n\t\tfmt::println(\"btop version: {}{}{}\", BOLD, Global::Version, RESET);\n\t} else {\n\t\tfmt::println(\"btop version: {}{}+{}{}\", BOLD, Global::Version, GIT_COMMIT, RESET);\n\t}\n}\n\nstatic void build_info() noexcept {\n\tfmt::println(\"Compiled with: {} ({})\", COMPILER, COMPILER_VERSION);\n\tfmt::println(\"Configured with: {}\", CONFIGURE_COMMAND);\n}\n\nstatic void error(std::string_view msg) noexcept {\n\tfmt::println(\"{}error:{} {}\\n\", BOLD_RED, RESET, msg);\n}\n\nnamespace Cli {\n\t[[nodiscard]] auto parse(const std::span<const std::string_view> args) noexcept -> Result {\n\t\tCli cli {};\n\n\t\tfor (auto it = args.begin(); it != args.end(); ++it) {\n\t\t\tauto arg = *it;\n\n\t\t\tif (arg == \"--default-config\") {\n\t\t\t\treturn default_config();\n\t\t\t}\n\t\t\tif (arg == \"-h\" || arg == \"--help\") {\n\t\t\t\tusage();\n\t\t\t\thelp();\n\t\t\t\treturn std::unexpected { 0 };\n\t\t\t}\n\t\t\tif (arg == \"-v\" || arg == \"-V\") {\n\t\t\t\tversion();\n\t\t\t\treturn std::unexpected { 0 };\n\t\t\t}\n\t\t\tif (arg == \"--version\") {\n\t\t\t\tversion();\n\t\t\t\tbuild_info();\n\t\t\t\treturn std::unexpected { 0 };\n\t\t\t}\n\n\t\t\tif (arg == \"-d\" || arg == \"--debug\") {\n\t\t\t\tcli.debug = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"--force-utf\") {\n\t\t\t\tcli.force_utf = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-l\" || arg == \"--low-color\") {\n\t\t\t\tcli.low_color = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-t\" || arg == \"--tty\") {\n\t\t\t\tif (cli.force_tty.has_value()) {\n\t\t\t\t\terror(\"tty mode can't be set twice\");\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t}\n\t\t\t\tcli.force_tty = std::make_optional(true);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"--no-tty\") {\n\t\t\t\tif (cli.force_tty.has_value()) {\n\t\t\t\t\terror(\"tty mode can't be set twice\");\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t}\n\t\t\t\tcli.force_tty = std::make_optional(false);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (arg == \"-c\" || arg == \"--config\") {\n\t\t\t\t// This flag requires an argument.\n\t\t\t\tif (++it == args.end()) {\n\t\t\t\t\terror(\"Config requires an argument\");\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t}\n\n\t\t\t\tauto arg = *it;\n\t\t\t\tauto config_file = stdfs::path { arg };\n\n\t\t\t\tif (stdfs::is_directory(config_file)) {\n\t\t\t\t\terror(\"Config file can't be a directory\");\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t}\n\n\t\t\t\tcli.config_file = std::make_optional(config_file);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-f\" || arg == \"--filter\") {\n\t\t\t\t// This flag requires an argument.\n\t\t\t\tif (++it == args.end()) {\n\t\t\t\t\terror(\"Filter requires an argument\");\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t}\n\n\t\t\t\tauto arg = *it;\n\t\t\t\tcli.filter = std::make_optional(arg);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-p\" || arg == \"--preset\") {\n\t\t\t\t// This flag requires an argument.\n\t\t\t\tif (++it == args.end()) {\n\t\t\t\t\terror(\"Preset requires an argument\");\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t}\n\n\t\t\t\tauto arg = *it;\n\t\t\t\ttry {\n\t\t\t\t\tauto preset_id = std::clamp(std::stoi(arg.data()), 0, 9);\n\t\t\t\t\tcli.preset = std::make_optional(preset_id);\n\t\t\t\t} catch (std::invalid_argument& e) {\n\t\t\t\t\terror(\"Preset must be a positive number\");\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t} catch (std::out_of_range& e) {\n\t\t\t\t\terror(fmt::format(\"Preset argument is out of range: {}\", arg.data()));\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"--themes-dir\") {\n\t\t\t\t// This flag requires an argument.\n\t\t\t\tif (++it == args.end()) {\n\t\t\t\t\terror(\"Themes directory requires an argument\");\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t}\n\n\t\t\t\tauto arg = *it;\n\t\t\t\tauto themes_dir = stdfs::path { arg };\n\n\t\t\t\tif (not stdfs::is_directory(themes_dir)) {\n\t\t\t\t\terror(\"Themes directory does not exist or is not a directory\");\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t}\n\n\t\t\t\tcli.themes_dir = std::make_optional(themes_dir);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (arg == \"-u\" || arg == \"--update\") {\n\t\t\t\t// This flag requires an argument.\n\t\t\t\tif (++it == args.end()) {\n\t\t\t\t\terror(\"Update requires an argument\");\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t}\n\n\t\t\t\tauto arg = *it;\n\t\t\t\ttry {\n\t\t\t\t\tauto refresh_rate = std::max(std::stoi(arg.data()), 100);\n\t\t\t\t\tcli.updates = refresh_rate;\n\t\t\t\t} catch (std::invalid_argument& e) {\n\t\t\t\t\terror(\"Update must be a positive number\");\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t} catch (std::out_of_range& e) {\n\t\t\t\t\terror(fmt::format(\"Update argument is out of range: {}\", arg.data()));\n\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\terror(fmt::format(\"Unknown argument '{}{}{}'\", YELLOW, arg, RESET));\n\t\t\treturn std::unexpected { 1 };\n\t\t}\n\t\treturn cli;\n\t}\n\n\tauto default_config() noexcept -> Result {\n\t\t// The idea of using `current_config` is that the CLI parser is run before loading the actual config and thus\n\t\t// provides default values.\n\t\tauto config = Config::current_config();\n\t\t\n\t\tif (isatty(STDOUT_FILENO)) {\n\t\t\tstd::string buffer {};\n\t\t\t// The config buffer ends in `\\n`. `std::views::split` will then create an empty element after the last\n\t\t\t// newline, which we would write as an additional empty line at the very end.\n\t\t\tauto trimmed_config = config.substr(0, config.length() - 1);\n\t\t\tfor (const auto line : std::views::split(trimmed_config, '\\n')) {\n\t\t\t\tauto line_view = std::string_view { line };\n\t\t\t\tif (line_view.starts_with(\"#\")) {\n\t\t\t\t\tfmt::format_to(\n\t\t\t\t\t\tstd::back_inserter(buffer), \"{1}{0}{2}\\n\", line_view, BOLD_BRIGHT_BLACK, RESET\n\t\t\t\t\t);\n\t\t\t\t} else if (!line_view.empty()) {\n\t\t\t\t\tauto pos = line_view.find(\"=\");\n\t\t\t\t\tif (pos == line_view.npos) {\n\t\t\t\t\t\terror(\"invalid default config: '=' not found\");\n\t\t\t\t\t\treturn std::unexpected { 1 };\n\t\t\t\t\t}\n\t\t\t\t\tauto name = line_view.substr(0, pos);\n\t\t\t\t\tauto value = line_view.substr(pos + 1);\n\t\t\t\t\tfmt::format_to(\n\t\t\t\t\t\tstd::back_inserter(buffer),\n\t\t\t\t\t\t\"{2}{0}{4}={3}{1}{4}\\n\",\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tvalue,\n\t\t\t\t\t\tBOLD_YELLOW,\n\t\t\t\t\t\tBOLD_GREEN,\n\t\t\t\t\t\tRESET\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tfmt::format_to(std::back_inserter(buffer), \"\\n\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tfmt::print(\"{}\", buffer);\n\t\t} else {\n\t\t\tfmt::print(\"{}\", config);\n\t\t}\n\t\treturn std::unexpected { 0 };\n\t}\n\n\tvoid usage() noexcept {\n\t\tfmt::println(\"{0}Usage:{1} {2}btop{1} [OPTIONS]\\n\", BOLD_UNDERLINE, RESET, BOLD);\n\t}\n\n\tvoid help() noexcept {\n\t\tfmt::print(\n\t\t\t\"{0}Options:{1}\\n\"\n\t\t\t\"  {2}-c, --config{1} <file>     Path to a config file\\n\"\n\t\t\t\"  {2}-d, --debug{1}             Start in debug mode with additional logs and metrics\\n\"\n\t\t\t\"  {2}-f, --filter{1} <filter>   Set an initial process filter\\n\"\n\t\t\t\"  {2}    --force-utf{1}         Override automatic UTF locale detection\\n\"\n\t\t\t\"  {2}-l, --low-color{1}         Disable true color, 256 colors only\\n\"\n\t\t\t\"  {2}-p, --preset{1} <id>       Start with a preset (0-9)\\n\"\n\t\t\t\"  {2}-t, --tty{1}               Force tty mode with ANSI graph symbols and 16 colors only\\n\"\n\t\t\t\"  {2}    --themes-dir{1} <dir>  Path to a custom themes directory\\n\"\n\t\t\t\"  {2}    --no-tty{1}            Force disable tty mode\\n\"\n\t\t\t\"  {2}-u, --update{1} <ms>       Set an initial update rate in milliseconds\\n\"\n\t\t\t\"  {2}    --default-config{1}    Print default config to standard output\\n\"\n\t\t\t\"  {2}-h, --help{1}              Show this help message and exit\\n\"\n\t\t\t\"  {2}-V, --version{1}           Show a version message and exit (more with --version)\\n\",\n\t\t\tBOLD_UNDERLINE, RESET, BOLD\n\t\t);\n\t}\n\n\tvoid help_hint() noexcept {\n\t\tfmt::println(\"For more information, try '{}--help{}'\", BOLD, RESET);\n\t}\n} // namespace Cli\n"
  },
  {
    "path": "src/btop_cli.hpp",
    "content": "// SPDX-License-Identifier: Apache-2.0\n\n#pragma once\n\n#include <cstdint>\n#include <expected>\n#include <filesystem>\n#include <optional>\n#include <span>\n#include <string_view>\n\nnamespace Cli {\n\tnamespace stdfs = std::filesystem;\n\n\t// Configuration options set via the command line.\n\tstruct Cli {\n\t\t// Alternate path to a configuration file\n\t\tstd::optional<stdfs::path> config_file;\n\t\t// Enable debug mode with additional logs and metrics\n\t\tbool debug {};\n\t\t// Set an initial process filter.\n\t\tstd::optional<std::string> filter;\n\t\t// Only use ANSI supported graph symbols and colors\n\t\tstd::optional<bool> force_tty;\n\t\t// Use UTF-8 locale even if not detected\n\t\tbool force_utf {};\n\t\t// Disable true color and only use 256 color mode\n\t\tbool low_color {};\n\t\t// Start with one of the provided presets\n\t\tstd::optional<std::uint32_t> preset;\n\t\t// Path to a custom themes directory\n\t\tstd::optional<stdfs::path> themes_dir;\n\t\t// The initial refresh rate\n\t\tstd::optional<std::uint32_t> updates;\n\t};\n\n\tusing Result = std::expected<Cli, std::int32_t>;\n\n\t// Parse the command line arguments\n\t[[nodiscard]] auto parse(std::span<const std::string_view> args) noexcept -> Result;\n\n\t// Print default config to standard output\n\t[[nodiscard]] auto default_config() noexcept -> Result;\n\n\t// Print a usage header\n\tvoid usage() noexcept;\n\n\t// Print a help message\n\tvoid help() noexcept;\n\n\t// Print a hint on how to show more help\n\tvoid help_hint() noexcept;\n} // namespace Cli\n"
  },
  {
    "path": "src/btop_config.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include <array>\n#include <atomic>\n#include <filesystem>\n#include <fmt/format.h>\n#include <fstream>\n#include <iterator>\n#include <locale>\n#include <optional>\n#include <ranges>\n#include <string_view>\n#include <utility>\n\n#include <fmt/base.h>\n#include <fmt/core.h>\n#include <sys/statvfs.h>\n\n#include \"btop_config.hpp\"\n#include \"btop_log.hpp\"\n#include \"btop_shared.hpp\"\n#include \"btop_tools.hpp\"\n\nusing std::array;\nusing std::atomic;\nusing std::string_view;\n\nnamespace fs = std::filesystem;\nnamespace rng = std::ranges;\n\nusing namespace std::literals;\nusing namespace Tools;\n\n//* Functions and variables for reading and writing the btop config file\nnamespace Config {\n\n\tatomic<bool> locked (false);\n\tatomic<bool> writelock (false);\n\tbool write_new;\n\n\tconst vector<array<string, 2>> descriptions = {\n\t\t{\"color_theme\", \t\t\"#* Name of a btop++/bpytop/bashtop formatted \\\".theme\\\" file, \\\"Default\\\" and \\\"TTY\\\" for builtin themes.\\n\"\n\t\t\t\t\t\t\t\t\"#* Themes should be placed in \\\"../share/btop/themes\\\" relative to binary or \\\"$HOME/.config/btop/themes\\\"\"},\n\n\t\t{\"theme_background\", \t\"#* If the theme set background should be shown, set to False if you want terminal background transparency.\"},\n\n\t\t{\"truecolor\", \t\t\t\"#* Sets if 24-bit truecolor should be used, will convert 24-bit colors to 256 color (6x6x6 color cube) if false.\"},\n\n\t\t{\"force_tty\", \t\t\t\"#* Set to true to force tty mode regardless if a real tty has been detected or not.\\n\"\n\t\t\t\t\t\t\t\t\"#* Will force 16-color mode and TTY theme, set all graph symbols to \\\"tty\\\" and swap out other non tty friendly symbols.\"},\n\n\t\t{\"disable_presets\",\t\t\"#* Option to disable presets. Either the default preset, custom presets, or all presets.\\n\"\n\t\t\t\t\t\t\t\t\"#* \\\"Off\\\" All presets are enabled.\\n\"\n\t\t\t\t\t\t\t\t\"#* \\\"Default\\\" preset is disabled.\"\n\t\t\t\t\t\t\t\t\"#* \\\"Custom\\\" presets are disabled.\"\n\t\t\t\t\t\t\t\t\"#* \\\"All\\\" presets are disabled.\"},\n\n\t\t{\"presets\",\t\t\t\t\"#* Define presets for the layout of the boxes. Preset 0 is always all boxes shown with default settings. Max 9 presets.\\n\"\n\t\t\t\t\t\t\t\t\"#* Format: \\\"box_name:P:G,box_name:P:G\\\" P=(0 or 1) for alternate positions, G=graph symbol to use for box.\\n\"\n\t\t\t\t\t\t\t\t\"#* Use whitespace \\\" \\\" as separator between different presets.\\n\"\n\t\t\t\t\t\t\t\t\"#* Example: \\\"cpu:0:default,mem:0:tty,proc:1:default cpu:0:braille,proc:0:tty\\\"\"},\n\n\t\t{\"vim_keys\",\t\t\t\"#* Set to True to enable \\\"h,j,k,l,g,G\\\" keys for directional control in lists.\\n\"\n\t\t\t\t\t\t\t\t\"#* Conflicting keys for h:\\\"help\\\" and k:\\\"kill\\\" is accessible while holding shift.\"},\n\n\t\t{\"disable_mouse\", \"#* Disable all mouse events.\"},\n\t\t{\"rounded_corners\",\t\t\"#* Rounded corners on boxes, is ignored if TTY mode is ON.\"},\n\n\t\t{\"terminal_sync\", \t\t\"#* Use terminal synchronized output sequences to reduce flickering on supported terminals.\"},\n\n\t\t{\"graph_symbol\", \t\t\"#* Default symbols to use for graph creation, \\\"braille\\\", \\\"block\\\" or \\\"tty\\\".\\n\"\n\t\t\t\t\t\t\t\t\"#* \\\"braille\\\" offers the highest resolution but might not be included in all fonts.\\n\"\n\t\t\t\t\t\t\t\t\"#* \\\"block\\\" has half the resolution of braille but uses more common characters.\\n\"\n\t\t\t\t\t\t\t\t\"#* \\\"tty\\\" uses only 3 different symbols but will work with most fonts and should work in a real TTY.\\n\"\n\t\t\t\t\t\t\t\t\"#* Note that \\\"tty\\\" only has half the horizontal resolution of the other two, so will show a shorter historical view.\"},\n\n\t\t{\"graph_symbol_cpu\", \t\"# Graph symbol to use for graphs in cpu box, \\\"default\\\", \\\"braille\\\", \\\"block\\\" or \\\"tty\\\".\"},\n#ifdef GPU_SUPPORT\n\t\t{\"graph_symbol_gpu\", \t\"# Graph symbol to use for graphs in gpu box, \\\"default\\\", \\\"braille\\\", \\\"block\\\" or \\\"tty\\\".\"},\n#endif\n\t\t{\"graph_symbol_mem\", \t\"# Graph symbol to use for graphs in cpu box, \\\"default\\\", \\\"braille\\\", \\\"block\\\" or \\\"tty\\\".\"},\n\n\t\t{\"graph_symbol_net\", \t\"# Graph symbol to use for graphs in cpu box, \\\"default\\\", \\\"braille\\\", \\\"block\\\" or \\\"tty\\\".\"},\n\n\t\t{\"graph_symbol_proc\", \t\"# Graph symbol to use for graphs in cpu box, \\\"default\\\", \\\"braille\\\", \\\"block\\\" or \\\"tty\\\".\"},\n\n\t\t{\"shown_boxes\", \t\t\"#* Manually set which boxes to show. Available values are \\\"cpu mem net proc\\\" and \\\"gpu0\\\" through \\\"gpu5\\\", separate values with whitespace.\"},\n\n\t\t{\"update_ms\", \t\t\t\"#* Update time in milliseconds, recommended 2000 ms or above for better sample times for graphs.\"},\n\n\t\t{\"proc_sorting\",\t\t\"#* Processes sorting, \\\"pid\\\" \\\"program\\\" \\\"arguments\\\" \\\"threads\\\" \\\"user\\\" \\\"memory\\\" \\\"cpu lazy\\\" \\\"cpu direct\\\",\\n\"\n\t\t\t\t\t\t\t\t\"#* \\\"cpu lazy\\\" sorts top process over time (easier to follow), \\\"cpu direct\\\" updates top process directly.\"},\n\n\t\t{\"proc_reversed\",\t\t\"#* Reverse sorting order, True or False.\"},\n\n\t\t{\"proc_tree\",\t\t\t\"#* Show processes as a tree.\"},\n\n\t\t{\"proc_colors\", \t\t\"#* Use the cpu graph colors in the process list.\"},\n\n\t\t{\"proc_gradient\", \t\t\"#* Use a darkening gradient in the process list.\"},\n\n\t\t{\"proc_per_core\", \t\t\"#* If process cpu usage should be of the core it's running on or usage of the total available cpu power.\"},\n\n\t\t{\"proc_mem_bytes\", \t\t\"#* Show process memory as bytes instead of percent.\"},\n\n\t\t{\"proc_cpu_graphs\",     \"#* Show cpu graph for each process.\"},\n\n\t\t{\"proc_info_smaps\",\t\t\"#* Use /proc/[pid]/smaps for memory information in the process info box (very slow but more accurate)\"},\n\n\t\t{\"proc_left\",\t\t\t\"#* Show proc box on left side of screen instead of right.\"},\n\n\t\t{\"proc_filter_kernel\",  \"#* (Linux) Filter processes tied to the Linux kernel(similar behavior to htop).\"},\n\n\t\t{\"proc_follow_detailed\",\t\"#* Should the process list follow the selected process when detailed view is open.\"},\n\n\t\t{\"proc_aggregate\",\t\t\"#* In tree-view, always accumulate child process resources in the parent process.\"},\n\n\t\t{\"keep_dead_proc_usage\", \"#* Should cpu and memory usage display be preserved for dead processes when paused.\"},\n\n\t\t{\"cpu_graph_upper\", \t\"#* Sets the CPU stat shown in upper half of the CPU graph, \\\"total\\\" is always available.\\n\"\n\t\t\t\t\t\t\t\t\"#* Select from a list of detected attributes from the options menu.\"},\n\n\t\t{\"cpu_graph_lower\", \t\"#* Sets the CPU stat shown in lower half of the CPU graph, \\\"total\\\" is always available.\\n\"\n\t\t\t\t\t\t\t\t\"#* Select from a list of detected attributes from the options menu.\"},\n\t#ifdef GPU_SUPPORT\n\t\t{\"show_gpu_info\",\t\t\"#* If gpu info should be shown in the cpu box. Available values = \\\"Auto\\\", \\\"On\\\" and \\\"Off\\\".\"},\n\t#endif\n\t\t{\"cpu_invert_lower\", \t\"#* Toggles if the lower CPU graph should be inverted.\"},\n\n\t\t{\"cpu_single_graph\", \t\"#* Set to True to completely disable the lower CPU graph.\"},\n\n\t\t{\"cpu_bottom\",\t\t\t\"#* Show cpu box at bottom of screen instead of top.\"},\n\n\t\t{\"show_uptime\", \t\t\"#* Shows the system uptime in the CPU box.\"},\n\n\t\t{\"show_cpu_watts\",\t\t\"#* Shows the CPU package current power consumption in watts. Requires running `make setcap` or `make setuid` or running with sudo.\"},\n\n\t\t{\"check_temp\", \t\t\t\"#* Show cpu temperature.\"},\n\n\t\t{\"cpu_sensor\", \t\t\t\"#* Which sensor to use for cpu temperature, use options menu to select from list of available sensors.\"},\n\n\t\t{\"show_coretemp\", \t\t\"#* Show temperatures for cpu cores also if check_temp is True and sensors has been found.\"},\n\n\t\t{\"cpu_core_map\",\t\t\"#* Set a custom mapping between core and coretemp, can be needed on certain cpus to get correct temperature for correct core.\\n\"\n\t\t\t\t\t\t\t\t\"#* Use lm-sensors or similar to see which cores are reporting temperatures on your machine.\\n\"\n\t\t\t\t\t\t\t\t\"#* Format \\\"x:y\\\" x=core with wrong temp, y=core with correct temp, use space as separator between multiple entries.\\n\"\n\t\t\t\t\t\t\t\t\"#* Example: \\\"4:0 5:1 6:3\\\"\"},\n\n\t\t{\"temp_scale\", \t\t\t\"#* Which temperature scale to use, available values: \\\"celsius\\\", \\\"fahrenheit\\\", \\\"kelvin\\\" and \\\"rankine\\\".\"},\n\n\t\t{\"base_10_sizes\",\t\t\"#* Use base 10 for bits/bytes sizes, KB = 1000 instead of KiB = 1024.\"},\n\n\t\t{\"show_cpu_freq\", \t\t\"#* Show CPU frequency.\"},\n\t#ifdef __linux__\n\t\t{\"freq_mode\",\t\t\t\t\"#* How to calculate CPU frequency, available values: \\\"first\\\", \\\"range\\\", \\\"lowest\\\", \\\"highest\\\" and \\\"average\\\".\"},\n\t#endif\n\t\t{\"clock_format\", \t\t\"#* Draw a clock at top of screen, formatting according to strftime, empty string to disable.\\n\"\n\t\t\t\t\t\t\t\t\"#* Special formatting: /host = hostname | /user = username | /uptime = system uptime\"},\n\n\t\t{\"background_update\", \t\"#* Update main ui in background when menus are showing, set this to false if the menus is flickering too much for comfort.\"},\n\n\t\t{\"custom_cpu_name\", \t\"#* Custom cpu model name, empty string to disable.\"},\n\n\t\t{\"disks_filter\", \t\t\"#* Optional filter for shown disks, should be full path of a mountpoint, separate multiple values with whitespace \\\" \\\".\\n\"\n\t\t\t\t\t\t\t\t\t\"#* Only disks matching the filter will be shown. Prepend exclude= to only show disks not matching the filter. Examples: disk_filter=\\\"/boot /home/user\\\", disks_filter=\\\"exclude=/boot /home/user\\\"\"},\n\n\t\t{\"mem_graphs\", \t\t\t\"#* Show graphs instead of meters for memory values.\"},\n\n\t\t{\"mem_below_net\",\t\t\"#* Show mem box below net box instead of above.\"},\n\n\t\t{\"zfs_arc_cached\",\t\t\"#* Count ZFS ARC in cached and available memory.\"},\n\n\t\t{\"show_swap\", \t\t\t\"#* If swap memory should be shown in memory box.\"},\n\n\t\t{\"swap_disk\", \t\t\t\"#* Show swap as a disk, ignores show_swap value above, inserts itself after first disk.\"},\n\n\t\t{\"show_disks\", \t\t\t\"#* If mem box should be split to also show disks info.\"},\n\n\t\t{\"only_physical\", \t\t\"#* Filter out non physical disks. Set this to False to include network disks, RAM disks and similar.\"},\n\n\t\t{\"use_fstab\", \t\t\t\"#* Read disks list from /etc/fstab. This also disables only_physical.\"},\n\n\t\t{\"zfs_hide_datasets\",\t\t\"#* Setting this to True will hide all datasets, and only show ZFS pools. (IO stats will be calculated per-pool)\"},\n\n\t\t{\"disk_free_priv\",\t\t\"#* Set to true to show available disk space for privileged users.\"},\n\n\t\t{\"show_io_stat\", \t\t\"#* Toggles if io activity % (disk busy time) should be shown in regular disk usage view.\"},\n\n\t\t{\"io_mode\", \t\t\t\"#* Toggles io mode for disks, showing big graphs for disk read/write speeds.\"},\n\n\t\t{\"io_graph_combined\", \t\"#* Set to True to show combined read/write io graphs in io mode.\"},\n\n\t\t{\"io_graph_speeds\", \t\"#* Set the top speed for the io graphs in MiB/s (100 by default), use format \\\"mountpoint:speed\\\" separate disks with whitespace \\\" \\\".\\n\"\n\t\t\t\t\t\t\t\t\"#* Example: \\\"/mnt/media:100 /:20 /boot:1\\\".\"},\n\n\t\t{\"swap_upload_download\", \"#* Swap the positions of the upload and download speed graphs. When true, upload will be on top.\"},\n\n\t\t{\"net_download\", \t\t\"#* Set fixed values for network graphs in Mebibits. Is only used if net_auto is also set to False.\"},\n\n\t\t{\"net_upload\", \"\"},\n\n\t\t{\"net_auto\", \t\t\t\"#* Use network graphs auto rescaling mode, ignores any values set above and rescales down to 10 Kibibytes at the lowest.\"},\n\n\t\t{\"net_sync\", \t\t\t\"#* Sync the auto scaling for download and upload to whichever currently has the highest scale.\"},\n\n\t\t{\"net_iface\", \t\t\t\"#* Starts with the Network Interface specified here.\"},\n\n\t    {\"base_10_bitrate\",     \"#* \\\"True\\\" shows bitrates in base 10 (Kbps, Mbps). \\\"False\\\" shows bitrates in binary sizes (Kibps, Mibps, etc.). \\\"Auto\\\" uses base_10_sizes.\"},\n\n\t\t{\"show_battery\", \t\t\"#* Show battery stats in top right if battery is present.\"},\n\n\t\t{\"selected_battery\",\t\"#* Which battery to use if multiple are present. \\\"Auto\\\" for auto detection.\"},\n\n\t\t{\"show_battery_watts\",\t\"#* Show power stats of battery next to charge indicator.\"},\n\n\t\t{\"log_level\", \t\t\t\"#* Set loglevel for \\\"~/.local/state/btop.log\\\" levels are: \\\"ERROR\\\" \\\"WARNING\\\" \\\"INFO\\\" \\\"DEBUG\\\".\\n\"\n\t\t\t\t\t\t\t\t\"#* The level set includes all lower levels, i.e. \\\"DEBUG\\\" will show all logging info.\"},\n\t\t{\"save_config_on_exit\",  \"#* Automatically save current settings to config file on exit.\"},\n\t#ifdef GPU_SUPPORT\n\n\t\t{\"nvml_measure_pcie_speeds\",\n\t\t\t\t\t\t\t\t\"#* Measure PCIe throughput on NVIDIA cards, may impact performance on certain cards.\"},\n\t\t{\"rsmi_measure_pcie_speeds\",\n\t\t\t\t\t\t\t\t\"#* Measure PCIe throughput on AMD cards, may impact performance on certain cards.\"},\n\t\t{\"gpu_mirror_graph\",\t\"#* Horizontally mirror the GPU graph.\"},\n\t\t{\"shown_gpus\",\t\t\t\"#* Set which GPU vendors to show. Available values are \\\"nvidia amd intel apple\\\"\"},\n\t\t{\"custom_gpu_name0\",\t\"#* Custom gpu0 model name, empty string to disable.\"},\n\t\t{\"custom_gpu_name1\",\t\"#* Custom gpu1 model name, empty string to disable.\"},\n\t\t{\"custom_gpu_name2\",\t\"#* Custom gpu2 model name, empty string to disable.\"},\n\t\t{\"custom_gpu_name3\",\t\"#* Custom gpu3 model name, empty string to disable.\"},\n\t\t{\"custom_gpu_name4\",\t\"#* Custom gpu4 model name, empty string to disable.\"},\n\t\t{\"custom_gpu_name5\",\t\"#* Custom gpu5 model name, empty string to disable.\"},\n\t#endif\n\t};\n\n\tstd::unordered_map<std::string_view, string> strings = {\n\t\t{\"color_theme\", \"Default\"},\n\t\t{\"shown_boxes\", \"cpu mem net proc\"},\n\t\t{\"graph_symbol\", \"braille\"},\n\t\t{\"disable_presets\", \"Off\"},\n\t\t{\"presets\", \"cpu:1:default,proc:0:default cpu:0:default,mem:0:default,net:0:default cpu:0:block,net:0:tty\"},\n\t\t{\"graph_symbol_cpu\", \"default\"},\n\t\t{\"graph_symbol_gpu\", \"default\"},\n\t\t{\"graph_symbol_mem\", \"default\"},\n\t\t{\"graph_symbol_net\", \"default\"},\n\t\t{\"graph_symbol_proc\", \"default\"},\n\t\t{\"proc_sorting\", \"cpu lazy\"},\n\t\t{\"cpu_graph_upper\", \"Auto\"},\n\t\t{\"cpu_graph_lower\", \"Auto\"},\n\t\t{\"cpu_sensor\", \"Auto\"},\n\t\t{\"selected_battery\", \"Auto\"},\n\t\t{\"cpu_core_map\", \"\"},\n\t\t{\"temp_scale\", \"celsius\"},\n\t#ifdef __linux__\n\t\t{\"freq_mode\", \"first\"},\n\t#endif\n\t\t{\"clock_format\", \"%X\"},\n\t\t{\"custom_cpu_name\", \"\"},\n\t\t{\"disks_filter\", \"\"},\n\t\t{\"io_graph_speeds\", \"\"},\n\t\t{\"net_iface\", \"\"},\n\t\t{\"base_10_bitrate\", \"Auto\"},\n\t\t{\"log_level\", \"WARNING\"},\n\t\t{\"proc_filter\", \"\"},\n\t\t{\"proc_command\", \"\"},\n\t\t{\"selected_name\", \"\"},\n\t#ifdef GPU_SUPPORT\n\t\t{\"custom_gpu_name0\", \"\"},\n\t\t{\"custom_gpu_name1\", \"\"},\n\t\t{\"custom_gpu_name2\", \"\"},\n\t\t{\"custom_gpu_name3\", \"\"},\n\t\t{\"custom_gpu_name4\", \"\"},\n\t\t{\"custom_gpu_name5\", \"\"},\n\t\t{\"show_gpu_info\", \"Auto\"},\n\t\t{\"shown_gpus\", \"nvidia amd intel apple\"}\n\t#endif\n\t};\n\tstd::unordered_map<std::string_view, string> stringsTmp;\n\n\tstd::unordered_map<std::string_view, bool> bools = {\n\t\t{\"theme_background\", true},\n\t\t{\"truecolor\", true},\n\t\t{\"rounded_corners\", true},\n\t\t{\"proc_reversed\", false},\n\t\t{\"proc_tree\", false},\n\t\t{\"proc_colors\", true},\n\t\t{\"proc_gradient\", true},\n\t\t{\"proc_per_core\", false},\n\t\t{\"proc_mem_bytes\", true},\n\t\t{\"proc_cpu_graphs\", true},\n\t\t{\"proc_info_smaps\", false},\n\t\t{\"proc_left\", false},\n\t\t{\"proc_filter_kernel\", false},\n\t\t{\"cpu_invert_lower\", true},\n\t\t{\"cpu_single_graph\", false},\n\t\t{\"cpu_bottom\", false},\n\t\t{\"show_uptime\", true},\n\t\t{\"show_cpu_watts\", true},\n\t\t{\"check_temp\", true},\n\t\t{\"show_coretemp\", true},\n\t\t{\"show_cpu_freq\", true},\n\t\t{\"background_update\", true},\n\t\t{\"mem_graphs\", true},\n\t\t{\"mem_below_net\", false},\n\t\t{\"zfs_arc_cached\", true},\n\t\t{\"show_swap\", true},\n\t\t{\"swap_disk\", true},\n\t\t{\"show_disks\", true},\n\t\t{\"only_physical\", true},\n\t\t{\"use_fstab\", true},\n\t\t{\"zfs_hide_datasets\", false},\n\t\t{\"show_io_stat\", true},\n\t\t{\"io_mode\", false},\n\t\t{\"swap_upload_download\", false},\n\t\t{\"base_10_sizes\", false},\n\t\t{\"io_graph_combined\", false},\n\t\t{\"net_auto\", true},\n\t\t{\"net_sync\", true},\n\t\t{\"show_battery\", true},\n\t\t{\"show_battery_watts\", true},\n\t\t{\"vim_keys\", false},\n\t\t{\"tty_mode\", false},\n\t\t{\"disk_free_priv\", false},\n\t\t{\"force_tty\", false},\n\t\t{\"lowcolor\", false},\n\t\t{\"show_detailed\", false},\n\t\t{\"proc_filtering\", false},\n\t\t{\"proc_aggregate\", false},\n\t\t{\"pause_proc_list\", false},\n\t\t{\"keep_dead_proc_usage\", false},\n\t\t{\"proc_banner_shown\", false},\n\t\t{\"proc_follow_detailed\", true},\n\t\t{\"follow_process\", false},\n\t\t{\"update_following\", false},\n\t\t{\"should_selection_return_to_followed\", false},\n\t#ifdef GPU_SUPPORT\n\t\t{\"nvml_measure_pcie_speeds\", true},\n\t\t{\"rsmi_measure_pcie_speeds\", true},\n\t\t{\"gpu_mirror_graph\", true},\n\t#endif\n\t\t{\"terminal_sync\", true},\n\t\t{\"save_config_on_exit\", true},\n\t\t{\"disable_mouse\", false},\n\t};\n\tstd::unordered_map<std::string_view, bool> boolsTmp;\n\n\tstd::unordered_map<std::string_view, int> ints = {\n\t\t{\"update_ms\", 2000},\n\t\t{\"net_download\", 100},\n\t\t{\"net_upload\", 100},\n\t\t{\"detailed_pid\", 0},\n\t\t{\"restore_detailed_pid\", 0},\n\t\t{\"selected_pid\", 0},\n\t\t{\"followed_pid\", 0},\n\t\t{\"selected_depth\", 0},\n\t\t{\"proc_start\", 0},\n\t\t{\"proc_selected\", 0},\n\t\t{\"proc_last_selected\", 0},\n\t\t{\"proc_followed\", 0},\n\t};\n\tstd::unordered_map<std::string_view, int> intsTmp;\n\n\t// Returns a valid config dir or an empty optional\n\t// The config dir might be read only, a warning is printed, but a path is returned anyway\n\t[[nodiscard]] std::optional<fs::path> get_config_dir() noexcept {\n\t\tfs::path config_dir;\n\t\t{\n\t\t\tstd::error_code error;\n\t\t\tif (const auto xdg_config_home = std::getenv(\"XDG_CONFIG_HOME\"); xdg_config_home != nullptr) {\n\t\t\t\tif (fs::exists(xdg_config_home, error)) {\n\t\t\t\t\tconfig_dir = fs::path(xdg_config_home) / \"btop\";\n\t\t\t\t}\n\t\t\t} else if (const auto home = std::getenv(\"HOME\"); home != nullptr) {\n\t\t\t\terror.clear();\n\t\t\t\tif (fs::exists(home, error)) {\n\t\t\t\t\tconfig_dir = fs::path(home) / \".config\" / \"btop\";\n\t\t\t\t}\n\t\t\t\tif (error) {\n\t\t\t\t\tfmt::print(stderr, \"\\033[0;31mWarning: \\033[0m{} could not be accessed: {}\\n\", config_dir.string(), error.message());\n\t\t\t\t\tconfig_dir = \"\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// FIXME: This warnings can be noisy if the user deliberately has a non-writable config dir\n\t\t//  offer an alternative | disable messages by default | disable messages if config dir is not writable | disable messages with a flag\n\t\t// FIXME: Make happy path not branch\n\t\tif (not config_dir.empty()) {\n\t\t\tstd::error_code error;\n\t\t\tif (fs::exists(config_dir, error)) {\n\t\t\t\tif (fs::is_directory(config_dir, error)) {\n\t\t\t\t\tstruct statvfs stats {};\n\t\t\t\t\tif ((fs::status(config_dir, error).permissions() & fs::perms::owner_write) == fs::perms::owner_write and\n\t\t\t\t\t\tstatvfs(config_dir.c_str(), &stats) == 0 and (stats.f_flag & ST_RDONLY) == 0) {\n\t\t\t\t\t\treturn config_dir;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt::print(stderr, \"\\033[0;31mWarning: \\033[0m`{}` is not writable\\n\", fs::absolute(config_dir).string());\n\t\t\t\t\t\t// If the config is readable we can still use the provided config, but changes will not be persistent\n\t\t\t\t\t\tif ((fs::status(config_dir, error).permissions() & fs::perms::owner_read) == fs::perms::owner_read) {\n\t\t\t\t\t\t\tfmt::print(stderr, \"\\033[0;31mWarning: \\033[0mLogging is disabled, config changes are not persistent\\n\");\n\t\t\t\t\t\t\treturn config_dir;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfmt::print(stderr, \"\\033[0;31mWarning: \\033[0m`{}` is not a directory\\n\", fs::absolute(config_dir).string());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Doesn't exist\n\t\t\t\tif (fs::create_directories(config_dir, error)) {\n\t\t\t\t\treturn config_dir;\n\t\t\t\t} else {\n\t\t\t\t\tfmt::print(stderr, \"\\033[0;31mWarning: \\033[0m`{}` could not be created: {}\\n\", fs::absolute(config_dir).string(), error.message());\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfmt::print(stderr, \"\\033[0;31mWarning: \\033[0mCould not determine config path: Make sure `$XDG_CONFIG_HOME` or `$HOME` is set\\n\");\n\t\t}\n\t\tfmt::print(stderr, \"\\033[0;31mWarning: \\033[0mLogging is disabled, config changes are not persistent\\n\");\n\t\treturn {};\n\t}\n\n\tbool _locked(const std::string_view name) {\n\t\tatomic_wait(writelock, true);\n\t\tif (not write_new and rng::find_if(descriptions, [&name](const auto& a) { return a.at(0) == name; }) != descriptions.end())\n\t\t\twrite_new = true;\n\t\treturn locked.load();\n\t}\n\n\tfs::path conf_dir;\n\tfs::path conf_file;\n\n\tvector<string> available_batteries = {\"Auto\"};\n\n\tvector<string> current_boxes;\n\tvector<string> preset_list = {\"cpu:0:default,mem:0:default,net:0:default,proc:0:default\"};\n\tstd::optional<int> current_preset;\n\n\tbool presetsValid(const string& presets) {\n\t\tvector<string> new_presets = {preset_list.at(0)};\n\n\t\tfor (int x = 0; const auto& preset : ssplit(presets)) {\n\t\t\tif (++x > 9) {\n\t\t\t\tvalidError = \"Too many presets entered!\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tfor (int y = 0; const auto& box : ssplit(preset, ',')) {\n\t\t\t\tif (++y > 4) {\n\t\t\t\t\tvalidError = \"Too many boxes entered for preset!\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tconst auto& vals = ssplit(box, ':');\n\t\t\t\tif (vals.size() != 3) {\n\t\t\t\t\tvalidError = \"Malformatted preset in config value presets!\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (not is_in(vals.at(0), \"cpu\", \"mem\", \"net\", \"proc\", \"gpu0\", \"gpu1\", \"gpu2\", \"gpu3\", \"gpu4\", \"gpu5\")) {\n\t\t\t\t\tvalidError = \"Invalid box name in config value presets!\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (not is_in(vals.at(1), \"0\", \"1\")) {\n\t\t\t\t\tvalidError = \"Invalid position value in config value presets!\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif (not v_contains(valid_graph_symbols_def, vals.at(2))) {\n\t\t\t\t\tvalidError = \"Invalid graph name in config value presets!\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\tnew_presets.push_back(preset);\n\t\t}\n\n\t\tpreset_list = std::move(new_presets);\n\t\treturn true;\n\t}\n\n\t//* Apply selected preset\n\tbool apply_preset(const string& preset) {\n\t\tstring boxes;\n\n\t\tfor (const auto& box : ssplit(preset, ',')) {\n\t\t\tconst auto& vals = ssplit(box, ':');\n\t\t\tboxes += vals.at(0) + ' ';\n\t\t}\n\t\tif (not boxes.empty()) boxes.pop_back();\n\n\t\tauto min_size = Term::get_min_size(boxes);\n\t\tif (Term::width < min_size.at(0) or Term::height < min_size.at(1)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (const auto& box : ssplit(preset, ',')) {\n\t\t\tconst auto& vals = ssplit(box, ':');\n\t\t\tif (vals.at(0) == \"cpu\") {\n\t\t\t\tset(\"cpu_bottom\", (vals.at(1) != \"0\"));\n\t\t\t} else if (vals.at(0) == \"mem\") {\n\t\t\t\tset(\"mem_below_net\", (vals.at(1) != \"0\"));\n\t\t\t} else if (vals.at(0) == \"proc\") {\n\t\t\t\tset(\"proc_left\", (vals.at(1) != \"0\"));\n\t\t\t}\n\t\t\tif (vals.at(0).starts_with(\"gpu\")) {\n\t\t\t\tset(\"graph_symbol_gpu\", vals.at(2));\n\t\t\t} else {\n\t\t\t\tset(strings.find(\"graph_symbol_\" + vals.at(0))->first, vals.at(2));\n\t\t\t}\n\t\t}\n\n\t\tif (set_boxes(boxes)) {\n\t\t\tset(\"shown_boxes\", boxes);\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tvoid lock() {\n\t\tatomic_wait(writelock);\n\t\tlocked = true;\n\t}\n\n\tstring validError;\n\n\tbool intValid(const std::string_view name, const string& value) {\n\t\tint i_value;\n\t\ttry {\n\t\t\ti_value = stoi(value);\n\t\t}\n\t\tcatch (const std::invalid_argument&) {\n\t\t\tvalidError = \"Invalid numerical value!\";\n\t\t\treturn false;\n\t\t}\n\t\tcatch (const std::out_of_range&) {\n\t\t\tvalidError = \"Value out of range!\";\n\t\t\treturn false;\n\t\t}\n\t\tcatch (const std::exception& e) {\n\t\t\tvalidError = string{e.what()};\n\t\t\treturn false;\n\t\t}\n\n\t\tif (name == \"update_ms\" and i_value < 100)\n\t\t\tvalidError = \"Config value update_ms set too low (<100).\";\n\n\t\telse if (name == \"update_ms\" and i_value > ONE_DAY_MILLIS)\n\t\t\tvalidError = fmt::format(\"Config value update_ms set too high (>{}).\", ONE_DAY_MILLIS);\n\n\t\telse\n\t\t\treturn true;\n\n\t\treturn false;\n\t}\n\n\tbool validBoxSizes(const string& boxes) {\n\t\tauto min_size = Term::get_min_size(boxes);\n\t\treturn (Term::width >= min_size.at(0) and Term::height >= min_size.at(1));\n\t}\n\n\tbool stringValid(const std::string_view name, const string& value) {\n\t\tif (name == \"log_level\" and not v_contains(Logger::log_levels, value))\n\t\t\tvalidError = \"Invalid log_level: \" + value;\n\n\t\telse if (name == \"graph_symbol\" and not v_contains(valid_graph_symbols, value))\n\t\t\tvalidError = \"Invalid graph symbol identifier: \" + value;\n\n\t\telse if (name.starts_with(\"graph_symbol_\") and (value != \"default\" and not v_contains(valid_graph_symbols, value)))\n\t\t\tvalidError = fmt::format(\"Invalid graph symbol identifier for {}: {}\", name, value);\n\n\t\telse if (name == \"shown_boxes\" and not Global::init_conf) {\n\t\t\tif (value.empty())\n\t\t\t\tvalidError = \"No boxes selected!\";\n\t\t\telse if (not validBoxSizes(value))\n\t\t\t\tvalidError = \"Terminal too small to display entered boxes!\";\n\t\t\telse if (not set_boxes(value))\n\t\t\t\tvalidError = \"Invalid box name(s) in shown_boxes!\";\n\t\t\telse\n\t\t\t\treturn true;\n\t\t}\n\n\t#ifdef GPU_SUPPORT\n\t\telse if (name == \"show_gpu_info\" and not v_contains(show_gpu_values, value))\n\t\t\tvalidError = \"Invalid value for show_gpu_info: \" + value;\n\t#endif\n\n\t\telse if (name == \"presets\" and not presetsValid(value))\n\t\t\treturn false;\n\n\t\telse if (name == \"cpu_core_map\") {\n\t\t\tconst auto maps = ssplit(value);\n\t\t\tbool all_good = true;\n\t\t\tfor (const auto& map : maps) {\n\t\t\t\tconst auto map_split = ssplit(map, ':');\n\t\t\t\tif (map_split.size() != 2)\n\t\t\t\t\tall_good = false;\n\t\t\t\telse if (not isint(map_split.at(0)) or not isint(map_split.at(1)))\n\t\t\t\t\tall_good = false;\n\n\t\t\t\tif (not all_good) {\n\t\t\t\t\tvalidError = \"Invalid formatting of cpu_core_map!\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\telse if (name == \"io_graph_speeds\") {\n\t\t\tconst auto maps = ssplit(value);\n\t\t\tbool all_good = true;\n\t\t\tfor (const auto& map : maps) {\n\t\t\t\tconst auto map_split = ssplit(map, ':');\n\t\t\t\tif (map_split.size() != 2)\n\t\t\t\t\tall_good = false;\n\t\t\t\telse if (map_split.at(0).empty() or not isint(map_split.at(1)))\n\t\t\t\t\tall_good = false;\n\n\t\t\t\tif (not all_good) {\n\t\t\t\t\tvalidError = \"Invalid formatting of io_graph_speeds!\";\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\telse\n\t\t\treturn true;\n\n\t\treturn false;\n\t}\n\n\tstring getAsString(const std::string_view name) {\n\t\tif (auto it = bools.find(name); it != bools.end())\n\t\t\treturn it->second ? \"True\" : \"False\";\n\t\tif (auto it = ints.find(name); it != ints.end())\n\t\t\treturn to_string(it->second);\n\t\tif (auto it = strings.find(name); it != strings.end())\n\t\t\treturn it->second;\n\t\treturn \"\";\n\t}\n\n\tvoid flip(const std::string_view name) {\n\t\tif (_locked(name)) {\n\t\t\tif (boolsTmp.contains(name)) boolsTmp.at(name) = not boolsTmp.at(name);\n\t\t\telse boolsTmp.insert_or_assign(name, (not bools.at(name)));\n\t\t}\n\t\telse bools.at(name) = not bools.at(name);\n\t}\n\n\tvoid unlock() {\n\t\tif (not locked) return;\n\t\tatomic_wait(Runner::active);\n\t\tatomic_lock lck(writelock, true);\n\t\ttry {\n\t\t\tif (Proc::shown) {\n\t\t\t\tints.at(\"selected_pid\") = Proc::selected_pid;\n\t\t\t\tstrings.at(\"selected_name\") = Proc::selected_name;\n\t\t\t\tints.at(\"proc_start\") = Proc::start;\n\t\t\t\tints.at(\"proc_selected\") = Proc::selected;\n\t\t\t\tints.at(\"selected_depth\") = Proc::selected_depth;\n\t\t\t}\n\n\t\t\tfor (auto& item : stringsTmp) {\n\t\t\t\tstrings.at(item.first) = item.second;\n\t\t\t}\n\t\t\tstringsTmp.clear();\n\n\t\t\tfor (auto& item : intsTmp) {\n\t\t\t\tints.at(item.first) = item.second;\n\t\t\t}\n\t\t\tintsTmp.clear();\n\n\t\t\tfor (auto& item : boolsTmp) {\n\t\t\t\tbools.at(item.first) = item.second;\n\t\t\t}\n\t\t\tboolsTmp.clear();\n\t\t}\n\t\tcatch (const std::exception& e) {\n\t\t\tGlobal::exit_error_msg = fmt::format(\"Exception during Config::unlock() : {}\", e.what());\n\t\t\tclean_quit(1);\n\t\t}\n\n\t\tlocked = false;\n\t}\n\n\tbool set_boxes(const string& boxes) {\n\t\tauto new_boxes = ssplit(boxes);\n\t\tfor (auto& box : new_boxes) {\n\t\t\tif (not v_contains(valid_boxes, box)) return false;\n\t\t#ifdef GPU_SUPPORT\n\t\t\tif (box.starts_with(\"gpu\")) {\n\t\t\t\tint gpu_num = stoi(box.substr(3)) + 1;\n\t\t\t\tif (gpu_num > Gpu::count) return false;\n\t\t\t}\n\t\t#endif\n\t\t}\n\t\tcurrent_boxes = std::move(new_boxes);\n\t\treturn true;\n\t}\n\n\tbool toggle_box(const string& box) {\n\t\tauto old_boxes = current_boxes;\n\t\tauto box_pos = rng::find(current_boxes, box);\n\t\tif (box_pos == current_boxes.end())\n\t\t\tcurrent_boxes.push_back(box);\n\t\telse\n\t\t\tcurrent_boxes.erase(box_pos);\n\n\t\tstring new_boxes;\n\t\tif (not current_boxes.empty()) {\n\t\t\tfor (const auto& b : current_boxes) new_boxes += b + ' ';\n\t\t\tnew_boxes.pop_back();\n\t\t}\n\n\t\tauto min_size = Term::get_min_size(new_boxes);\n\n\t\tif (Term::width < min_size.at(0) or Term::height < min_size.at(1)) {\n\t\t\tcurrent_boxes = old_boxes;\n\t\t\treturn false;\n\t\t}\n\n\t\tConfig::set(\"shown_boxes\", new_boxes);\n\t\treturn true;\n\t}\n\n\tvoid load(const fs::path& conf_file, vector<string>& load_warnings) {\n\t\tstd::error_code error;\n\t\tif (conf_file.empty())\n\t\t\treturn;\n\t\telse if (not fs::exists(conf_file, error)) {\n\t\t\twrite_new = true;\n\t\t\treturn;\n\t\t}\n\t\tif (error) {\n\t\t\treturn;\n\t\t}\n\n\t\tstd::ifstream cread(conf_file);\n\t\tif (cread.good()) {\n\t\t\tvector<string> valid_names;\n\t\t\tvalid_names.reserve(descriptions.size());\n\t\t\tfor (const auto &n : descriptions)\n\t\t\t\tvalid_names.push_back(n[0]);\n\t\t\tif (string v_string; cread.peek() != '#' or (getline(cread, v_string, '\\n') and not v_string.contains(Global::Version)))\n\t\t\t\twrite_new = true;\n\t\t\twhile (not cread.eof()) {\n\t\t\t\tcread >> std::ws;\n\t\t\t\tif (cread.peek() == '#') {\n\t\t\t\t\tcread.ignore(SSmax, '\\n');\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstring name, value;\n\t\t\t\tgetline(cread, name, '=');\n\t\t\t\tif (name.ends_with(' ')) name = trim(name);\n\t\t\t\tif (not v_contains(valid_names, name)) {\n\t\t\t\t\tcread.ignore(SSmax, '\\n');\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tcread >> std::ws;\n\n\t\t\t\tif (bools.contains(name)) {\n\t\t\t\t\tcread >> value;\n\t\t\t\t\tif (not isbool(value))\n\t\t\t\t\t\tload_warnings.push_back(\"Got an invalid bool value for config name: \" + name);\n\t\t\t\t\telse\n\t\t\t\t\t\tbools.at(name) = stobool(value);\n\t\t\t\t}\n\t\t\t\telse if (ints.contains(name)) {\n\t\t\t\t\tcread >> value;\n\t\t\t\t\tif (not isint(value))\n\t\t\t\t\t\tload_warnings.push_back(\"Got an invalid integer value for config name: \" + name);\n\t\t\t\t\telse if (not intValid(name, value)) {\n\t\t\t\t\t\tload_warnings.push_back(validError);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tints.at(name) = stoi(value);\n\t\t\t\t}\n\t\t\t\telse if (strings.contains(name)) {\n\t\t\t\t\tif (cread.peek() == '\"') {\n\t\t\t\t\t\tcread.ignore(1);\n\t\t\t\t\t\tgetline(cread, value, '\"');\n\t\t\t\t\t}\n\t\t\t\t\telse cread >> value;\n\n\t\t\t\t\tif (not stringValid(name, value))\n\t\t\t\t\t\tload_warnings.push_back(validError);\n\t\t\t\t\telse\n\t\t\t\t\t\tstrings.at(name) = value;\n\t\t\t\t}\n\n\t\t\t\tcread.ignore(SSmax, '\\n');\n\t\t\t}\n\n\t\t\tif (not load_warnings.empty()) write_new = true;\n\t\t}\n\t}\n\n\tvoid write() {\n\t\tif (conf_file.empty() or not write_new) return;\n\t\tLogger::debug(\"Writing new config file\");\n\t\tif (geteuid() != Global::real_uid and seteuid(Global::real_uid) != 0) return;\n\t\tstd::ofstream cwrite(conf_file, std::ios::trunc);\n\t\t// TODO: Report error when stream is in a bad state.\n\t\tif (cwrite.good()) {\n\t\t\tcwrite << current_config();\n\t\t}\n\t}\n\n\tstatic constexpr auto get_xdg_state_dir() -> std::optional<fs::path> {\n\t\tstd::optional<fs::path> xdg_state_home;\n\n\t\t{\n\t\t\tconst auto* xdg_state_home_ptr = std::getenv(\"XDG_STATE_HOME\");\n\t\t\tif (xdg_state_home_ptr != nullptr) {\n\t\t\t\txdg_state_home = std::make_optional(fs::path(xdg_state_home_ptr));\n\t\t\t} else {\n\t\t\t\tconst auto* home_ptr = std::getenv(\"HOME\");\n\t\t\t\tif (home_ptr != nullptr) {\n\t\t\t\t\txdg_state_home = std::make_optional(fs::path(home_ptr) / \".local\" / \"state\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (xdg_state_home.has_value()) {\n\t\t\tstd::error_code err;\n\t\t\tfs::create_directories(xdg_state_home.value(), err);\n\t\t\tif (err) {\n\t\t\t\treturn std::nullopt;\n\t\t\t}\n\t\t\treturn xdg_state_home;\n\t\t}\n\t\treturn std::nullopt;\n\t}\n\n\tauto get_log_file() -> std::optional<fs::path> {\n\t\treturn get_xdg_state_dir().transform([](auto&& state_home) -> auto { return state_home / \"btop.log\"; });\n\t}\n\n\tauto current_config() -> std::string {\n\t\tauto buffer = std::string {};\n\t\tfmt::format_to(std::back_inserter(buffer), \"#? Config file for btop v.{}\\n\", Global::Version);\n\n\t\tfor (const auto& [name, description] : descriptions) {\n\t\t\t// Write a description comment if available.\n\t\t\tfmt::format_to(std::back_inserter(buffer), \"\\n\");\n\t\t\tif (!description.empty()) {\n\t\t\t\tfmt::format_to(std::back_inserter(buffer), \"{}\\n\", description);\n\t\t\t}\n\n\t\t\tfmt::format_to(std::back_inserter(buffer), \"{} = \", name);\n\t\t\t// Lookup default value by name and write it out.\n\t\t\tif (strings.contains(name)) {\n\t\t\t\tfmt::format_to(std::back_inserter(buffer), R\"(\"{}\")\", strings[name]);\n\t\t\t} else if (ints.contains(name)) {\n\t\t\t\tfmt::format_to(std::back_inserter(buffer), std::locale::classic(), \"{:L}\", ints[name]);\n\t\t\t} else if (bools.contains(name)) {\n\t\t\t\tfmt::format_to(std::back_inserter(buffer), \"{}\", bools[name] ? \"true\" : \"false\");\n\t\t\t}\n\t\t\tfmt::format_to(std::back_inserter(buffer), \"\\n\");\n\t\t}\n\t\treturn buffer;\n\t}\n}\n"
  },
  {
    "path": "src/btop_config.hpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#pragma once\n\n#include <filesystem>\n#include <optional>\n#include <string>\n#include <vector>\n\n#include <unordered_map>\n\nusing std::string;\nusing std::vector;\n\n//* Functions and variables for reading and writing the btop config file\nnamespace Config {\n\n\textern std::filesystem::path conf_dir;\n\textern std::filesystem::path conf_file;\n\n\textern std::unordered_map<std::string_view, string> strings;\n\textern std::unordered_map<std::string_view, string> stringsTmp;\n\textern std::unordered_map<std::string_view, bool> bools;\n\textern std::unordered_map<std::string_view, bool> boolsTmp;\n\textern std::unordered_map<std::string_view, int> ints;\n\textern std::unordered_map<std::string_view, int> intsTmp;\n\n\tconst vector<string> valid_graph_symbols = { \"braille\", \"block\", \"tty\" };\n\tconst vector<string> valid_graph_symbols_def = { \"default\", \"braille\", \"block\", \"tty\" };\n\tconst vector<string> valid_boxes = {\n\t\t\"cpu\", \"mem\", \"net\", \"proc\"\n#ifdef GPU_SUPPORT\n\t\t,\"gpu0\", \"gpu1\", \"gpu2\", \"gpu3\", \"gpu4\", \"gpu5\"\n#endif\n\t\t};\n\tconst vector<string> temp_scales = { \"celsius\", \"fahrenheit\", \"kelvin\", \"rankine\" };\n#ifdef __linux__\n\tconst vector<string> freq_modes = { \"first\", \"range\", \"lowest\", \"highest\", \"average\" };\n#endif\n#ifdef GPU_SUPPORT\n\tconst vector<string> show_gpu_values = { \"Auto\", \"On\", \"Off\" };\n#endif\n    const vector<string> base_10_bitrate_values = { \"Auto\", \"True\", \"False\" };\n\textern vector<string> current_boxes;\n\textern vector<string> preset_list;\n\tconst vector<string> disable_preset_options = { \"Off\", \"Default\", \"Custom\", \"All\" };\n\textern vector<string> available_batteries;\n\textern std::optional<int> current_preset;\n\n\textern bool write_new;\n\n\tconstexpr int ONE_DAY_MILLIS = 1000 * 60 * 60 * 24;\n\n\t[[nodiscard]] std::optional<std::filesystem::path> get_config_dir() noexcept;\n\n\t//* Check if string only contains space separated valid names for boxes and set current_boxes\n\tbool set_boxes(const string& boxes);\n\n\tbool validBoxSizes(const string& boxes);\n\n\t//* Toggle box and update config string shown_boxes\n\tbool toggle_box(const string& box);\n\n\t//* Parse and setup config value presets\n\tbool presetsValid(const string& presets);\n\n\t//* Apply selected preset\n\tbool apply_preset(const string& preset);\n\n\tbool _locked(const std::string_view name);\n\n\t//* Return bool for config key <name>\n\tinline bool getB(const std::string_view name) { return bools.at(name); }\n\n\t//* Return integer for config key <name>\n\tinline const int& getI(const std::string_view name) { return ints.at(name); }\n\n\t//* Return string for config key <name>\n\tinline const string& getS(const std::string_view name) { return strings.at(name); }\n\n\tstring getAsString(const std::string_view name);\n\n\textern string validError;\n\n\tbool intValid(const std::string_view name, const string& value);\n\tbool stringValid(const std::string_view name, const string& value);\n\n\t//* Set config key <name> to bool <value>\n\tinline void set(const std::string_view name, bool value) {\n\t\tif (_locked(name)) boolsTmp.insert_or_assign(name, value);\n\t\telse bools.at(name) = value;\n\t}\n\n\t//* Set config key <name> to int <value>\n\tinline void set(const std::string_view name, const int value) {\n\t\tif (_locked(name)) intsTmp.insert_or_assign(name, value);\n\t\telse ints.at(name) = value;\n\t}\n\n\t//* Set config key <name> to string <value>\n\tinline void set(const std::string_view name, const string& value) {\n\t\tif (_locked(name)) stringsTmp.insert_or_assign(name, value);\n\t\telse strings.at(name) = value;\n\t}\n\n\t//* Flip config key bool <name>\n\tvoid flip(const std::string_view name);\n\n\t//* Lock config and cache changes until unlocked\n\tvoid lock();\n\n\t//* Unlock config and write any cached values to config\n\tvoid unlock();\n\n\t//* Load the config file from disk\n\tvoid load(const std::filesystem::path& conf_file, vector<string>& load_warnings);\n\n\t//* Write the config file to disk\n\tvoid write();\n\n\tauto get_log_file() -> std::optional<std::filesystem::path>;\n\n\t// Write default config to an in-memory buffer\n\t[[nodiscard]] auto current_config() -> std::string;\n}\n"
  },
  {
    "path": "src/btop_draw.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include <algorithm>\n#include <array>\n#include <cmath>\n#include <iterator>\n#include <ranges>\n#include <stdexcept>\n#include <string>\n#include <string_view>\n#include <utility>\n\n#include <fmt/format.h>\n\n#include \"btop_config.hpp\"\n#include \"btop_draw.hpp\"\n#include \"btop_input.hpp\"\n#include \"btop_log.hpp\"\n#include \"btop_menu.hpp\"\n#include \"btop_shared.hpp\"\n#include \"btop_theme.hpp\"\n#include \"btop_tools.hpp\"\n\nusing std::array;\nusing std::clamp;\nusing std::cmp_equal;\nusing std::cmp_greater;\nusing std::cmp_less;\nusing std::cmp_less_equal;\nusing std::floor;\nusing std::max;\nusing std::min;\nusing std::round;\nusing std::to_string;\nusing std::views::iota;\n\nusing namespace Tools;\nusing namespace std::literals; // for operator\"\"s\nnamespace rng = std::ranges;\n\nnamespace Symbols {\n\tconst string meter = \"■\";\n\n\tconst array<string, 10> superscript = { \"⁰\", \"¹\", \"²\", \"³\", \"⁴\", \"⁵\", \"⁶\", \"⁷\", \"⁸\", \"⁹\" };\n\n\tconst std::unordered_map<string, vector<string>> graph_symbols = {\n\t\t{ \"braille_up\", {\n\t\t\t\" \", \"⢀\", \"⢠\", \"⢰\", \"⢸\",\n\t\t\t\"⡀\", \"⣀\", \"⣠\", \"⣰\", \"⣸\",\n\t\t\t\"⡄\", \"⣄\", \"⣤\", \"⣴\", \"⣼\",\n\t\t\t\"⡆\", \"⣆\", \"⣦\", \"⣶\", \"⣾\",\n\t\t\t\"⡇\", \"⣇\", \"⣧\", \"⣷\", \"⣿\"\n\t\t}},\n\t\t{\"braille_down\", {\n\t\t\t\" \", \"⠈\", \"⠘\", \"⠸\", \"⢸\",\n\t\t\t\"⠁\", \"⠉\", \"⠙\", \"⠹\", \"⢹\",\n\t\t\t\"⠃\", \"⠋\", \"⠛\", \"⠻\", \"⢻\",\n\t\t\t\"⠇\", \"⠏\", \"⠟\", \"⠿\", \"⢿\",\n\t\t\t\"⡇\", \"⡏\", \"⡟\", \"⡿\", \"⣿\"\n\t\t}},\n\t\t{\"block_up\", {\n\t\t\t\" \", \"▗\", \"▗\", \"▐\", \"▐\",\n\t\t\t\"▖\", \"▄\", \"▄\", \"▟\", \"▟\",\n\t\t\t\"▖\", \"▄\", \"▄\", \"▟\", \"▟\",\n\t\t\t\"▌\", \"▙\", \"▙\", \"█\", \"█\",\n\t\t\t\"▌\", \"▙\", \"▙\", \"█\", \"█\"\n\t\t}},\n\t\t{\"block_down\", {\n\t\t\t\" \", \"▝\", \"▝\", \"▐\", \"▐\",\n\t\t\t\"▘\", \"▀\", \"▀\", \"▜\", \"▜\",\n\t\t\t\"▘\", \"▀\", \"▀\", \"▜\", \"▜\",\n\t\t\t\"▌\", \"▛\", \"▛\", \"█\", \"█\",\n\t\t\t\"▌\", \"▛\", \"▛\", \"█\", \"█\"\n\t\t}},\n\t\t{\"tty_up\", {\n\t\t\t\" \", \"░\", \"░\", \"▒\", \"▒\",\n\t\t\t\"░\", \"░\", \"▒\", \"▒\", \"█\",\n\t\t\t\"░\", \"▒\", \"▒\", \"▒\", \"█\",\n\t\t\t\"▒\", \"▒\", \"▒\", \"█\", \"█\",\n\t\t\t\"▒\", \"█\", \"█\", \"█\", \"█\"\n\t\t}},\n\t\t{\"tty_down\", {\n\t\t\t\" \", \"░\", \"░\", \"▒\", \"▒\",\n\t\t\t\"░\", \"░\", \"▒\", \"▒\", \"█\",\n\t\t\t\"░\", \"▒\", \"▒\", \"▒\", \"█\",\n\t\t\t\"▒\", \"▒\", \"▒\", \"█\", \"█\",\n\t\t\t\"▒\", \"█\", \"█\", \"█\", \"█\"\n\t\t}}\n\t};\n\n}\n\nnamespace Draw {\n\n\tstring banner_gen(int y, int x, bool centered, bool redraw) {\n\t\tstatic string banner;\n\t\tstatic size_t width = 0;\n\t\tif (redraw) banner.clear();\n\t\tif (banner.empty()) {\n\t\t\tstring b_color, bg, fg, oc, letter;\n\t\t\tauto lowcolor = Config::getB(\"lowcolor\");\n\t\t\tauto tty_mode = Config::getB(\"tty_mode\");\n\t\t\tfor (size_t z = 0; const auto& line : Global::Banner_src) {\n\t\t\t\tif (const auto w = ulen(line[1]); w > width) width = w;\n\t\t\t\tif (tty_mode) {\n\t\t\t\t\tfg = (z > 2) ? \"\\x1b[31m\" : \"\\x1b[91m\";\n\t\t\t\t\tbg = (z > 2) ? \"\\x1b[90m\" : \"\\x1b[37m\";\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfg = Theme::hex_to_color(line[0], lowcolor);\n\t\t\t\t\tint bg_i = 120 - z * 12;\n\t\t\t\t\tbg = Theme::dec_to_color(bg_i, bg_i, bg_i, lowcolor);\n\t\t\t\t}\n\t\t\t\tfor (size_t i = 0; i < line[1].size(); i += 3) {\n\t\t\t\t\tif (line[1][i] == ' ') {\n\t\t\t\t\t\tletter = Mv::r(1);\n\t\t\t\t\t\ti -= 2;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tletter = line[1].substr(i, 3);\n\n\t\t\t\t\tb_color = (letter == \"█\") ? fg : bg;\n\t\t\t\t\tif (b_color != oc) banner += b_color;\n\t\t\t\t\tbanner += letter;\n\t\t\t\t\toc = b_color;\n\t\t\t\t}\n\t\t\t\tif (++z < Global::Banner_src.size()) banner += Mv::l(ulen(line[1])) + Mv::d(1);\n\t\t\t}\n\t\t\tbanner += Mv::r(18 - Global::Version.size())\n\t\t\t\t\t+ Theme::c(\"main_fg\") + Fx::b + Fx::i + \"v\" + Global::Version + Fx::reset;\n\t\t}\n\t\tif (redraw) return \"\";\n\t\treturn (centered ? Mv::to(y, Term::width / 2 - width / 2) : Mv::to(y, x)) + banner;\n\t}\n\n\tTextEdit::TextEdit() {}\n\tTextEdit::TextEdit(string text, bool numeric) : numeric(numeric), text(std::move(text)) {\n\t\tpos = this->text.size();\n\t\tupos = ulen(this->text);\n\t}\n\n\tbool TextEdit::command(const std::string_view key) {\n\t\tif (key == \"left\" and upos > 0) {\n\t\t\tupos--;\n\t\t\tpos = uresize(text, upos).size();\n\t\t}\n\t\telse if (key == \"right\" and pos < text.size()) {\n\t\t\tupos++;\n\t\t\tpos = uresize(text, upos).size();\n\t\t}\n\t\telse if (key == \"home\" and not text.empty() and pos > 0) {\n\t\t\tpos = upos = 0;\n\t\t}\n\t\telse if (key == \"end\" and not text.empty() and pos < text.size()) {\n\t\t\tpos = text.size();\n\t\t\tupos = ulen(text);\n\t\t}\n\t\telse if (key == \"backspace\" and pos > 0) {\n\t\t\tif (pos == text.size()) {\n\t\t\t\ttext = uresize(text, --upos);\n\t\t\t\tpos = text.size();\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst string first = uresize(text, --upos);\n\t\t\t\tpos = first.size();\n\t\t\t\ttext = first + luresize(text.substr(pos), ulen(text) - upos - 1);\n\t\t\t}\n\t\t}\n\t\telse if (key == \"delete\" and pos < text.size()) {\n\t\t\tconst string first = uresize(text, upos + 1);\n\t\t\ttext = uresize(first, ulen(first) - 1) + text.substr(first.size());\n\t\t}\n\t\telse if (key == \"space\" and not numeric) {\n\t\t\ttext.insert(pos++, 1, ' ');\n\t\t\tupos++;\n\t\t}\n\t\telse if (ulen(key) == 1 and text.size() < text.max_size() - 20) {\n\t\t\tif (numeric and not isint(key)) return false;\n\t\t\tif (key.size() == 1) {\n\t\t\t\ttext.insert(pos++, 1, key.at(0));\n\t\t\t\tupos++;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tconst auto first = fmt::format(\"{}{}\", uresize(text, upos), key);\n\t\t\t\ttext = first + text.substr(pos);\n\t\t\t\tupos++;\n\t\t\t\tpos = first.size();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\treturn false;\n\n\t\treturn true;\n\t}\n\n\tstring TextEdit::operator()(const size_t limit) {\n\t\tstring out;\n\t\tsize_t c_upos = upos;\n\t\tif (text.empty())\n\t\t\treturn Fx::ul + \" \" + Fx::uul;\n\t\tif (limit > 0 and ulen(text) + 1 > limit) {\n\t\t\ttry {\n\t\t\t\tconst size_t half = (size_t)round((double)limit / 2);\n\t\t\t\tstring first;\n\n\t\t\t\tif (upos + half > ulen(text))\n\t\t\t\t\tfirst = luresize(text.substr(0, pos), limit - (ulen(text) - upos));\n\t\t\t\telse if (upos - half < 1)\n\t\t\t\t\tfirst = text.substr(0, pos);\n\t\t\t\telse\n\t\t\t\t\tfirst = luresize(text.substr(0, pos), half);\n\n\t\t\t\tout = first + uresize(text.substr(pos), limit - ulen(first));\n\t\t\t\tc_upos = ulen(first);\n\t\t\t}\n\t\t\tcatch (const std::exception& e) {\n\t\t\t\tLogger::error(\"In TextEdit::operator() : {}\", e.what());\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tout = text;\n\n\t\tif (c_upos == 0)\n\t\t\treturn Fx::ul + uresize(out, 1) + Fx::uul + luresize(out, ulen(out) - 1);\n\t\telse if (c_upos == ulen(out))\n\t\t\treturn out + Fx::ul + \" \" + Fx::uul;\n\t\telse\n\t\t\treturn uresize(out, c_upos) + Fx::ul + luresize(uresize(out, c_upos + 1), 1) + Fx::uul + luresize(out, ulen(out) - c_upos - 1);\n\t}\n\n\tvoid TextEdit::clear() {\n\t\tthis->text.clear();\n\t}\n\n\tstring createBox(\n\t\t\tconst int x, const int y, const int width, const int height, string line_color, bool fill, const std::string_view title,\n\t\t\tconst std::string_view title2, const int num\n\t) {\n\t\tstring out;\n\n\t\tif (line_color.empty())\n\t\t\tline_color = Theme::c(\"div_line\");\n\n\t\tauto tty_mode = Config::getB(\"tty_mode\");\n\t\tauto rounded = Config::getB(\"rounded_corners\");\n\t\tconst string numbering = (num == 0) ? \"\" : Theme::c(\"hi_fg\") + (tty_mode ? std::to_string(num) : Symbols::superscript.at(clamp(num, 0, 9)));\n\t\tconst auto& right_up = (tty_mode or not rounded ? Symbols::right_up : Symbols::round_right_up);\n\t\tconst auto& left_up = (tty_mode or not rounded ? Symbols::left_up : Symbols::round_left_up);\n\t\tconst auto& right_down = (tty_mode or not rounded ? Symbols::right_down : Symbols::round_right_down);\n\t\tconst auto& left_down = (tty_mode or not rounded ? Symbols::left_down : Symbols::round_left_down);\n\n\t\tout = Fx::reset + line_color;\n\n\t\t//? Draw horizontal lines\n\t\tfor (const int& hpos : {y, y + height - 1}) {\n\t\t\tout += Mv::to(hpos, x) + Symbols::h_line * (width - 1);\n\t\t}\n\n\t\t//? Draw vertical lines and fill if enabled\n\t\tfor (const int& hpos : iota(y + 1, y + height - 1)) {\n\t\t\tout += Mv::to(hpos, x) + Symbols::v_line\n\t\t\t\t+  ((fill) ? string(width - 2, ' ') : Mv::r(width - 2))\n\t\t\t\t+  Symbols::v_line;\n\t\t}\n\n\t\t//? Draw corners\n\t\tout += \tMv::to(y, x) + left_up\n\t\t\t+\tMv::to(y, x + width - 1) + right_up\n\t\t\t+\tMv::to(y + height - 1, x) +left_down\n\t\t\t+\tMv::to(y + height - 1, x + width - 1) + right_down;\n\n\t\t//? Draw titles if defined\n\t\tif (not title.empty()) {\n\t\t\tout += fmt::format(\n\t\t\t\t\"{}{}{}{}{}{}{}{}{}\", Mv::to(y, x + 2), Symbols::title_left, Fx::b, numbering, Theme::c(\"title\"), title, Fx::ub,\n\t\t\t\tline_color, Symbols::title_right\n\t\t\t);\n\t\t}\n\t\tif (not title2.empty()) {\n\t\t\tout += fmt::format(\n\t\t\t\t\"{}{}{}{}{}{}{}{}{}\", Mv::to(y + height - 1, x + 2), Symbols::title_left_down, Fx::b, numbering, Theme::c(\"title\"), title2, Fx::ub,\n\t\t\t\tline_color, Symbols::title_right_down\n\t\t\t);\n\t\t}\n\n\t\treturn out + Fx::reset + Mv::to(y + 1, x + 1);\n\t}\n\n\tbool update_clock(bool force) {\n\t\tconst auto& clock_format = Config::getS(\"clock_format\");\n\t\tif (not Cpu::shown or clock_format.empty()) {\n\t\t\tif (clock_format.empty() and not Global::clock.empty()) Global::clock.clear();\n\t\t\treturn false;\n\t\t}\n\n\t\tstatic const std::unordered_map<string, string> clock_custom_format = {\n\t\t\t{\"/user\", Tools::username()},\n\t\t\t{\"/host\", Tools::hostname()},\n\t\t\t{\"/uptime\", \"\"}\n\t\t};\n\n\t\tstatic time_t c_time{};\n\t\tstatic size_t clock_len{};\n\t\tstatic string clock_str;\n\n\t\tif (auto n_time = time(nullptr); not force and n_time == c_time)\n\t\t\treturn false;\n\t\telse {\n\t\t\tc_time = n_time;\n\t\t\tconst auto new_clock = Tools::strf_time(clock_format);\n\t\t\tif (not force and new_clock == clock_str) return false;\n\t\t\tclock_str = new_clock;\n\t\t}\n\n\t\tauto& out = Global::clock;\n\t\tauto cpu_bottom = Config::getB(\"cpu_bottom\");\n\t\tconst auto& x = Cpu::x;\n\t\tconst auto y = (cpu_bottom ? Cpu::y + Cpu::height - 1 : Cpu::y);\n\t\tconst auto& width = Cpu::width;\n\t\tconst auto& title_left = (cpu_bottom ? Symbols::title_left_down : Symbols::title_left);\n\t\tconst auto& title_right = (cpu_bottom ? Symbols::title_right_down : Symbols::title_right);\n\n\n\t\tfor (const auto& [c_format, replacement] : clock_custom_format) {\n\t\t\tif (clock_str.contains(c_format)) {\n\t\t\t\tif (c_format == \"/uptime\") {\n\t\t\t\t\tstring upstr = sec_to_dhms(system_uptime());\n\t\t\t\t\tif (upstr.size() > 8) upstr.resize(upstr.size() - 3);\n\t\t\t\t\tclock_str = s_replace(clock_str, c_format, upstr);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tclock_str = s_replace(clock_str, c_format, replacement);\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tclock_str = uresize(clock_str, std::max(10, width - 66 - (Term::width >= 100 and Config::getB(\"show_battery\") and Cpu::has_battery ? 22 : 0)));\n\t\tout.clear();\n\n\t\tif (clock_str.size() != clock_len) {\n\t\t\tif (not Global::resized and clock_len > 0)\n\t\t\t\tout = Mv::to(y, x+(width / 2)-(clock_len / 2)) + Fx::ub + Theme::c(\"cpu_box\") + Symbols::h_line * clock_len;\n\t\t\tclock_len = clock_str.size();\n\t\t}\n\n\t\tout += Mv::to(y, x+(width / 2)-(clock_len / 2)) + Fx::ub + Theme::c(\"cpu_box\") + title_left\n\t\t\t+ Theme::c(\"title\") + Fx::b + clock_str + Theme::c(\"cpu_box\") + Fx::ub + title_right;\n\n\t\treturn true;\n\t}\n\n\t//* Meter class ------------------------------------------------------------------------------------------------------------>\n\tMeter::Meter() {}\n\n\tMeter::Meter(const int width, string color_gradient, bool invert)\n\t\t: width(width), color_gradient(std::move(color_gradient)), invert(invert) {}\n\n\tstring Meter::operator()(int value) {\n\t\tif (width < 1) return \"\";\n\t\tvalue = clamp(value, 0, 100);\n\t\tif (not cache.at(value).empty()) return cache.at(value);\n\t\tauto& out = cache.at(value);\n\t\tfor (const int& i : iota(1, width + 1)) {\n\t\t\tint y = round((double)i * 100.0 / width);\n\t\t\tif (value >= y)\n\t\t\t\tout += Theme::g(color_gradient).at(invert ? 100 - y : y) + Symbols::meter;\n\t\t\telse {\n\t\t\t\tout += Theme::c(\"meter_bg\") + Symbols::meter * (width + 1 - i);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tout += Fx::reset;\n\t\treturn out;\n\t}\n\n\t//* Graph class ------------------------------------------------------------------------------------------------------------>\n\tvoid Graph::_create(const deque<long long>& data, int data_offset) {\n\t\tbool mult = (data.size() - data_offset > 1);\n\t\tconst auto& graph_symbol = Symbols::graph_symbols.at(symbol + '_' + (invert ? \"down\" : \"up\"));\n\t\tarray<int, 2> result;\n\t\tconst float mod = (height == 1) ? 0.3 : 0.1;\n\t\tlong long data_value = 0;\n\t\tif (mult and data_offset > 0) {\n\t\t\tlast = data.at(data_offset - 1);\n\t\t\tif (max_value > 0) last = clamp((last + offset) * 100 / max_value, 0ll, 100ll);\n\t\t}\n\n\t\t//? Horizontal iteration over values in <data>\n\t\tfor (const int& i : iota(data_offset, (int)data.size())) {\n\t\t\t// if (tty_mode and mult and i % 2 != 0) continue;\n\t\t\tif (not tty_mode and mult) current = not current;\n\t\t\tif (i < 0) {\n\t\t\t\tdata_value = 0;\n\t\t\t\tlast = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdata_value = data.at(i);\n\t\t\t\tif (max_value > 0) data_value = clamp((data_value + offset) * 100 / max_value, 0ll, 100ll);\n\t\t\t}\n\n\t\t\t//? Vertical iteration over height of graph\n\t\t\tfor (const int& horizon : iota(0, height)) {\n\t\t\t\tconst int cur_high = (height > 1) ? round(100.0 * (height - horizon) / height) : 100;\n\t\t\t\tconst int cur_low = (height > 1) ? round(100.0 * (height - (horizon + 1)) / height) : 0;\n\t\t\t\t//? Calculate previous + current value to fit two values in 1 braille character\n\t\t\t\tfor (int ai = 0; const auto& value : {last, data_value}) {\n\t\t\t\t\tconst int clamp_min = (no_zero and horizon == height - 1 and not (mult and i == data_offset and ai == 0)) ? 1 : 0;\n\t\t\t\t\tif (value >= cur_high)\n\t\t\t\t\t\tresult[ai++] = 4;\n\t\t\t\t\telse if (value <= cur_low)\n\t\t\t\t\t\tresult[ai++] = clamp_min;\n\t\t\t\t\telse {\n\t\t\t\t\t\tresult[ai++] = clamp((int)round((float)(value - cur_low) * 4 / (cur_high - cur_low) + mod), clamp_min, 4);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? Generate graph symbol from 5x5 2D vector\n\t\t\t\tif (height == 1) {\n\t\t\t\t\tif (result.at(0) + result.at(1) == 0) graphs.at(current).at(horizon) += Mv::r(1);\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (not color_gradient.empty()) graphs.at(current).at(horizon) += Theme::g(color_gradient).at(clamp(max(last, data_value), 0ll, 100ll));\n\t\t\t\t\t\tgraphs.at(current).at(horizon) += graph_symbol.at((result.at(0) * 5 + result.at(1)));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse graphs.at(current).at(horizon) += graph_symbol.at((result.at(0) * 5 + result.at(1)));\n\t\t\t}\n\t\t\tif (mult and i >= 0) last = data_value;\n\t\t}\n\t\tlast = data_value;\n\t\tout.clear();\n\t\tif (height == 1) {\n\t\t\t//if (not color_gradient.empty())\n\t\t\t//\tout += (last < 1 ? Theme::c(\"inactive_fg\") : Theme::g(color_gradient).at(clamp(last, 0ll, 100ll)));\n\t\t\tout += graphs.at(current).at(0);\n\t\t}\n\t\telse {\n\t\t\tfor (const int& i : iota(1, height + 1)) {\n\t\t\t\tif (i > 1) out += Mv::d(1) + Mv::l(width);\n\t\t\t\tif (not color_gradient.empty())\n\t\t\t\t\tout += (invert) ? Theme::g(color_gradient).at(i * 100 / height) : Theme::g(color_gradient).at(100 - ((i - 1) * 100 / height));\n\t\t\t\tout += (invert) ? graphs.at(current).at(height - i) : graphs.at(current).at(i-1);\n\t\t\t}\n\t\t}\n\t\tif (not color_gradient.empty()) out += Fx::reset;\n\t}\n\n\tGraph::Graph() {}\n\n\tGraph::Graph(int width, int height, const string& color_gradient,\n\t\t\t\t const deque<long long>& data, const string& symbol,\n\t\t\t\t bool invert, bool no_zero, long long max_value, long long offset)\n\t: width(width), height(height), color_gradient(color_gradient),\n\t  invert(invert), no_zero(no_zero), offset(offset) {\n\t\tif (Config::getB(\"tty_mode\") or symbol == \"tty\") this->symbol = \"tty\";\n\t\telse if (symbol != \"default\") this->symbol = symbol;\n\t\telse this->symbol = Config::getS(\"graph_symbol\");\n\t\tif (this->symbol == \"tty\") tty_mode = true;\n\n\t\tif (max_value == 0 and offset > 0) max_value = 100;\n\t\tthis->max_value = max_value;\n\t\tconst int value_width = (tty_mode ? data.size() : ceil((double)data.size() / 2));\n\t\tint data_offset = (value_width > width) ? data.size() - width * (tty_mode ? 1 : 2) : 0;\n\n\t\tif (not tty_mode and (data.size() - data_offset) % 2 != 0) {\n\t\t\tdata_offset--;\n\t\t}\n\n\t\t//? Populate the two switching graph vectors and fill empty space if data size < width\n\t\tfor (const int& i : iota(0, height * 2)) {\n\t\t\tif (tty_mode and i % 2 != current) continue;\n\t\t\tgraphs[(i % 2 != 0)].push_back((value_width < width) ? ((height == 1) ? Mv::r(1) : \" \"s) * (width - value_width) : \"\");\n\t\t}\n\t\tif (data.size() == 0) return;\n\t\tthis->_create(data, data_offset);\n\t}\n\n\tstring& Graph::operator()(const deque<long long>& data, bool data_same) {\n\t\tif (data_same) return out;\n\n\t\t//? Make room for new characters on graph\n\t\tif (not tty_mode) current = not current;\n\t\tfor (const int& i : iota(0, height)) {\n\t\t\tif (height == 1 and graphs.at(current).at(i).at(1) == '[') {\n\t\t\t\tif (graphs.at(current).at(i).at(3) == 'C') graphs.at(current).at(i).erase(0, 4);\n\t\t\t\telse graphs.at(current).at(i).erase(0, graphs.at(current).at(i).find_first_of('m') + 4);\n\t\t\t}\n\t\t\telse if (graphs.at(current).at(i).at(0) == ' ') graphs.at(current).at(i).erase(0, 1);\n\t\t\telse graphs.at(current).at(i).erase(0, 3);\n\t\t}\n\t\tthis->_create(data, (int)data.size() - 1);\n\t\treturn out;\n\t}\n\n\tstring& Graph::operator()() {\n\t\treturn out;\n\t}\n\t//*------------------------------------------------------------------------------------------------------------------------->\n\n}\n\nnamespace Cpu {\n\tint width_p = 100, height_p = 32;\n\tint min_width = 60, min_height = 8;\n\tint x = 1, y = 1, width = 20, height;\n\tint b_columns, b_column_size;\n\tint b_x, b_y, b_width, b_height;\n\tfloat max_observed_pwr = 1.0f;\n\n\tint graph_up_height, graph_low_height;\n\tint graph_up_width, graph_low_width;\n\tint gpu_meter_width;\n\tbool shown = true, redraw = true, mid_line = false;\n\tstring box;\n\tvector<Draw::Graph> graphs_upper;\n\tvector<Draw::Graph> graphs_lower;\n\tDraw::Meter cpu_meter;\n\tvector<Draw::Meter> gpu_meters;\n\tvector<Draw::Graph> core_graphs;\n\tvector<Draw::Graph> temp_graphs;\n\tvector<Draw::Graph> gpu_temp_graphs;\n\tvector<Draw::Graph> gpu_mem_graphs;\n\n    string draw(\n\t\tconst cpu_info& cpu,\n#if defined(GPU_SUPPORT)\n\t\tconst vector<Gpu::gpu_info>& gpus,\n#endif // GPU_SUPPORT\n\t\tbool force_redraw,\n\t\tbool data_same\n\t) {\n\t\tif (Runner::stopping) return \"\";\n\t\tif (force_redraw) redraw = true;\n\t\tbool show_temps = (Config::getB(\"check_temp\") and got_sensors);\n\t\tbool show_watts = (Config::getB(\"show_cpu_watts\") and supports_watts);\n\t\tauto single_graph = Config::getB(\"cpu_single_graph\");\n\t\tbool hide_cores = show_temps and (cpu_temp_only or not Config::getB(\"show_coretemp\"));\n\t\tconst int extra_width = (hide_cores ? max(6, 6 * b_column_size) : (b_columns == 1 && !show_temps) ? 8 : 0);\n#if defined(GPU_SUPPORT)\n\t\tconst auto& show_gpu_info = Config::getS(\"show_gpu_info\");\n\t\tconst bool gpu_always = show_gpu_info == \"On\";\n\t\tconst bool gpu_auto = show_gpu_info == \"Auto\";\n\t\tconst bool show_gpu = (gpus.size() > 0 and (gpu_always or (gpu_auto and Gpu::shown < Gpu::count)));\n#endif // GPU_SUPPORT\n\t\tauto graph_up_field = Config::getS(\"cpu_graph_upper\");\n\t\tif (graph_up_field == \"Auto\" or not v_contains(Cpu::available_fields, graph_up_field))\n\t\t\tgraph_up_field = \"total\";\n\t\tauto graph_lo_field = Config::getS(\"cpu_graph_lower\");\n\t\tif (graph_lo_field == \"Auto\" or not v_contains(Cpu::available_fields, graph_lo_field)) {\n\t\t#ifdef GPU_SUPPORT\n\t\t\tgraph_lo_field = show_gpu ? \"gpu-totals\" : graph_up_field;\n\t\t#else\n\t\t\tgraph_lo_field = graph_up_field;\n\t\t#endif\n\t\t}\n\t\tauto tty_mode = Config::getB(\"tty_mode\");\n\t\tauto& graph_symbol = (tty_mode ? \"tty\" : Config::getS(\"graph_symbol_cpu\"));\n\t\tauto& graph_bg = Symbols::graph_symbols.at((graph_symbol == \"default\" ? Config::getS(\"graph_symbol\") + \"_up\" : graph_symbol + \"_up\")).at(6);\n\t\tauto& temp_scale = Config::getS(\"temp_scale\");\n\t\tauto cpu_bottom = Config::getB(\"cpu_bottom\");\n\n\t\tconst string& title_left = Theme::c(\"cpu_box\") + (cpu_bottom ? Symbols::title_left_down : Symbols::title_left);\n\t\tconst string& title_right = Theme::c(\"cpu_box\") + (cpu_bottom ? Symbols::title_right_down : Symbols::title_right);\n\t\tstatic int bat_pos = 0, bat_len = 0;\n\t\tif (safeVal(cpu.cpu_percent, \"total\"s).empty()\n\t\t\tor safeVal(cpu.core_percent, 0).empty()\n\t\t\tor (show_temps and safeVal(cpu.temp, 0).empty())) return \"\";\n\t\tif (safeVal(cpu.cpu_percent, \"total\"s).empty()\n\t\t\tor safeVal(cpu.core_percent, 0).empty()\n\t\t\tor (show_temps and safeVal(cpu.temp, 0).empty())) return \"\";\n\t\tstring out;\n\t\tout.reserve(width * height);\n\n\t\t//* Redraw elements not needed to be updated every cycle\n\t\tif (redraw) {\n\t\t\tmid_line = (not single_graph and graph_up_field != graph_lo_field);\n\t\t\tgraph_up_height = (single_graph ? height - 2 : ceil((double)(height - 2) / 2) - (mid_line and height % 2 != 0));\n\t\t\tgraph_low_height = height - 2 - graph_up_height - mid_line;\n\t\t\tconst int button_y = cpu_bottom ? y + height - 1 : y;\n\t\t\tout += box;\n\n\t\t\t//? Buttons on title\n\t\t\tout += Mv::to(button_y, x + 10) + title_left + Theme::c(\"hi_fg\") + Fx::b + 'm' + Theme::c(\"title\") + \"enu\" + Fx::ub + title_right;\n\t\t\tInput::mouse_mappings[\"m\"] = {button_y, x + 11, 1, 4};\n\t\t\tout += Mv::to(button_y, x + 16) + title_left + Theme::c(\"hi_fg\") + Fx::b + 'p' + Theme::c(\"title\") + \"reset \"\n\t\t\t\t+ (!Config::current_preset.has_value() ? \"*\" : to_string(Config::current_preset.value())) + Fx::ub + title_right;\n\t\t\tInput::mouse_mappings[\"p\"] = {button_y, x + 17, 1, 8};\n\t\t\tconst string update = to_string(Config::getI(\"update_ms\")) + \"ms\";\n\t\t\tout += Mv::to(button_y, x + width - update.size() - 8) + title_left + Fx::b + Theme::c(\"hi_fg\") + \"- \" + Theme::c(\"title\") + update\n\t\t\t\t+ Theme::c(\"hi_fg\") + \" +\" + Fx::ub + title_right;\n\t\t\tInput::mouse_mappings[\"-\"] = {button_y, x + width - (int)update.size() - 7, 1, 2};\n\t\t\tInput::mouse_mappings[\"+\"] = {button_y, x + width - 5, 1, 2};\n\n\t\t\t// Draw container engine name\n\t\t\tif (Cpu::container_engine.has_value()) {\n\t\t\t\tfmt::format_to(std::back_inserter(out), \"{}{}{}{}{}\", Mv::to(button_y, x + 28), title_left, Theme::c(\"title\"), Cpu::container_engine.value(), title_right);\n\t\t\t}\n\n\t\t\t//? Graphs & meters\n\t\t\tconst int graph_default_width = x + width - b_width - 3;\n\n\t\t\tauto init_graphs = [&](vector<Draw::Graph>& graphs, const int graph_height, int& graph_width, const string& graph_field, bool invert) {\n\t\t\t#ifdef GPU_SUPPORT\n\t\t\t\tif (graph_field.starts_with(\"gpu\")) {\n\t\t\t\t\tif (graph_field.find(\"totals\") != string::npos) {\n\t\t\t\t\t\tgraphs.resize(gpus.size());\n\t\t\t\t\t\tgpu_temp_graphs.resize(gpus.size());\n\t\t\t\t\t\tgpu_mem_graphs.resize(gpus.size());\n\t\t\t\t\t\tgpu_meters.resize(gpus.size());\n\t\t\t\t\t\tconst int gpu_draw_count = gpu_always ? Gpu::count : Gpu::count - Gpu::shown;\n\t\t\t\t\t\tgraph_width = gpu_draw_count <= 0 ? graph_default_width : graph_default_width/gpu_draw_count - gpu_draw_count + 1 + graph_default_width%gpu_draw_count;\n\t\t\t\t\t\tfor (size_t i = 0; i < gpus.size(); i++) {\n\t\t\t\t\t\t\tif (gpu_auto and v_contains(Gpu::shown_panels, i))\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tauto& gpu = gpus[i]; auto& graph = graphs[i];\n\n\t\t\t\t\t\t\t//? GPU graphs\n\t\t\t\t\t\t\tif (gpu.supported_functions.gpu_utilization) {\n\t\t\t\t\t\t\t\tif (i + 1 < gpus.size()) {\n\t\t\t\t\t\t\t\t\tgraph = Draw::Graph{graph_width, graph_height, \"cpu\", safeVal(gpu.gpu_percent, graph_field), graph_symbol, invert, true};\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\tgraph = Draw::Graph{\n\t\t\t\t\t\t\t\t\t\tgraph_width + graph_default_width%graph_width - (int)gpus.size() + 1,\n\t\t\t\t\t\t\t\t\t\tgraph_height, \"cpu\", safeVal(gpu.gpu_percent, graph_field), graph_symbol, invert, true\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgraphs.resize(1);\n\t\t\t\t\t\tgraph_width = graph_default_width;\n\t\t\t\t\t\tgraphs[0] = Draw::Graph{ graph_width, graph_height, \"cpu\", safeVal(Gpu::shared_gpu_percent, graph_field), graph_symbol, invert, true };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t#endif\n\t\t\t\t\tgraphs.resize(1);\n\t\t\t\t\tgraph_width = graph_default_width;\n\t\t\t\t\tgraphs[0] = Draw::Graph{ graph_width, graph_height, \"cpu\", safeVal(cpu.cpu_percent, graph_field), graph_symbol, invert, true };\n\t\t\t#ifdef GPU_SUPPORT\n\t\t\t\t}\n\t\t\t#endif\n\t\t\t};\n\n            init_graphs(graphs_upper, graph_up_height, graph_up_width, graph_up_field, false);\n            if (not single_graph)\n            \tinit_graphs(graphs_lower, graph_low_height, graph_low_width, graph_lo_field, Config::getB(\"cpu_invert_lower\"));\n\n\t\t\t#ifdef GPU_SUPPORT\n\t\t\tif (show_gpu and b_columns > 1) {\n\t\t\t\tgpu_temp_graphs.resize(gpus.size());\n\t\t\t\tgpu_mem_graphs.resize(gpus.size());\n\t\t\t\tgpu_meters.resize(gpus.size());\n\t\n\t\t\t\t// Shrink gpu graph width in small boxes to prevent line width extending past box border\n\t\t\t\tauto gpu_graph_width = b_width < 42 ? 4 : 5;\n\n\t\t\t\tfor (size_t i = 0; i < gpus.size(); i++) {\n\t\t\t\t\tif (gpu_auto and v_contains(Gpu::shown_panels, i))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tauto& gpu = gpus[i];\n\n\t\t\t\t\t//? GPU graphs/meters\n\t\t\t\t\tauto width_left = b_width - 10 - (gpus.size() > 9 ? 2 : gpus.size() > 1 ? 1 : 0);\n\t\t\t\t\tif (gpu.supported_functions.temp_info and show_temps) {\n\t\t\t\t\t\tgpu_temp_graphs[i] = Draw::Graph{ gpu_graph_width, 1, \"temp\", gpu.temp, graph_symbol, false, false, gpu.temp_max, -23 };\n\t\t\t\t\t\twidth_left -= 11;\n\t\t\t\t\t}\n\t\t\t\t\tif (gpu.supported_functions.mem_used and gpu.supported_functions.mem_total and b_columns > 1) {\n\t\t\t\t\t\tgpu_mem_graphs[i] = Draw::Graph{ gpu_graph_width, 1, \"used\", safeVal(gpu.gpu_percent, \"gpu-vram-totals\"s), graph_symbol };\n\t\t\t\t\t\twidth_left -= 5;\n\t\t\t\t\t}\n\t\t\t\t\twidth_left -= (gpu.supported_functions.mem_used ? 5 : 0);\n\t\t\t\t\twidth_left -= (gpu.supported_functions.mem_total ? 6 : 0);\n\t\t\t\t\twidth_left -= (gpu.supported_functions.pwr_usage ? 6 : 0);\n\t\t\t\t\tif (gpu.supported_functions.gpu_utilization) {\n\t\t\t\t\t\tgpu_meters[i] = Draw::Meter{width_left, \"cpu\" };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t#endif\n\n\t\t\tint cpu_meter_width = b_width - (show_temps ? 23 - (b_column_size <= 1 and b_columns == 1 ? 6 : 0) : 11);\n\t\t\tif (show_watts) {\n\t\t\t\tcpu_meter_width -= 6;\n\t\t\t}\n\n\t\t\tcpu_meter = Draw::Meter{cpu_meter_width, \"cpu\"};\n\n\t\t\tif (mid_line) {\n\t\t\t\tout += Mv::to(y + graph_up_height + 1, x) + Fx::ub + Theme::c(\"cpu_box\") + Symbols::div_left + Theme::c(\"div_line\")\n\t\t\t\t\t+ Symbols::h_line * (width - b_width - 2) + Symbols::div_right\n\t\t\t\t\t+ Mv::to(y + graph_up_height + 1, x + ((width - b_width) / 2) - ((graph_up_field.size() + graph_lo_field.size()) / 2) - 4)\n\t\t\t\t\t+ Theme::c(\"main_fg\") + graph_up_field + Mv::r(1) + \"▲▼\" + Mv::r(1) + graph_lo_field;\n\t\t\t}\n\n\t\t\tif (b_column_size > 0 or extra_width > 0) {\n\t\t\t\tcore_graphs.clear();\n\t\t\t\tfor (const auto& core_data : cpu.core_percent) {\n\t\t\t\t\tcore_graphs.emplace_back(5 * b_column_size + extra_width, 1, \"cpu\", core_data, graph_symbol);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (show_temps) {\n\t\t\t\ttemp_graphs.clear();\n\t\t\t\ttemp_graphs.emplace_back(5, 1, \"temp\", safeVal(cpu.temp, 0), graph_symbol, false, false, cpu.temp_max, -23);\n\t\t\t\tif (not hide_cores and b_column_size > 1) {\n\t\t\t\t\tfor (const auto& i : iota((size_t)1, cpu.temp.size())) {\n\t\t\t\t\t\ttemp_graphs.emplace_back(5, 1, \"temp\", safeVal(cpu.temp, i), graph_symbol, false, false, cpu.temp_max, -23);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//? Draw battery if enabled and present\n\t\tif (Config::getB(\"show_battery\") and has_battery) {\n\t\t\tstatic int old_percent{};   // defaults to = 0\n\t\t\tstatic long old_seconds{};  // defaults to = 0\n\t\t\tstatic float old_watts{};\t// defaults to = 0\n\t\t\tstatic string old_status;\n\t\t\tstatic Draw::Meter bat_meter {10, \"cpu\", true};\n\t\t\tstatic const std::unordered_map<string, string> bat_symbols = {\n\t\t\t\t{\"charging\", \"▲\"},\n\t\t\t\t{\"discharging\", \"▼\"},\n\t\t\t\t{\"full\", \"■\"},\n\t\t\t\t{\"unknown\", \"○\"}\n\t\t\t};\n\n\t\t\tconst auto& [percent, watts, seconds, status] = current_bat;\n\n\t\t\tif (redraw or percent != old_percent or (watts != old_watts and Config::getB(\"show_battery_watts\")) or seconds != old_seconds or status != old_status) {\n\t\t\t\told_percent = percent;\n\t\t\t\told_watts = watts;\n\t\t\t\told_seconds = seconds;\n\t\t\t\told_status = status;\n\t\t\t\tconst string str_time = (seconds > 0 ? sec_to_dhms(seconds, false, true) : \"\");\n\t\t\t\tconst string str_percent = to_string(percent) + '%';\n\t\t\t\tconst string str_watts = (watts != -1 and Config::getB(\"show_battery_watts\") ? fmt::format(\"{:.2f}\", watts) + 'W' : \"\");\n\t\t\t\tconst auto& bat_symbol = bat_symbols.at((bat_symbols.contains(status) ? status : \"unknown\"));\n\t\t\t\tconst int current_len = (Term::width >= 100 ? 11 : 0) + str_time.size() + str_percent.size() + str_watts.size() + to_string(Config::getI(\"update_ms\")).size();\n\t\t\t\tconst int current_pos = Term::width - current_len - 17;\n\n\t\t\t\tif ((bat_pos != current_pos or bat_len != current_len) and bat_pos > 0 and not redraw)\n\t\t\t\t\tout += Mv::to(y, bat_pos) + Fx::ub + Theme::c(\"cpu_box\") + Symbols::h_line * (bat_len + 4);\n\t\t\t\tbat_pos = current_pos;\n\t\t\t\tbat_len = current_len;\n\n\t\t\t\tout += Mv::to(y, bat_pos) + title_left + Theme::c(\"title\") + Fx::b + \"BAT\" + bat_symbol + ' ' + str_percent\n\t\t\t\t\t+ (Term::width >= 100 ? Fx::ub + ' ' + bat_meter(percent) + Fx::b : \"\")\n\t\t\t\t\t+ (not str_time.empty() ? ' ' + Theme::c(\"title\") + str_time : \"\") + (not str_watts.empty() ? \" \" + Theme::c(\"title\") + Fx::b + str_watts : \"\") + Fx::ub + title_right;\n\t\t\t}\n\t\t}\n\t\telse if (bat_pos > 0) {\n\t\t\tout += Mv::to(y, bat_pos) + Fx::ub + Theme::c(\"cpu_box\") + Symbols::h_line * (bat_len + 4);\n\t\t\tbat_pos = bat_len = 0;\n\t\t}\n\n\t\ttry {\n\t\t\t//? Cpu/Gpu graphs\n\t\t\tout += Fx::ub + Mv::to(y + 1, x + 1);\n\t\t\tauto draw_graphs = [&](vector<Draw::Graph>& graphs, const int graph_height, const int graph_width, const string& graph_field) {\n\t\t\t#ifdef GPU_SUPPORT\n\t\t\t\tif (graph_field.starts_with(\"gpu\"))\n\t\t\t\t\tif (graph_field.ends_with(\"totals\")) {\n\t\t\t\t\t\tint gpu_drawn = 0;\n\t\t\t\t\t\tfor (size_t i = 0; i < gpus.size(); i++) {\n\t\t\t\t\t\t\tif (gpu_auto and v_contains(Gpu::shown_panels, i)) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst auto& gpu_percent = gpus[i].gpu_percent;\n\t\t\t\t\t\t\t\tout += graphs[i](safeVal(gpu_percent, graph_field), (data_same or redraw));\n\t\t\t\t\t\t\t} catch (std::out_of_range& /* unused */) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (Gpu::count - (gpu_auto ? Gpu::shown : 0) > 1) {\n\t\t\t\t\t\t\t\tauto i_str = to_string(i);\n\t\t\t\t\t\t\t\tout += Mv::l(graph_width-1) + Mv::u(graph_height/2) + (graph_width > 5 ? \"GPU\" : \"\") + i_str\n\t\t\t\t\t\t\t\t\t+ Mv::d(graph_height/2) + Mv::r(graph_width - 1 - (graph_width > 5)*3 - i_str.size());\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (++gpu_drawn < Gpu::count - (gpu_auto ? Gpu::shown : 0))\n\t\t\t\t\t\t\t\tout += Theme::c(\"div_line\") + (Symbols::v_line + Mv::l(1) + Mv::u(1))*graph_height + Mv::r(1) + Mv::d(1);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tout += graphs[0](safeVal(Gpu::shared_gpu_percent, graph_field), (data_same or redraw));\n\t\t\t\telse\n\t\t\t#else\n\t\t\t\t(void)graph_height;\n\t\t\t\t(void)graph_width;\n\t\t\t#endif\n\t\t\t\t\tout += graphs[0](safeVal(cpu.cpu_percent, graph_field), (data_same or redraw));\n\t\t\t};\n\n\t\t\tdraw_graphs(graphs_upper, graph_up_height, graph_up_width, graph_up_field);\n\t\t\tif (not single_graph) {\n\t\t\t\tout += Mv::to(y + graph_up_height + 1 + mid_line, x + 1);\n\t\t\t\tdraw_graphs(graphs_lower, graph_low_height, graph_low_width, graph_lo_field);\n\t\t\t}\n\n\t\t\t//? Uptime\n\t\t\tif (Config::getB(\"show_uptime\")) {\n\t\t\t\tstring upstr = sec_to_dhms(system_uptime());\n\t\t\t\tif (upstr.size() > 8) {\n\t\t\t\t\tupstr.resize(upstr.size() - 3);\n\t\t\t\t\tupstr = trans(upstr);\n\t\t\t\t}\n\t\t\t\tout += Mv::to(y + (single_graph or not Config::getB(\"cpu_invert_lower\") ? 1 : height - 2), x + 2)\n\t\t\t\t\t+ Theme::c(\"graph_text\") + \"up\" + Mv::r(1) + upstr;\n\t\t\t}\n\n\t\t#ifdef __linux__\n\t\t\tconst bool freq_range = Config::getS(\"freq_mode\") == \"range\";\n\t\t#else\n\t\t\tconst bool freq_range = false;\n\t\t#endif\n\n\t\t\t//? Cpu clock and cpu meter\n\t\t\tif (Config::getB(\"show_cpu_freq\") and not cpuHz.empty())\n\t\t\t\tout += Mv::to(b_y, b_x + b_width - (freq_range ? 20 : 10)) + Fx::ub + Theme::c(\"div_line\")\n\t\t\t\t\t+ Symbols::h_line * ((freq_range ? 17 : 7) - cpuHz.size())\n\t\t\t\t\t+ Symbols::title_left + Fx::b + Theme::c(\"title\") + cpuHz + Fx::ub + Theme::c(\"div_line\") + Symbols::title_right;\n\n\t\tout += Mv::to(b_y + 1, b_x + 1) + Theme::c(\"main_fg\") + Fx::b + \"CPU \" + cpu_meter(safeVal(cpu.cpu_percent, \"total\"s).back())\n\t\t\t+ Theme::g(\"cpu\").at(clamp(safeVal(cpu.cpu_percent, \"total\"s).back(), 0ll, 100ll)) + rjust(to_string(safeVal(cpu.cpu_percent, \"total\"s).back()), 4) + Theme::c(\"main_fg\") + '%';\n\t\tif (show_temps) {\n\t\t\tconst auto [temp, unit] = celsius_to(safeVal(cpu.temp, 0).back(), temp_scale);\n\t\t\tconst auto temp_color = Theme::g(\"temp\").at(clamp(safeVal(cpu.temp, 0).back() * 100 / cpu.temp_max, 0ll, 100ll));\n\t\t\tif ((b_column_size > 1 or b_columns > 1) and temp_graphs.size() >= 1ll)\n\t\t\t\tout += ' ' + Theme::c(\"inactive_fg\") + graph_bg * 5 + Mv::l(5) + temp_color\n\t\t\t\t\t+ temp_graphs.at(0)(safeVal(cpu.temp, 0), data_same or redraw);\n\t\t\tout += rjust(to_string(temp), 4) + Theme::c(\"main_fg\") + unit;\n\t\t}\n\n\t\tif (show_watts) {\n\t\t\tstring cwatts = fmt::format(\" {:>4.{}f}\", cpu.usage_watts, cpu.usage_watts < 10.0f ? 2 : cpu.usage_watts < 100.0f ? 1 : 0);\n\t\t\tstring cwatts_post = \"W\";\n\n\t\t\tmax_observed_pwr = max(max_observed_pwr, cpu.usage_watts);\n\t\t\tout += Theme::g(\"cached\").at(clamp(cpu.usage_watts / max_observed_pwr * 100.0f, 0.0f, 100.0f)) + cwatts + Theme::c(\"main_fg\") + cwatts_post; \n\t\t}\n\n\t\t\tout += Theme::c(\"div_line\") + Symbols::v_line;\n\t\t} catch (const std::exception& e) {\n\t\t\tthrow std::runtime_error(\"graphs, clock, meter : \" + string{e.what()});\n\t\t}\n\n\t\tint max_row = b_height - 3; // Subtracting one extra row for the load average (and power if enabled)\n\t\tint n_gpus_to_show = 0;\n\t#ifdef GPU_SUPPORT\n\t\tn_gpus_to_show = show_gpu ? (gpus.size() - (gpu_always ? 0 : Gpu::shown)) : 0;\n\t#endif\n\t\tmax_row -= n_gpus_to_show;\n\n\t\tauto is_cpu_enabled = [&cpu](const std::int32_t num) -> bool {\n\t\t\treturn !cpu.active_cpus.has_value() || std::ranges::find(cpu.active_cpus.value(), num) != cpu.active_cpus.value().end();\n\t\t};\n\n\t\t//? Core text and graphs\n\t\tint cx = 0, cy = 1, cc = 0, core_width = (b_column_size == 0 ? 2 : 3);\n\t\tif (Shared::coreCount >= 100) core_width++;\n\t\tfor (const auto& n : iota(0, Shared::coreCount)) {\n\t\t\tauto enabled = is_cpu_enabled(n);\n\t\t\tout += Mv::to(b_y + cy + 1, b_x + cx + 1) + Theme::c(enabled ? \"main_fg\" : \"inactive_fg\") + (Shared::coreCount < 100 ? Fx::b + 'C' + Fx::ub : \"\")\n\t\t\t\t+ ljust(to_string(n), core_width);\n\t\t\tif ((b_column_size > 0 or extra_width > 0) and cmp_less(n, core_graphs.size()))\n\t\t\t\tout += Theme::c(\"inactive_fg\") + graph_bg * (5 * b_column_size + extra_width) + Mv::l(5 * b_column_size + extra_width)\n\t\t\t\t\t+ core_graphs.at(n)(safeVal(cpu.core_percent, n), data_same or redraw);\n\n\t\t\tout += enabled ? Theme::g(\"cpu\").at(clamp(safeVal(cpu.core_percent, n).back(), 0ll, 100ll)) : Theme::c(\"inactive_fg\");\n\t\t\tout += rjust(to_string(safeVal(cpu.core_percent, n).back()), (b_column_size < 2 ? 3 : 4)) + Theme::c(enabled ? \"main_fg\" : \"inactive_fg\") + '%';\n\n\t\t\tif (show_temps and not hide_cores) {\n\t\t\t\tconst auto core_temps = safeVal(cpu.temp, n + 1);\n\t\t\t\tif (!core_temps.empty()) {\n\t\t\t\t\t// FIXME: This should be checked during collection and just not be made available with\n\t\t\t\t\t// something like `std::nullopt`.\n\t\t\t\t\tconst auto last_temp = core_temps.back();\n\t\t\t\t\tconst auto [temp, unit] = celsius_to(last_temp, temp_scale);\n\t\t\t\t\tconst auto temp_color = enabled ? Theme::g(\"temp\").at(clamp(last_temp * 100 / cpu.temp_max, 0ll, 100ll)) : Theme::c(\"inactive_fg\");\n\t\t\t\t\tif (b_column_size > 1 and std::cmp_greater_equal(temp_graphs.size(), n)) {\n\t\t\t\t\t\tfmt::format_to(\n\t\t\t\t\t\t\tstd::back_inserter(out),\n\t\t\t\t\t\t\t\" {}{}{}{}\", Theme::c(\"inactive_fg\"),\n\t\t\t\t\t\t\tgraph_bg * 5, Mv::l(5),\n\t\t\t\t\t\t\ttemp_graphs.at(n + 1)(core_temps, data_same || redraw)\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tfmt::format_to(\n\t\t\t\t\t\tstd::back_inserter(out),\n\t\t\t\t\t\t\"{}{}{}{}\",\n\t\t\t\t\t\ttemp_color,\n\t\t\t\t\t\trjust(std::to_string(temp), 4),\n\t\t\t\t\t\tTheme::c(enabled ? \"main_fg\" : \"inactive_fg\"),\n\t\t\t\t\t\tunit\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tout += Theme::c(\"div_line\") + Symbols::v_line;\n\n\t\t\tif ((++cy > ceil((double)Shared::coreCount / b_columns) or cy == max_row) and n != Shared::coreCount - 1) {\n\t\t\t\tif (++cc >= b_columns) break;\n\t\t\t\tcy = 1; cx = (b_width / b_columns) * cc;\n\t\t\t}\n\t\t}\n\n\t\t//? Load average\n\t\tif (cy < b_height - 1 and cc <= b_columns) {\n\t\t\tcy = b_height - 2 - n_gpus_to_show;\n\n\t\t\tstring load_avg_pre = \"Load avg:\";\n\t\t\tstring load_avg;\n\n\t\t\tfor (const auto& val : cpu.load_avg) {\n\t\t\t\tload_avg += fmt::format(\" {:.2f}\", val);\n\t\t\t}\n\n\t\t\tint len = load_avg_pre.size() + load_avg.size();\n\t\t\tout += Mv::to(b_y + cy, b_x + 1) + string(max(b_width - len - 2, 0), ' ') + Theme::c(\"main_fg\") + Fx::b + load_avg_pre + Fx::ub + load_avg;\n\t\t}\n\n\t#ifdef GPU_SUPPORT\n\t\t//? Gpu brief info\n\t\tif (show_gpu) {\n\t\t\tfor (unsigned long i = 0; i < gpus.size(); ++i) {\n\t\t\t\tif (gpu_auto and v_contains(Gpu::shown_panels, i))\n\t\t\t\t\tcontinue;\n\t\t\t\tout += Mv::to(b_y + ++cy, b_x + 1) + Theme::c(\"main_fg\") + Fx::b + \"GPU\";\n\t\t\t\tif (gpus.size() > 1) out += rjust(to_string(i), 1 + (gpus.size() > 9));\n\t\t\t\tif (gpus[i].supported_functions.gpu_utilization) {\n\t\t\t\t\tout += ' ';\n\t\t\t\t\tif (b_columns > 1) {\n\t\t\t\t\tout += gpu_meters[i](safeVal(gpus[i].gpu_percent, \"gpu-totals\"s).back())\n\t\t\t\t\t\t+ Theme::g(\"cpu\").at(clamp(safeVal(gpus[i].gpu_percent, \"gpu-totals\"s).back(), 0ll, 100ll));\n\t\t\t\t\t}\n\t\t\t\t\tout += rjust(to_string(safeVal(gpus[i].gpu_percent, \"gpu-totals\"s).back()), 3) + Theme::c(\"main_fg\") + '%';\n\t\t\t\t\tif (b_columns == 1)\n\t\t\t\t\t\tout += ' ';\n\t\t\t\t}\n\t\t\t\tif (gpus[i].supported_functions.mem_used and gpus[i].supported_functions.mem_total and b_columns > 1) {\n\t\t\t\t\tout += ' ' + Theme::c(\"inactive_fg\") + graph_bg * 5 + Mv::l(5) + Theme::g(\"used\").at(safeVal(gpus[i].gpu_percent, \"gpu-vram-totals\"s).back())\n\t\t\t\t\t\t+ gpu_mem_graphs[i](safeVal(gpus[i].gpu_percent, \"gpu-vram-totals\"s), data_same or redraw);\n\t\t\t\t}\n\t\t\t\tif (gpus[i].supported_functions.mem_used) {\n\t\t\t\t\t\tout += Theme::c(\"main_fg\")\n\t\t\t\t\t\t+ rjust(floating_humanizer(gpus[i].mem_used, true), 5);\n\t\t\t\t}\n\t\t\t\tif (gpus[i].supported_functions.mem_total) {\n\t\t\t\t\t\tout += Theme::c(\"inactive_fg\") + '/' + Theme::c(\"main_fg\") + ljust(floating_humanizer(gpus[i].mem_total, true), 4);\n\t\t\t\t}\n\t\t\t\tif (show_temps and gpus[i].supported_functions.temp_info) {\n\t\t\t\t\tconst auto [temp, unit] = celsius_to(gpus[i].temp.back(), temp_scale);\n\t\t\t\t\tout += ' ';\n\t\t\t\t\tif (b_columns > 1)\n\t\t\t\t\t\tout += Theme::c(\"inactive_fg\") + graph_bg * 5 + Mv::l(5) + Theme::g(\"temp\").at(clamp(gpus[i].temp.back() * 100 / gpus[i].temp_max, 0ll, 100ll))\n\t\t\t\t\t\t\t+ gpu_temp_graphs[i](gpus[i].temp, data_same or redraw);\n\t\t\t\t\telse out += Theme::g(\"temp\").at(clamp(gpus[i].temp.back() * 100 / gpus[i].temp_max, 0ll, 100ll));\n\t\t\t\t\tout += rjust(to_string(temp), 3) + Theme::c(\"main_fg\") + unit;\n\t\t\t\t}\n\t\t\t\tif (gpus[i].supported_functions.pwr_usage) {\n\t\t\t\t\tout += ' ' + Theme::g(\"cached\").at(clamp(safeVal(gpus[i].gpu_percent, \"gpu-pwr-totals\"s).back(), 0ll, 100ll))\n\t\t\t\t\t\t+ fmt::format(\"{:>4.{}f}\", gpus[i].pwr_usage / 1000.0, gpus[i].pwr_usage < 10'000 ? 2 : gpus[i].pwr_usage < 100'000 ? 1 : 0) + Theme::c(\"main_fg\") + 'W';\n\t\t\t\t}\n\n\t\t\t\tif (cy > b_height - 1) break;\n\t\t\t}\n\t\t}\n\t#endif\n\n\t\tredraw = false;\n\t\treturn out + Fx::reset;\n\t}\n\n}\n\n#ifdef GPU_SUPPORT\nnamespace Gpu {\n\tint width_p = 100, height_p = 32;\n\tint min_width = 41, min_height = 8;\n\tint width = 41, total_height;\n\tvector<int> x_vec = {}, y_vec = {}, b_height_vec = {};\n\tint b_width;\n\tvector<int> b_x_vec = {}, b_y_vec = {};\n\tvector<bool> redraw = {};\n\tint shown = 0;\n\tint count = 0;\n\tvector<int> shown_panels = {};\n\tint graph_up_height;\n\tvector<Draw::Graph> graph_upper_vec = {}, graph_lower_vec = {};\n\tvector<Draw::Graph> temp_graph_vec = {};\n\tvector<Draw::Graph> mem_used_graph_vec = {}, mem_util_graph_vec = {};\n\tvector<Draw::Meter> gpu_meter_vec = {};\n\tvector<Draw::Meter> pwr_meter_vec = {};\n\tvector<Draw::Meter> enc_meter_vec = {};\n\tvector<string> box = {};\n\n    string draw(const gpu_info& gpu, unsigned long index, bool force_redraw, bool data_same) {\n\t\tif (Runner::stopping) return \"\";\n\n\t\tauto& b_x = b_x_vec[index];\n\t\tauto& b_y = b_y_vec[index];\n\t\tauto& x = x_vec[index];\n\t\tauto& y = y_vec[index];\n\n\t\tauto& graph_upper = graph_upper_vec[index];\n\t\tauto& graph_lower = graph_lower_vec[index];\n\t\tauto& temp_graph = temp_graph_vec[index];\n\t\tauto& mem_used_graph = mem_used_graph_vec[index];\n\t\tauto& mem_util_graph = mem_util_graph_vec[index];\n\t\tauto& gpu_meter = gpu_meter_vec[index];\n\t\tauto& pwr_meter = pwr_meter_vec[index];\n\t\tauto& enc_meter = enc_meter_vec[index];\n\n\t\tif (force_redraw) redraw[index] = true;\n        bool show_temps = gpu.supported_functions.temp_info and (Config::getB(\"check_temp\"));\n        auto tty_mode = Config::getB(\"tty_mode\");\n\t\tauto& temp_scale = Config::getS(\"temp_scale\");\n\t\tauto& graph_symbol = (tty_mode ? \"tty\" : Config::getS(\"graph_symbol_gpu\"));\n\t\tauto& graph_bg = Symbols::graph_symbols.at((graph_symbol == \"default\" ? Config::getS(\"graph_symbol\") + \"_up\" : graph_symbol + \"_up\")).at(6);\n        auto single_graph = !Config::getB(\"gpu_mirror_graph\");\n\t\tstring out;\n\t\tint height = gpu_b_height_offsets[index] + 4;\n\t\tout.reserve(width * height);\n\n\t\t//* Redraw elements not needed to be updated every cycle\n\t\tif (redraw[index]) {\n\t\t\tout += box[index];\n\n\t\t\tgraph_up_height = single_graph ? b_height_vec[index] : (b_height_vec[index] + 1) / 2;\n\t\t\tint graph_low_height = single_graph ? 0 : b_height_vec[index] - graph_up_height;\n\n\t\t\tif (gpu.supported_functions.gpu_utilization) {\n\t\t\t\tgraph_upper = Draw::Graph{x + width - b_width - 3, graph_up_height, \"cpu\", safeVal(gpu.gpu_percent, \"gpu-totals\"s), graph_symbol, false, true}; // TODO cpu -> gpu\n            \tif (not single_graph) {\n                \tgraph_lower = Draw::Graph{\n                    \tx + width - b_width - 3,\n                    \tgraph_low_height, \"cpu\",\n                    \tsafeVal(gpu.gpu_percent, \"gpu-totals\"s),\n                    \tgraph_symbol,\n                    \tConfig::getB(\"cpu_invert_lower\"), true\n                \t};\n            \t}\n\t\t\t\tgpu_meter = Draw::Meter{b_width - (show_temps ? 25 : 12), \"cpu\"};\n\t\t\t}\n\t\t\tif (gpu.supported_functions.temp_info)\n\t\t\t\ttemp_graph = Draw::Graph{6, 1, \"temp\", gpu.temp, graph_symbol, false, false, gpu.temp_max, -23};\n\t\t\tif (gpu.supported_functions.pwr_usage)\n\t\t\t\tpwr_meter = Draw::Meter{b_width - (gpu.supported_functions.pwr_state and gpu.pwr_state != 32 ? 25 : 12), \"cached\"};\n\t\t\tif (gpu.supported_functions.mem_utilization)\n\t\t\t\tmem_util_graph = Draw::Graph{b_width/2 - 1, 2, \"free\", gpu.mem_utilization_percent, graph_symbol, 0, 0, 100, 4}; // offset so the graph isn't empty at 0-5% utilization\n\t\t\tif (gpu.supported_functions.mem_used and gpu.supported_functions.mem_total)\n\t\t\t\tmem_used_graph = Draw::Graph{b_width/2 - 2, 2 + 2*(gpu.supported_functions.mem_utilization), \"used\", safeVal(gpu.gpu_percent, \"gpu-vram-totals\"s), graph_symbol};\n\t\t\tif (gpu.supported_functions.encoder_utilization)\n\t\t\t\tenc_meter = Draw::Meter{b_width/2 - 10, \"cpu\"};\n\t\t}\n\n\n\t\t//* General GPU info\n\t\tint rows_used = 1;\n\t\t//? Gpu graph, meter & clock speed\n\t\tif (gpu.supported_functions.gpu_utilization) {\n\t\t\tout += Fx::ub + Mv::to(y + rows_used, x + 1) + graph_upper(safeVal(gpu.gpu_percent, \"gpu-totals\"s), (data_same or redraw[index]));\n\t\t\tif (not single_graph)\n\t\t\t\tout += Mv::to(y + rows_used + graph_up_height, x + 1) + graph_lower(safeVal(gpu.gpu_percent, \"gpu-totals\"s), (data_same or redraw[index]));\n\n\t\t\tout += Mv::to(b_y + rows_used, b_x + 1) + Theme::c(\"main_fg\") + Fx::b + \"GPU \" + gpu_meter(safeVal(gpu.gpu_percent, \"gpu-totals\"s).back())\n\t\t\t\t+ Theme::g(\"cpu\").at(clamp(safeVal(gpu.gpu_percent, \"gpu-totals\"s).back(), 0ll, 100ll)) + rjust(to_string(safeVal(gpu.gpu_percent, \"gpu-totals\"s).back()), 5) + Theme::c(\"main_fg\") + '%';\n\n\t\t\t//? Temperature graph, I assume the device supports utilization if it supports temperature\n\t\t\tif (show_temps) {\n\t\t\t\tconst auto [temp, unit] = celsius_to(gpu.temp.back(), temp_scale);\n\t\t\t\tout += ' ' + Theme::c(\"inactive_fg\") + graph_bg * 6 + Mv::l(6) + Theme::g(\"temp\").at(clamp(gpu.temp.back() * 100 / gpu.temp_max, 0ll, 100ll))\n\t\t\t\t\t+ temp_graph(gpu.temp, data_same or redraw[index]);\n\t\t\t\tout += rjust(to_string(temp), 4) + Theme::c(\"main_fg\") + unit;\n\t\t\t}\n\t\t\tout += Theme::c(\"div_line\") + Symbols::v_line;\n\t\t\trows_used++;\n\t\t}\n\n\t\tif (gpu.supported_functions.gpu_clock) {\n\t\t\tstring clock_speed_string = to_string(gpu.gpu_clock_speed);\n\t\t\tout += Mv::to(b_y, b_x + b_width - 12) + Theme::c(\"div_line\") + Symbols::h_line*(5-clock_speed_string.size())\n\t\t\t\t+ Symbols::title_left + Fx::b + Theme::c(\"title\") + clock_speed_string + \" MHz\" + Fx::ub + Theme::c(\"div_line\") + Symbols::title_right;\n\t\t}\n\n\t\t//? Power usage meter, power state\n\t\tif (gpu.supported_functions.pwr_usage) {\n\t\t\tout += Mv::to(b_y + rows_used, b_x + 1) + Theme::c(\"main_fg\") + Fx::b + \"PWR \" + pwr_meter(safeVal(gpu.gpu_percent, \"gpu-pwr-totals\"s).back())\n\t\t\t\t+ Theme::g(\"cached\").at(clamp(safeVal(gpu.gpu_percent, \"gpu-pwr-totals\"s).back(), 0ll, 100ll))\n\t\t\t\t+ fmt::format(\"{:>5.{}f}\", gpu.pwr_usage / 1000.0, gpu.pwr_usage < 10'000 ? 2 : gpu.pwr_usage < 100'000 ? 1 : 0) + Theme::c(\"main_fg\") + 'W';\n\t\t\tif (gpu.supported_functions.pwr_state and gpu.pwr_state != 32) // NVML_PSTATE_UNKNOWN; unsupported or non-nvidia card\n\t\t\t\tout += std::string(\" P-state: \") + (gpu.pwr_state > 9 ? \"\" : \" \") + 'P' + Theme::g(\"cached\").at(clamp(gpu.pwr_state, 0ll, 100ll)) + to_string(gpu.pwr_state);\n\t\t\trows_used++;\n\t\t}\n\n\t\t//? Encode and Decode meters\n\t\tbool drawnEncDec = gpu.supported_functions.encoder_utilization and gpu.supported_functions.decoder_utilization;\n\t\tif (drawnEncDec) {\n\t\t\tout += Mv::to(b_y + rows_used, b_x +1) + Theme::c(\"main_fg\") + Fx::b + \"ENC \" + enc_meter(gpu.encoder_utilization)\n\t\t\t\t+ Theme::g(\"cpu\").at(clamp(gpu.encoder_utilization, 0ll, 100ll)) + rjust(to_string(gpu.encoder_utilization), 4) + Theme::c(\"main_fg\") + '%'\n\t\t\t\t+ Theme::c(\"div_line\") + Symbols::v_line + Theme::c(\"main_fg\") + Fx::b + \"DEC \" + enc_meter(gpu.decoder_utilization)\n\t\t\t\t+ Theme::g(\"cpu\").at(clamp(gpu.decoder_utilization, 0ll, 100ll)) + rjust(to_string(gpu.decoder_utilization), 4) + Theme::c(\"main_fg\") + '%';\n\t\t\trows_used++;\n\t\t}\n\n\t\tif (gpu.supported_functions.mem_total or gpu.supported_functions.mem_used) {\n\t\t\tout += Mv::to(b_y + rows_used, b_x);\n\t\t\tif (gpu.supported_functions.mem_total and gpu.supported_functions.mem_used) {\n\t\t\t\tstring used_memory_string = floating_humanizer(gpu.mem_used);\n\n\t\t\t\tauto offset = (gpu.supported_functions.mem_total or gpu.supported_functions.mem_used)\n\t\t\t\t\t* (1 + 2*(gpu.supported_functions.mem_total and gpu.supported_functions.mem_used) + 2*gpu.supported_functions.mem_utilization);\n\n\t\t\t\t//? Used graph, memory section header, total vram\n\t\t\t\tout += Theme::c(\"div_line\") + Symbols::div_left + Symbols::h_line + Symbols::title_left + Fx::b + Theme::c(\"title\") + \"vram\" + Theme::c(\"div_line\") + Fx::ub + Symbols::title_right\n\t\t\t\t\t+  Symbols::h_line*(b_width/2-8) + Symbols::div_up + Mv::d(offset)+Mv::l(1) + Symbols::div_down + Mv::l(1)+Mv::u(1) + (Symbols::v_line + Mv::l(1)+Mv::u(1))*(offset-1) + Symbols::div_up\n\t\t\t\t\t+  Symbols::h_line + Theme::c(\"title\") + \"Used:\" + Theme::c(\"div_line\")\n\t\t\t\t\t+  Symbols::h_line*(b_width/2+b_width%2-9-used_memory_string.size()) + Theme::c(\"title\") + used_memory_string + Theme::c(\"div_line\") + Symbols::h_line + Symbols::div_right\n\t\t\t\t\t+  Mv::d(1) + Mv::l(b_width/2-1) + mem_used_graph(safeVal(gpu.gpu_percent, \"gpu-vram-totals\"s), (data_same or redraw[index]))\n\t\t\t\t\t+  Mv::l(b_width-3) + Mv::u(1+2*gpu.supported_functions.mem_utilization) + Theme::c(\"main_fg\") + Fx::b + \"Total:\" + rjust(floating_humanizer(gpu.mem_total), b_width/2-9) + Fx::ub\n\t\t\t\t\t+  Mv::r(3) + rjust(to_string(safeVal(gpu.gpu_percent, \"gpu-vram-totals\"s).back()), 3) + '%';\n\n\t\t\t\t//? Memory utilization\n\t\t\t\tif (gpu.supported_functions.mem_utilization)\n\t\t\t\t\tout += Mv::l(b_width/2+6) + Mv::d(1) + Theme::c(\"div_line\") + Symbols::div_left+Symbols::h_line + Theme::c(\"title\") + \"Utilization:\" + Theme::c(\"div_line\") + Symbols::h_line*(b_width/2-14) + Symbols::div_right\n\t\t\t\t\t\t+  Mv::l(b_width/2)   + Mv::d(1) + mem_util_graph(gpu.mem_utilization_percent, (data_same or redraw[index]))\n\t\t\t\t\t\t+  Mv::l(b_width/2-1) + Mv::u(1) + rjust(to_string(gpu.mem_utilization_percent.back()), 3) + '%';\n\n\t\t\t\t//? Memory clock speed\n\t\t\t\tif (gpu.supported_functions.mem_clock) {\n\t\t\t\t\tstring clock_speed_string = to_string(gpu.mem_clock_speed);\n\t\t\t\t\tout += Mv::to(b_y + rows_used, b_x + b_width/2 - 11) + Theme::c(\"div_line\") + Symbols::h_line*(5-clock_speed_string.size())\n\t\t\t\t\t\t+ Symbols::title_left + Fx::b + Theme::c(\"title\") + clock_speed_string + \" MHz\" + Fx::ub + Theme::c(\"div_line\") + Symbols::title_right;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tout += Theme::c(\"main_fg\") + Mv::r(1);\n\t\t\t\tif (gpu.supported_functions.mem_total)\n\t\t\t\t\tout += \"VRAM total:\" + rjust(floating_humanizer(gpu.mem_total), b_width/(1 + gpu.supported_functions.mem_clock)-14);\n\t\t\t\telse out += \"VRAM usage:\" + rjust(floating_humanizer(gpu.mem_used), b_width/(1 + gpu.supported_functions.mem_clock)-14);\n\n\t\t\t\tif (gpu.supported_functions.mem_clock)\n\t\t\t\t\tout += \"   VRAM clock:\" + rjust(to_string(gpu.mem_clock_speed) + \" MHz\", b_width/2-13);\n\t\t\t}\n\t\t}\n\n\t\t//? Processes section header\n\t\t//out += Mv::to(b_y+8, b_x) + Theme::c(\"div_line\") + Symbols::div_left + Symbols::h_line + Symbols::title_left + Theme::c(\"main_fg\") + Fx::b + \"gpu-proc\" + Fx::ub + Theme::c(\"div_line\")\n\t\t//\t+ Symbols::title_right + Symbols::h_line*(b_width/2-12) + Symbols::div_down + Symbols::h_line*(b_width/2-2) + Symbols::div_right;\n\n\t\t//? PCIe link throughput\n\t\t// Negative RX/TX means that they are manually disabled, not that they are unsupported\n\t\tif (gpu.supported_functions.pcie_txrx and not (gpu.pcie_rx < 0 or gpu.pcie_tx < 0)) {\n\t\t\tstring tx_string = floating_humanizer(gpu.pcie_tx, 0, 1, 0, 1);\n\t\t\tstring rx_string = floating_humanizer(gpu.pcie_rx, 0, 1, 0, 1);\n\t\t\tout += Mv::to(b_y + height - 3, b_x+2) + Theme::c(\"div_line\")\n\t\t\t\t+ Symbols::title_left_down + Theme::c(\"title\") + Fx::b + \"TX:\" + Fx::ub + Theme::c(\"div_line\") + Symbols::title_right_down + Symbols::h_line*(b_width/2-9-tx_string.size())\n\t\t\t\t+ Symbols::title_left_down + Theme::c(\"title\") + Fx::b + tx_string + Fx::ub + Theme::c(\"div_line\") + Symbols::title_right_down + (gpu.supported_functions.mem_total and gpu.supported_functions.mem_used ? Symbols::div_down : Symbols::h_line)\n\t\t\t\t+ Symbols::title_left_down + Theme::c(\"title\") + Fx::b + \"RX:\" + Fx::ub + Theme::c(\"div_line\") + Symbols::title_right_down + Symbols::h_line*(b_width/2+b_width%2-9-rx_string.size())\n\t\t\t\t+ Symbols::title_left_down + Theme::c(\"title\") + Fx::b + rx_string + Fx::ub + Theme::c(\"div_line\") + Symbols::title_right_down + Symbols::round_right_down;\n\t\t}\n\n\t\tredraw[index] = false;\n\t\treturn out + Fx::reset;\n\t}\n\n}\n#endif\n\nnamespace Mem {\n\tint width_p = 45, height_p = 40;\n\tint min_width = 36, min_height = 10;\n\tint x = 1, y, width = 20, height;\n\tint mem_width, disks_width, divider, item_height, mem_size, mem_meter, graph_height, disk_meter;\n\tint disks_io_h = 0;\n\tint disks_io_half = 0;\n\tbool shown = true, redraw = true;\n\tstring box;\n\tstd::unordered_map<string, Draw::Meter> mem_meters;\n\tstd::unordered_map<string, Draw::Graph> mem_graphs;\n\tstd::unordered_map<string, Draw::Meter> disk_meters_used;\n\tstd::unordered_map<string, Draw::Meter> disk_meters_free;\n\tstd::unordered_map<string, Draw::Graph> io_graphs;\n\n\tstring draw(const mem_info& mem, bool force_redraw, bool data_same) {\n\t\tif (Runner::stopping) return \"\";\n\t\tif (force_redraw) redraw = true;\n\t\tauto show_swap = Config::getB(\"show_swap\");\n\t\tauto swap_disk = Config::getB(\"swap_disk\");\n\t\tauto show_disks = Config::getB(\"show_disks\");\n\t\tauto show_io_stat = Config::getB(\"show_io_stat\");\n\t\tauto io_mode = Config::getB(\"io_mode\");\n\t\tauto io_graph_combined = Config::getB(\"io_graph_combined\");\n\t\tauto use_graphs = Config::getB(\"mem_graphs\");\n\t\tauto tty_mode = Config::getB(\"tty_mode\");\n\t\tauto& graph_symbol = (tty_mode ? \"tty\" : Config::getS(\"graph_symbol_mem\"));\n\t\tauto& graph_bg = Symbols::graph_symbols.at((graph_symbol == \"default\" ? Config::getS(\"graph_symbol\") + \"_up\" : graph_symbol + \"_up\")).at(6);\n\t\tauto totalMem = Mem::get_totalMem();\n\t\tstring out;\n\t\tout.reserve(height * width);\n\n\t\t//* Redraw elements not needed to be updated every cycle\n\t\tif (redraw) {\n\t\t\tout += box;\n\t\t\tmem_meters.clear();\n\t\t\tmem_graphs.clear();\n\t\t\tdisk_meters_free.clear();\n\t\t\tdisk_meters_used.clear();\n\t\t\tio_graphs.clear();\n\n\t\t\t//? Mem graphs and meters\n\t\t\tfor (const auto& name : mem_names) {\n\n\t\t\t\tif (use_graphs)\n\t\t\t\t\tmem_graphs[name] = Draw::Graph{mem_meter, graph_height, name, safeVal(mem.percent, name), graph_symbol};\n\t\t\t\telse\n\t\t\t\t\tmem_meters[name] = Draw::Meter{mem_meter, name};\n\t\t\t}\n\t\t\tif (show_swap and has_swap) {\n\t\t\t\tfor (const auto& name : swap_names) {\n\t\t\t\t\tif (use_graphs)\n\t\t\t\t\t\tmem_graphs[name] = Draw::Graph{mem_meter, graph_height, name.substr(5), safeVal(mem.percent, name), graph_symbol};\n\t\t\t\t\telse\n\t\t\t\t\t\tmem_meters[name] = Draw::Meter{mem_meter, name.substr(5)};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Disk meters and io graphs\n\t\t\tif (show_disks) {\n\t\t\t\tif (show_io_stat or io_mode) {\n\t\t\t\t\tstd::unordered_map<string, int> custom_speeds;\n\t\t\t\t\tint half_height = 0;\n\t\t\t\t\tif (io_mode) {\n\t\t\t\t\t\tdisks_io_h = max((int)floor((double)(height - 2 - (disk_ios * 2)) / max(1, disk_ios)), (io_graph_combined ? 1 : 2));\n\t\t\t\t\t\thalf_height = ceil((double)disks_io_h / 2);\n\n\t\t\t\t\t\tif (not Config::getS(\"io_graph_speeds\").empty()) {\n\t\t\t\t\t\t\tauto split = ssplit(Config::getS(\"io_graph_speeds\"));\n\t\t\t\t\t\t\tfor (const auto& entry : split) {\n\t\t\t\t\t\t\t\tauto vals = ssplit(entry, ':');\n\t\t\t\t\t\t\t\tif (vals.size() == 2 and mem.disks.contains(vals.at(0)) and isint(vals.at(1)))\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tcustom_speeds[vals.at(0)] = std::stoi(vals.at(1));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (const std::out_of_range&) { continue; }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (const auto& [name, disk] : mem.disks) {\n\t\t\t\t\t\tif (disk.io_read.empty()) continue;\n\n\t\t\t\t\t\tio_graphs[name + \"_activity\"] = Draw::Graph{disks_width - 6, 1, \"available\", disk.io_activity, graph_symbol};\n\n\t\t\t\t\t\tif (io_mode) {\n\t\t\t\t\t\t\t//? Create one combined graph for IO read/write if enabled\n\t\t\t\t\t\t\tlong long speed = (custom_speeds.contains(name) ? custom_speeds.at(name) : 100) << 20;\n\t\t\t\t\t\t\tif (io_graph_combined) {\n\t\t\t\t\t\t\t\tdeque<long long> combined(disk.io_read.size(), 0);\n\t\t\t\t\t\t\t\trng::transform(disk.io_read, disk.io_write, combined.begin(), std::plus<long long>());\n\t\t\t\t\t\t\t\tio_graphs[name] = Draw::Graph{\n\t\t\t\t\t\t\t\t\tdisks_width, disks_io_h, \"available\", combined,\n\t\t\t\t\t\t\t\t\tgraph_symbol, false, true, speed};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tio_graphs[name + \"_read\"] = Draw::Graph{\n\t\t\t\t\t\t\t\t\tdisks_width, half_height, \"free\",\n\t\t\t\t\t\t\t\t\tdisk.io_read, graph_symbol, false,\n\t\t\t\t\t\t\t\t\ttrue, speed};\n\t\t\t\t\t\t\t\tio_graphs[name + \"_write\"] = Draw::Graph{\n\t\t\t\t\t\t\t\t\tdisks_width, disks_io_h - half_height,\n\t\t\t\t\t\t\t\t\t\"used\", disk.io_write, graph_symbol,\n\t\t\t\t\t\t\t\t\ttrue, true, speed};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (int i = 0; const auto& [name, ignored] : mem.disks) {\n\t\t\t\t\tif (i * 2 > height - 2) break;\n\t\t\t\t\tdisk_meters_used[name] = Draw::Meter{disk_meter, \"used\"};\n\t\t\t\t\tif (cmp_less_equal(mem.disks.size() * 3, height - 1))\n\t\t\t\t\t\tdisk_meters_free[name] = Draw::Meter{disk_meter, \"free\"};\n\t\t\t\t}\n\n\t\t\t\tout += Mv::to(y, x + width - 6) + Fx::ub + Theme::c(\"mem_box\") + Symbols::title_left + (io_mode ? Fx::b : \"\") + Theme::c(\"hi_fg\")\n\t\t\t\t+ 'i' + Theme::c(\"title\") + 'o' + Fx::ub + Theme::c(\"mem_box\") + Symbols::title_right;\n\t\t\t\tInput::mouse_mappings[\"i\"] = {y, x + width - 5, 1, 2};\n\t\t\t}\n\n\t\t}\n\n\t\t//? Mem and swap\n\t\tint cx = 1, cy = 1;\n\t\tstring divider = (graph_height > 0 ? Mv::l(2) + Theme::c(\"mem_box\") + Symbols::div_left + Theme::c(\"div_line\") + Symbols::h_line * (mem_width - 1)\n\t\t\t\t\t\t+ (show_disks ? \"\" : Theme::c(\"mem_box\")) + Symbols::div_right + Mv::l(mem_width - 1) + Theme::c(\"main_fg\") : \"\");\n\t\tstring up = (graph_height >= 2 ? Mv::l(mem_width - 2) + Mv::u(graph_height - 1) : \"\");\n\t\tbool big_mem = mem_width > 21;\n\n\t\tout += Mv::to(y + 1, x + 2) + Theme::c(\"title\") + Fx::b + \"Total:\" + rjust(floating_humanizer(totalMem), mem_width - 9) + Fx::ub + Theme::c(\"main_fg\");\n\t\tvector<string> comb_names (mem_names.begin(), mem_names.end());\n\t\tif (show_swap and has_swap and not swap_disk) comb_names.insert(comb_names.end(), swap_names.begin(), swap_names.end());\n\t\tfor (const auto& name : comb_names) {\n\t\t\tif (cy > height - 4) break;\n\t\t\tstring title;\n\t\t\tif (name == \"swap_used\") {\n\t\t\t\tif (cy > height - 5) break;\n\t\t\t\tif (height - cy > 6) {\n\t\t\t\t\tif (graph_height > 0) out += Mv::to(y+1+cy, x+1+cx) + divider;\n\t\t\t\t\tcy += 1;\n\t\t\t\t}\n\t\t\t\tout += Mv::to(y+1+cy, x+1+cx) + Theme::c(\"title\") + Fx::b + \"Swap:\" + rjust(floating_humanizer(safeVal(mem.stats, \"swap_total\"s)), mem_width - 8)\n\t\t\t\t\t+ Theme::c(\"main_fg\") + Fx::ub;\n\t\t\t\tcy += 1;\n\t\t\t\ttitle = \"Used\";\n\t\t\t}\n\t\t\telse if (name == \"swap_free\")\n\t\t\t\ttitle = \"Free\";\n\n\t\t\tif (title.empty()) title = capitalize(name);\n\t\t\tconst string humanized = floating_humanizer(safeVal(mem.stats, name));\n\t\t\tconst int offset = max(0, divider.empty() ? 9 - (int)humanized.size() : 0);\n\t\t\tconst string graphics = (\n\t\t\t\tuse_graphs and mem_graphs.contains(name) ? mem_graphs.at(name)(safeVal(mem.percent, name), redraw or data_same)\n\t\t\t\t: mem_meters.contains(name) ? mem_meters.at(name)(safeVal(mem.percent, name).back())\n\t\t\t\t: \"\");\n\t\t\tif (mem_size > 2) {\n\t\t\t\tout += Mv::to(y+1+cy, x+1+cx) + divider + title.substr(0, big_mem ? 10 : 5) + \":\"\n\t\t\t\t\t+ Mv::to(y+1+cy, x+cx + mem_width - 2 - humanized.size()) + (divider.empty() ? Mv::l(offset) + string(\" \") * offset + humanized : trans(humanized))\n\t\t\t\t\t+ Mv::to(y+2+cy, x+cx + (graph_height >= 2 ? 0 : 1)) + graphics + up + rjust(to_string(safeVal(mem.percent, name).back()) + \"%\", 4);\n\t\t\t\tcy += (graph_height == 0 ? 2 : graph_height + 1);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tout += Mv::to(y+1+cy, x+1+cx) + ljust(title, (mem_size > 1 ? 5 : 1)) + (graph_height >= 2 ? \"\" : \" \")\n\t\t\t\t\t+ graphics + Theme::c(\"title\") + rjust(humanized, (mem_size > 1 ? 9 : 7));\n\t\t\t\tcy += (graph_height == 0 ? 1 : graph_height);\n\t\t\t}\n\t\t}\n\t\tif (graph_height > 0 and cy < height - 2)\n\t\t\tout += Mv::to(y+1+cy, x+1+cx) + divider;\n\n\t\t//? Disks\n\t\tif (show_disks) {\n\t\t\tconst auto& disks = mem.disks;\n\t\t\tcx = mem_width; cy = 0;\n\t\t\tbool big_disk = disks_width >= 25;\n\t\t\tdivider = Mv::l(1) + Theme::c(\"div_line\") + Symbols::div_left + Symbols::h_line * disks_width + Theme::c(\"mem_box\") + Fx::ub + Symbols::div_right + Mv::l(disks_width);\n\t\t\tconst string hu_div = Theme::c(\"div_line\") + Symbols::h_line + Theme::c(\"main_fg\");\n\t\t\tif (io_mode) {\n\t\t\t\tfor (const auto& mount : mem.disks_order) {\n\t\t\t\t\tif (not disks.contains(mount)) continue;\n\t\t\t\t\tif (cy > height - 3) break;\n\t\t\t\t\tconst auto disk = safeVal(disks, mount);\n\t\t\t\t\tif (disk.io_read.empty()) continue;\n\t\t\t\t\tconst string total = floating_humanizer(disk.total, not big_disk);\n\t\t\t\t\tout += Mv::to(y+1+cy, x+1+cx) + divider + Theme::c(\"title\") + Fx::b + uresize(disk.name, disks_width - 8) + Mv::to(y+1+cy, x+cx + disks_width - total.size())\n\t\t\t\t\t\t+ trans(total) + Fx::ub;\n\t\t\t\t\tif (big_disk) {\n\t\t\t\t\t\tconst string used_percent = to_string(disk.used_percent);\n\t\t\t\t\t\tout += Mv::to(y+1+cy, x+1+cx + round((double)disks_width / 2) - round((double)used_percent.size() / 2) - 1) + hu_div + used_percent + '%' + hu_div;\n\t\t\t\t\t}\n\t\t\t\t\tif (io_graphs.contains(mount + \"_activity\")) {\n\t\t\t\t\tout += Mv::to(y+2+cy++, x+1+cx) + (big_disk ? \" IO% \" : \" IO   \" + Mv::l(2)) + Theme::c(\"inactive_fg\") + graph_bg * (disks_width - 6)\n\t\t\t\t\t\t+ Mv::l(disks_width - 6) + io_graphs.at(mount + \"_activity\")(disk.io_activity, redraw or data_same) + Theme::c(\"main_fg\");\n\t\t\t\t\t}\n\t\t\t\t\tif (++cy > height - 3) break;\n\t\t\t\t\tif (io_graph_combined) {\n\t\t\t\t\t\tif (not io_graphs.contains(mount)) continue;\n\t\t\t\t\t\tauto comb_val = disk.io_read.back() + disk.io_write.back();\n\t\t\t\t\t\tconst string humanized = (disk.io_write.back() > 0 ? \"▼\"s : \"\"s) + (disk.io_read.back() > 0 ? \"▲\"s : \"\"s)\n\t\t\t\t\t\t\t\t\t\t\t\t+ (comb_val > 0 ? Mv::r(1) + floating_humanizer(comb_val, true) : \"RW\");\n\t\t\t\t\t\tif (disks_io_h == 1) out += Mv::to(y+1+cy, x+1+cx) + string(5, ' ');\n\t\t\t\t\t\tout += Mv::to(y+1+cy, x+1+cx) + io_graphs.at(mount)({comb_val}, redraw or data_same)\n\t\t\t\t\t\t\t+ Mv::to(y+1+cy, x+1+cx) + Theme::c(\"main_fg\") + humanized;\n\t\t\t\t\t\tcy += disks_io_h;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tif (not io_graphs.contains(mount + \"_read\") or not io_graphs.contains(mount + \"_write\")) continue;\n\t\t\t\t\t\tconst string human_read = (disk.io_read.back() > 0 ? \"▲\" + floating_humanizer(disk.io_read.back(), true) : \"R\");\n\t\t\t\t\t\tconst string human_write = (disk.io_write.back() > 0 ? \"▼\" + floating_humanizer(disk.io_write.back(), true) : \"W\");\n\t\t\t\t\t\tif (disks_io_h <= 3) out += Mv::to(y+1+cy, x+1+cx) + string(5, ' ') + Mv::to(y+cy + disks_io_h, x+1+cx) + string(5, ' ');\n\t\t\t\t\t\tout += Mv::to(y+1+cy, x+1+cx) + io_graphs.at(mount + \"_read\")(disk.io_read, redraw or data_same) + Mv::l(disks_width)\n\t\t\t\t\t\t\t+ Mv::d(1) + io_graphs.at(mount + \"_write\")(disk.io_write, redraw or data_same)\n\t\t\t\t\t\t\t+ Mv::to(y+1+cy, x+1+cx) + human_read + Mv::to(y+cy + disks_io_h, x+1+cx) + human_write;\n\t\t\t\t\t\tcy += disks_io_h;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfor (const auto& mount : mem.disks_order) {\n\t\t\t\t\tif (not disks.contains(mount)) continue;\n\t\t\t\t\tif (cy > height - 3) break;\n\t\t\t\t\tconst auto disk = safeVal(disks, mount);\n\t\t\t\t\tif (disk.name.empty() or not disk_meters_used.contains(mount)) continue;\n\t\t\t\t\tauto comb_val = (not disk.io_read.empty() ? disk.io_read.back() + disk.io_write.back() : 0ll);\n\t\t\t\t\tconst string human_io = (comb_val > 0 ? (disk.io_write.back() > 0 and big_disk ? \"▼\"s : \"\"s) + (disk.io_read.back() > 0 and big_disk ? \"▲\"s : \"\"s)\n\t\t\t\t\t\t\t\t\t\t\t+ floating_humanizer(comb_val, true) : \"\");\n\t\t\t\t\tconst string human_total = floating_humanizer(disk.total, not big_disk);\n\t\t\t\t\tconst string human_used = floating_humanizer(disk.used, not big_disk);\n\t\t\t\t\tconst string human_free = floating_humanizer(disk.free, not big_disk);\n\n\t\t\t\t\tout += Mv::to(y+1+cy, x+1+cx) + divider + Theme::c(\"title\") + Fx::b + uresize(disk.name, disks_width - 8) + Mv::to(y+1+cy, x+cx + disks_width - human_total.size())\n\t\t\t\t\t\t+ trans(human_total) + Fx::ub + Theme::c(\"main_fg\");\n\t\t\t\t\tif (big_disk and not human_io.empty())\n\t\t\t\t\t\tout += Mv::to(y+1+cy, x+1+cx + round((double)disks_width / 2) - round((double)human_io.size() / 2) - 1) + hu_div + human_io + hu_div;\n\t\t\t\t\tif (++cy > height - 3) break;\n\t\t\t\t\tif (show_io_stat and io_graphs.contains(mount + \"_activity\")) {\n\t\t\t\t\t\tout += Mv::to(y+1+cy, x+1+cx) + (big_disk ? \" IO% \" : \" IO   \" + Mv::l(2)) + Theme::c(\"inactive_fg\") + graph_bg * (disks_width - 6) + Theme::g(\"available\").at(clamp(disk.io_activity.back(), 50ll, 100ll))\n\t\t\t\t\t\t\t+ Mv::l(disks_width - 6) + io_graphs.at(mount + \"_activity\")(disk.io_activity, redraw or data_same) + Theme::c(\"main_fg\");\n\t\t\t\t\t\tif (not big_disk) out += Mv::to(y+1+cy, x+cx+1) + Theme::c(\"main_fg\") + human_io;\n\t\t\t\t\t\tif (++cy > height - 3) break;\n\t\t\t\t\t}\n\n\t\t\t\t\tout += Mv::to(y+1+cy, x+1+cx) + (big_disk ? \" Used:\" + rjust(to_string(disk.used_percent) + '%', 4) : \"U\") + ' '\n\t\t\t\t\t\t+ disk_meters_used.at(mount)(disk.used_percent) + rjust(human_used, (big_disk ? 9 : 5));\n\t\t\t\t\tif (++cy > height - 3) break;\n\n\t\t\t\t\tif (disk_meters_free.contains(mount) and cmp_less_equal(disks.size() * 3 + (show_io_stat ? disk_ios : 0), height - 1)) {\n\t\t\t\t\t\tout += Mv::to(y+1+cy, x+1+cx) + (big_disk ? \" Free:\" + rjust(to_string(disk.free_percent) + '%', 4) : \"F\") + ' '\n\t\t\t\t\t\t+ disk_meters_free.at(mount)(disk.free_percent) + rjust(human_free, (big_disk ? 9 : 5));\n\t\t\t\t\t\tcy++;\n\t\t\t\t\t\tif (cmp_less_equal(disks.size() * 4 + (show_io_stat ? disk_ios : 0), height - 1)) cy++;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (cy < height - 2) out += Mv::to(y+1+cy, x+1+cx) + divider;\n\t\t}\n\n\t\tredraw = false;\n\t\treturn out + Fx::reset;\n\t}\n\n}\n\nnamespace Net {\n\tint width_p = 45, height_p = 28;\n\tint min_width = 36, min_height = 6;\n\tint x = 1, y, width = 20, height;\n\tint b_x, b_y, b_width, b_height, d_graph_height, u_graph_height;\n\tbool shown = true, redraw = true;\n\tconst int MAX_IFNAMSIZ = 15;\n\tstring old_ip;\n\tstd::unordered_map<string, Draw::Graph> graphs;\n\tstring box;\n\n\tstring draw(const net_info& net, bool force_redraw, bool data_same) {\n\t\tif (Runner::stopping) return \"\";\n\t\tif (force_redraw) redraw = true;\n\t\tauto net_sync = Config::getB(\"net_sync\");\n\t\tauto net_auto = Config::getB(\"net_auto\");\n\t\tauto tty_mode = Config::getB(\"tty_mode\");\n\t\tauto swap_upload_download = Config::getB(\"swap_upload_download\");\n\t\tauto& graph_symbol = (tty_mode ? \"tty\" : Config::getS(\"graph_symbol_net\"));\n\t\tstring ip_addr = (net.ipv4.empty() ? net.ipv6 : net.ipv4);\n\t\tif (old_ip != ip_addr) {\n\t\t\told_ip = ip_addr;\n\t\t\tredraw = true;\n\t\t}\n\t\tstring out;\n\t\tout.reserve(width * height);\n\t\tconst string title_left = Theme::c(\"net_box\") + Fx::ub + Symbols::title_left;\n\t\tconst string title_right = Theme::c(\"net_box\") + Fx::ub + Symbols::title_right;\n\t\tconst int i_size = min((int)selected_iface.size(), MAX_IFNAMSIZ);\n\t\tconst long long down_max = (net_auto ? safeVal(graph_max, \"download\"s) : ((long long)(Config::getI(\"net_download\")) << 20) / 8);\n\t\tconst long long up_max = (net_auto ? safeVal(graph_max, \"upload\"s) : ((long long)(Config::getI(\"net_upload\")) << 20) / 8);\n\n\t\t//* Redraw elements not needed to be updated every cycle\n\t\tif (redraw) {\n\t\t\tout = box;\n\t\t\t//? Graphs\n\t\t\tgraphs.clear();\n\t\t\tif (safeVal(net.bandwidth, \"download\"s).empty() or safeVal(net.bandwidth, \"upload\"s).empty())\n\t\t\t\treturn out + Fx::reset;\n\n\t\t\tgraphs[\"download\"] = Draw::Graph{\n\t\t\t\twidth - b_width - 2, u_graph_height, \"download\",\n\t\t\t\tnet.bandwidth.at(\"download\"), graph_symbol,\n\t\t\t\tswap_upload_download, true, down_max};\n\t\t\tgraphs[\"upload\"] = Draw::Graph{\n\t\t\t\twidth - b_width - 2, d_graph_height, \"upload\",\n\t\t\t\tnet.bandwidth.at(\"upload\"), graph_symbol, !swap_upload_download, true, up_max};\n\n\t\t\t//? Interface selector and buttons\n\n\t\t\tout += Mv::to(y, x+width - i_size - 9) + title_left + Fx::b + Theme::c(\"hi_fg\") + Symbols::left + \"b \" + Theme::c(\"title\")\n\t\t\t\t+ uresize(selected_iface, MAX_IFNAMSIZ) + Theme::c(\"hi_fg\") + \" n\" + Symbols::right + title_right\n\t\t\t\t+ Mv::to(y, x+width - i_size - 15) + title_left + Theme::c(\"hi_fg\") + (safeVal(net.stat, \"download\"s).offset + safeVal(net.stat, \"upload\"s).offset > 0 ? Fx::b : \"\") + 'z'\n\t\t\t\t+ Theme::c(\"title\") + \"ero\" + title_right;\n\t\t\tInput::mouse_mappings[\"b\"] = {y, x+width - i_size - 8, 1, 3};\n\t\t\tInput::mouse_mappings[\"n\"] = {y, x+width - 6, 1, 3};\n\t\t\tInput::mouse_mappings[\"z\"] = {y, x+width - i_size - 14, 1, 4};\n\t\t\tif (width - i_size - 20 > 6) {\n\t\t\t\tout += Mv::to(y, x+width - i_size - 21) + title_left + Theme::c(\"hi_fg\") + (net_auto ? Fx::b : \"\") + 'a' + Theme::c(\"title\") + \"uto\" + title_right;\n\t\t\t\tInput::mouse_mappings[\"a\"] = {y, x+width - i_size - 20, 1, 4};\n\t\t\t}\n\t\t\tif (width - i_size - 20 > 13) {\n\t\t\t\tout += Mv::to(y, x+width - i_size - 27) + title_left + Theme::c(\"title\") + (net_sync ? Fx::b : \"\") + 's' + Theme::c(\"hi_fg\")\n\t\t\t\t\t+ 'y' + Theme::c(\"title\") + \"nc\" + title_right;\n\t\t\t\tInput::mouse_mappings[\"y\"] = {y, x+width - i_size - 26, 1, 4};\n\t\t\t}\n\t\t}\n\n\t\t//? IP or device address\n\t\tif (not ip_addr.empty() and cmp_greater(width - i_size - 36, ip_addr.size())) {\n\t\t\tout += Mv::to(y, x + 8) + title_left + Theme::c(\"title\") + Fx::b + ip_addr + title_right;\n\t\t}\n\n\t\t//? Graphs and stats\n\t\tfor (const string dir : {\"download\", \"upload\"}) {\n\t\t\t//         |  upload  |  download  |\n\t\t\t// no swap |  bottom  |     top    |\n\t\t\t//  swap   |    top   |   bottom   |\n\t\t\t// XNOR operation (==)\n\t\t\tif ((not swap_upload_download and dir == \"download\") or (swap_upload_download and dir == \"upload\")) {\n\t\t\t\tout += Mv::to(y+1, x + 1);\n\t\t\t} else {\n\t\t\t\tout += Mv::to(y + u_graph_height + 1 + ((height * swap_upload_download) % 2), x + 1);\n\t\t\t}\n\t\t\tout += graphs.at(dir)(safeVal(net.bandwidth, dir), redraw or data_same or not net.connected)\n\t\t\t\t+ Mv::to(y+1 + (((dir == \"upload\") == (!swap_upload_download)) * (height - 3)), x + 1) + Fx::ub + Theme::c(\"graph_text\")\n\t\t\t\t+ floating_humanizer((dir == \"upload\" ? up_max : down_max), true);\n\t\t\tconst string speed = floating_humanizer(safeVal(net.stat, dir).speed, false, 0, false, true);\n\t\t\tconst string speed_bits = (b_width >= 20 ? floating_humanizer(safeVal(net.stat, dir).speed, false, 0, true, true) : \"\");\n\t\t\tconst string top = floating_humanizer(safeVal(net.stat, dir).top, false, 0, true, true);\n\t\t\tconst string total = floating_humanizer(safeVal(net.stat, dir).total);\n\t\t\tconst string symbol = (dir == \"upload\" ? \"▲\" : \"▼\");\n\t\t\tif ((swap_upload_download and dir == \"upload\") or (not swap_upload_download and dir == \"download\")) {\n\t\t\t\t// Top graph\n\t\t\t\tout += Mv::to(b_y+1, b_x+1) + Fx::ub + Theme::c(\"main_fg\") + symbol + ' ' + ljust(speed, 10) + (b_width >= 20 ? rjust('(' + speed_bits + ')', 13) : \"\");\n\t\t\t\tif (b_height >= 8)\n\t\t\t\t\tout += Mv::to(b_y+2, b_x+1) + symbol + ' ' + \"Top: \" + rjust('(' + top, (b_width >= 20 ? 17 : 9)) + ')';\n\t\t\t\tif (b_height >= 6)\n\t\t\t\t\tout += Mv::to(b_y+2 + (b_height >= 8), b_x+1) + symbol + ' ' + \"Total: \" + rjust(total, (b_width >= 20 ? 16 : 8));\n\t\t\t} else {\n\t\t\t\t// Bottom graph\n\t\t\t\tout += Mv::to(b_y + b_height - (b_height / 2), b_x + 1) + Fx::ub + Theme::c(\"main_fg\") + symbol + ' ' + ljust(speed, 10) + (b_width >= 20 ? rjust('(' + speed_bits + ')', 13) : \"\");\n\t\t\t\tif (b_height >= 8)\n\t\t\t\t\tout += Mv::to(b_y + b_height - (b_height / 2) + 1, b_x + 1) + symbol + ' ' + \"Top: \" + rjust('(' + top, (b_width >= 20 ? 17 : 9)) + ')';\n\t\t\t\tif (b_height >= 6)\n\t\t\t\t\tout += Mv::to(b_y + b_height - (b_height / 2) + 1 + (b_height >= 8), b_x + 1) + symbol + ' ' + \"Total: \" + rjust(total, (b_width >= 20 ? 16 : 8));\n\t\t\t}\n\t\t}\n\n\t\tredraw = false;\n\t\treturn out + Fx::reset;\n\t}\n\n}\n\nnamespace Proc {\n\tint width_p = 55, height_p = 68;\n\tint min_width = 44, min_height = 16;\n\tint x, y, width = 20, height;\n\tint start, selected, select_max;\n\tbool shown = true, redraw = true;\n\tbool is_last_process_in_list = false;\n\tint selected_pid = 0, selected_depth = 0;\n\tint scroll_pos;\n\tstring selected_name;\n\tstd::unordered_map<size_t, Draw::Graph> p_graphs;\n\tstd::unordered_map<size_t, bool> p_wide_cmd;\n\tstd::unordered_map<size_t, int> p_counters;\n\tint counter = 0;\n\tDraw::TextEdit filter;\n\tDraw::Graph detailed_cpu_graph;\n\tDraw::Graph detailed_mem_graph;\n\tint user_size, thread_size, prog_size, cmd_size, tree_size;\n\tint dgraph_x, dgraph_width, d_width, d_x, d_y;\n\tbool previous_proc_banner_state = false;\n\tatomic<bool> resized (false);\n\n\tstring box;\n\n\tint selection(const std::string_view cmd_key) {\n\t\tauto start = Config::getI(\"proc_start\");\n\t\tauto selected = Config::getI(\"proc_selected\");\n\t\tauto last_selected = Config::getI(\"proc_last_selected\");\n\t\tbool changed = false;\n\t\tint select_max = (Config::getB(\"show_detailed\") ? (Config::getB(\"proc_banner_shown\") ? Proc::select_max - 9 : Proc::select_max - 8) :\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(Config::getB(\"proc_banner_shown\") ? Proc::select_max - 1 : Proc::select_max));\n\n\t\t// Return the selection from the detailed view to the followed process before moving the selection\n\t\t// Disengage following mode when moving the selection unless paused\n\t\tif (Config::getB(\"follow_process\")) {\n\t\t\tif (Config::getB(\"show_detailed\") and selected == 0 and Config::getB(\"should_selection_return_to_followed\")\n\t\t\tand Config::getI(\"detailed_pid\") == Config::getI(\"followed_pid\")) {\n\t\t\t\tselected = Config::getI(\"proc_followed\");\n\t\t\t\tConfig::set(\"should_selection_return_to_followed\", false);\n\t\t\t\tchanged = true;\n\t\t\t}\n\t\t\tif (not Config::getB(\"pause_proc_list\")) {\n\t\t\t\tConfig::flip(\"follow_process\");\n\t\t\t\tConfig::set(\"followed_pid\", 0);\n\t\t\t\tConfig::set(\"proc_followed\", 0);\n\t\t\t\tselect_max++;\n\t\t\t}\n\t\t\tredraw = true;\n\t\t}\n\n\t\tauto vim_keys = Config::getB(\"vim_keys\");\n\n\t\tint numpids = Proc::numpids;\n\t\tif ((cmd_key == \"up\" or (vim_keys and cmd_key == \"k\")) and selected > 0) {\n\t\t\tif (start > 0 and selected == 1) start--;\n\t\t\telse selected--;\n\t\t\tif (Config::getI(\"proc_last_selected\") > 0) Config::set(\"proc_last_selected\", 0);\n\t\t}\n\t\telse if (cmd_key == \"mouse_scroll_up\" and start > 0) {\n\t\t\tstart = max(0, start - 3);\n\t\t}\n\t\telse if (cmd_key == \"mouse_scroll_down\" and start < numpids - select_max) {\n\t\t\tstart = min(numpids - select_max, start + 3);\n\t\t}\n\t\telse if (cmd_key == \"down\" or (vim_keys and cmd_key == \"j\")) {\n\t\t\tif (start < numpids - select_max and selected == select_max) start++;\n\t\t\telse if (selected == 0 and last_selected > 0) {\n\t\t\t\tselected = last_selected;\n\t\t\t\tConfig::set(\"proc_last_selected\", 0);\n\t\t\t}\n\t\t\telse selected++;\n\t\t}\n\t\telse if (cmd_key == \"page_up\") {\n\t\t\tif (selected > 0 and start == 0) selected = 0;\n\t\t\telse start = max(0, start - select_max);\n\t\t}\n\t\telse if (cmd_key == \"page_down\") {\n\t\t\tif (selected > 0 and start >= numpids - select_max) selected = select_max;\n\t\t\telse start = clamp(start + select_max, 0, max(0, numpids - select_max));\n\t\t}\n\t\telse if (cmd_key == \"home\" or (vim_keys and cmd_key == \"g\")) {\n\t\t\tstart = 0;\n\t\t\tif (selected > 0) selected = 1;\n\t\t}\n\t\telse if (cmd_key == \"end\" or (vim_keys and cmd_key == \"G\")) {\n\t\t\tstart = max(0, numpids - select_max);\n\t\t\tif (selected > 0) selected = select_max;\n\t\t}\n\t\telse if (cmd_key.starts_with(\"mousey\")) {\n\t\t\tint mouse_y = std::atoi(cmd_key.substr(6).data());\n\t\t\tstart = clamp((int)round((double)mouse_y * (numpids - select_max - 2) / (select_max - 2)), 0, max(0, numpids - select_max));\n\t\t}\n\n\t\tif (start != Config::getI(\"proc_start\")) {\n\t\t\tConfig::set(\"proc_start\", start);\n\t\t\tchanged = true;\n\t\t}\n\t\tif (selected != Config::getI(\"proc_selected\")) {\n\t\t\tConfig::set(\"proc_selected\", selected);\n\t\t\tchanged = true;\n\t\t}\n\t\treturn (not changed ? -1 : selected);\n\t}\n\n\tstring draw(const vector<proc_info>& plist, bool force_redraw, bool data_same) {\n\t\tif (Runner::stopping) return \"\";\n\t\tauto proc_tree = Config::getB(\"proc_tree\");\n\t\tbool show_detailed = (Config::getB(\"show_detailed\") and cmp_equal(Proc::detailed.last_pid, Config::getI(\"detailed_pid\")));\n\t\tbool proc_gradient = (Config::getB(\"proc_gradient\") and not Config::getB(\"lowcolor\") and Theme::gradients.contains(\"proc\"));\n\t\tauto proc_colors = Config::getB(\"proc_colors\");\n\t\tauto tty_mode = Config::getB(\"tty_mode\");\n\t\tauto& graph_symbol = (tty_mode ? \"tty\" : Config::getS(\"graph_symbol_proc\"));\n\t\tauto& graph_bg = Symbols::graph_symbols.at((graph_symbol == \"default\" ? Config::getS(\"graph_symbol\") + \"_up\" : graph_symbol + \"_up\")).at(6);\n\t\tauto mem_bytes = Config::getB(\"proc_mem_bytes\");\n\t\tauto vim_keys = Config::getB(\"vim_keys\");\n\t\tauto show_graphs = Config::getB(\"proc_cpu_graphs\");\n\t\tconst auto pause_proc_list = Config::getB(\"pause_proc_list\");\n\t\tauto follow_process = Config::getB(\"follow_process\"); \n\t\tint followed_pid = Config::getI(\"followed_pid\");\n\t\tint followed = Config::getI(\"proc_followed\");\n\t\tbool should_selection_return_to_followed = Config::getB(\"should_selection_return_to_followed\");\n\t\tauto proc_banner_shown = pause_proc_list or follow_process;\n\t\tConfig::set(\"proc_banner_shown\", proc_banner_shown);\n\t\tstart = Config::getI(\"proc_start\");\n\t\tselected = Config::getI(\"proc_selected\");\n\t\tconst int y = show_detailed ? Proc::y + 8 : Proc::y;\n\t\tconst int height = show_detailed ? Proc::height - 8 : Proc::height;\n\t\tint select_max = show_detailed ? (proc_banner_shown ? Proc::select_max - 9 : Proc::select_max - 8) : \n\t\t\t\t\t\t\t\t\t\t\t\t(proc_banner_shown ? Proc::select_max - 1 : Proc::select_max);\n\t\tauto totalMem = Mem::get_totalMem();\n\t\tint numpids = Proc::numpids;\n\t\tif (force_redraw) redraw = true;\n\t\tstring out;\n\t\tout.reserve(width * height);\n\n\t\t//? Move current selection/view to the selected process when a process should be followed\n\t\t//? Restore view and selection to the detailed view process when detailed view is closed\n\t\tconst int restore_detailed_pid = Config::getI(\"restore_detailed_pid\");\n\t\tif ((follow_process and (not pause_proc_list or Config::getB(\"update_following\"))) or restore_detailed_pid > 0) {\n\t\t\tConfig::set(\"update_following\", false);\n\t\t\tint loc = 1;\n\t\t\tbool can_follow = false;\n\t\t\tfor (auto& p : plist) {\n\t\t\t\tif (p.filtered or (proc_tree and p.tree_index == plist.size())) continue;\n\t\t\t\tif (p.pid == (size_t)(restore_detailed_pid > 0 ? restore_detailed_pid : followed_pid)) {\n\t\t\t\t\tcan_follow = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tloc++;\n\t\t\t}\n\n\t\t\tif (can_follow) {\n\t\t\t\tconst int list_middle = select_max % 2 == 0 ? select_max / 2 : select_max / 2 + 1;\n\t\t\t\tstart = max(0, loc - list_middle);\n\t\t\t\tfollowed = loc < list_middle ? loc : start > numpids - select_max ? select_max - numpids + loc : list_middle;\n\t\t\t\tif (restore_detailed_pid == 0) {\n\t\t\t\t\tConfig::set(\"proc_followed\", followed);\n\t\t\t\t\tConfig::set(\"should_selection_return_to_followed\", should_selection_return_to_followed = true);\n\t\t\t\t}\n\t\t\t\tselected = (followed_pid != Config::getI(\"detailed_pid\") or restore_detailed_pid > 0) ? followed : 0;\n\t\t\t}\n\t\t\telse if (restore_detailed_pid == 0) {\n\t\t\t\tConfig::set(\"followed_pid\", followed_pid = 0);\n\t\t\t\tConfig::set(\"follow_process\", follow_process = false);\n\t\t\t\tConfig::set(\"proc_banner_shown\", proc_banner_shown = pause_proc_list);\n\t\t\t\tConfig::set(\"proc_followed\", 0);\n\t\t\t\tif (not proc_banner_shown) select_max++;\n\t\t\t}\n\t\t\tif (restore_detailed_pid > 0) Config::set(\"restore_detailed_pid\", 0);\n\t\t}\n\n\t\t//? Handle selection edge cases when list view is showing bottom of list\n\t\t//? for Pause and Following modes\n\t\tconst bool proc_banner_changed = proc_banner_shown != previous_proc_banner_state;\n\t\tprevious_proc_banner_state = proc_banner_shown;\n\t\tif (proc_banner_changed and not proc_banner_shown\n\t\tand start + select_max - 1 == numpids)\n\t\t\tselected++;\n\t\telse if (pause_proc_list and selected > select_max)\n\t\t\tstart++;\n\n\t\t//? redraw if selection reaches or leaves the end of the list\n\t\tif (selected != Config::getI(\"proc_last_selected\")) {\n\t\t\tif (selected >= select_max and start >= numpids - select_max) {\n\t\t\t\tredraw = true;\n\t\t\t\tis_last_process_in_list = true;\n\t\t\t}\n\t\t\telse if (is_last_process_in_list) {\n\t\t\t\tredraw = true;\n\t\t\t\tis_last_process_in_list = false;\n\t\t\t}\n\t\t}\n\n\t\t//* Redraw elements not needed to be updated every cycle\n\t\tif (redraw) {\n\t\t\tout = box;\n\t\t\tconst string title_left = Theme::c(\"proc_box\") + Symbols::title_left;\n\t\t\tconst string title_right = Theme::c(\"proc_box\") + Symbols::title_right;\n\t\t\tconst string title_left_down = Theme::c(\"proc_box\") + Symbols::title_left_down;\n\t\t\tconst string title_right_down = Theme::c(\"proc_box\") + Symbols::title_right_down;\n\t\t\tfor (const auto& key : {\"t\", \"K\", \"k\", \"s\", \"N\", \"F\", \"enter\", \"info_enter\"})\n\t\t\t\tif (Input::mouse_mappings.contains(key)) Input::mouse_mappings.erase(key);\n\n\t\t\t//? Adapt sizes of text fields\n\t\t\tuser_size = (width < 75 ? 5 : 10);\n\t\t\tthread_size = (width < 75 ? - 1 : 4);\n\t\t\tprog_size = (width > 70 ? 16 : ( width > 55 ? 8 : width - user_size - thread_size - 33));\n\t\t\tcmd_size = (width > 55 ? width - prog_size - user_size - thread_size - 33 : -1);\n\t\t\ttree_size = width - user_size - thread_size - 23;\n\t\t\tif (not show_graphs) {\n\t\t\t\tcmd_size += 5;\n\t\t\t\ttree_size += 5;\n\t\t\t}\n\n\t\t\t//? Detailed box\n\t\t\tif (show_detailed) {\n\t\t\t\tbool alive = detailed.status != \"Dead\";\n\t\t\t\tdgraph_x = x;\n\t\t\t\tdgraph_width = max(width / 3, width - 121);\n\t\t\t\td_width = width - dgraph_width - 1;\n\t\t\t\td_x = x + dgraph_width + 1;\n\t\t\t\td_y = Proc::y;\n\n\t\t\t\t//? Create cpu and mem graphs if process is alive\n\t\t\t\tif (alive or pause_proc_list) {\n\t\t\t\t\tdetailed_cpu_graph = Draw::Graph{dgraph_width - 1, 7, \"cpu\", detailed.cpu_percent, graph_symbol, false, true};\n\t\t\t\t\tdetailed_mem_graph = Draw::Graph{d_width / 3, 1, \"\", detailed.mem_bytes, graph_symbol, false, false, detailed.first_mem};\n\t\t\t\t}\n\n\t\t\t\t//? Draw structure of details box\n\t\t\t\tconst string pid_str = to_string(detailed.entry.pid);\n\t\t\t\tout += Mv::to(y, x) + Theme::c(\"proc_box\") + Symbols::div_left + Symbols::h_line + title_left + Theme::c(\"hi_fg\") + Fx::b\n\t\t\t\t+ (tty_mode ? \"4\" : Symbols::superscript.at(4)) + Theme::c(\"title\") + \"proc\"\n\t\t\t\t\t+ Fx::ub + title_right + Symbols::h_line * (width - 10) + Symbols::div_right\n\t\t\t\t\t+ Mv::to(d_y, dgraph_x + 2) + title_left + Fx::b + Theme::c(\"title\") + pid_str + Fx::ub + title_right\n\t\t\t\t\t+ title_left + Fx::b + Theme::c(\"title\") + uresize(detailed.entry.name, dgraph_width - pid_str.size() - 7, true) + Fx::ub + title_right;\n\n\t\t\t\tout += Mv::to(d_y, d_x - 1) + Theme::c(\"proc_box\") + Symbols::div_up + Mv::to(y, d_x - 1) + Symbols::div_down + Theme::c(\"div_line\");\n\t\t\t\tfor (const int& i : iota(1, 8)) out += Mv::to(d_y + i, d_x - 1) + Symbols::v_line;\n\n\t\t\t\tconst string t_color = (not alive or selected > 0 ? Theme::c(\"inactive_fg\") : Theme::c(\"title\"));\n\t\t\t\tconst string hi_color = (not alive or selected > 0 ? t_color : Theme::c(\"hi_fg\"));\n\t\t\t\tint mouse_x = d_x + 2;\n\t\t\t\tout += Mv::to(d_y, d_x + 1);\n\t\t\t\tif (width > 55) {\n\t\t\t\t\tout += Fx::ub + title_left + hi_color + Fx::b + 't' + t_color + \"erminate\" + Fx::ub + title_right;\n\t\t\t\t\tif (alive and selected == 0) Input::mouse_mappings[\"t\"] = {d_y, mouse_x, 1, 9};\n\t\t\t\t\tmouse_x += 11;\n\t\t\t\t}\n\t\t\t\tout += title_left + hi_color + Fx::b + (vim_keys ? 'K' : 'k') + t_color + \"ill\" + Fx::ub + title_right\n\t\t\t\t\t+ title_left + hi_color + Fx::b + 's' + t_color + \"ignals\" + Fx::ub + title_right\n\t\t\t\t\t+ title_left + hi_color + Fx::b + 'N' + t_color + \"ice\" + Fx::ub + title_right;\n\t\t\t\tif (alive and selected == 0) {\n\t\t\t\t\tInput::mouse_mappings[vim_keys ? \"K\" : \"k\"] = {d_y, mouse_x, 1, 4};\n\t\t\t\t\tmouse_x += 6;\n\t\t\t\t\tInput::mouse_mappings[\"s\"] = {d_y, mouse_x, 1, 7};\n\t\t\t\t    mouse_x += 9;\n\t\t\t\t\tInput::mouse_mappings[\"N\"] = {d_y, mouse_x, 1, 5};\n\t\t\t\t    mouse_x += 7;\n\t\t\t\t}\n\t\t\t\tif (width > 77) {\n\t\t\t\t    fmt::format_to(std::back_inserter(out), \"{}{}{}{}{}{}{}{}\",\n\t\t\t\t    \ttitle_left, follow_process ? Fx::b : \"\",\n\t\t\t\t    \thi_color, 'F', t_color, \"ollow\",\n\t\t\t\t    \tFx::ub, title_right);\n\t\t\t\t    if (selected == 0) Input::mouse_mappings[\"F\"] = {d_y, mouse_x, 1, 6};\n\t\t\t\t}\n\n\t\t\t\t//? Labels\n\t\t\t\tconst int item_fit = floor((double)(d_width - 2) / 10);\n\t\t\t\tconst int item_width = floor((double)(d_width - 2) / min(item_fit, 8));\n\t\t\t\tout += Mv::to(d_y + 1, d_x + 1) + Fx::b + Theme::c(\"title\")\n\t\t\t\t\t\t\t\t\t\t+ cjust(\"Status:\", item_width)\n\t\t\t\t\t\t\t\t\t\t+ cjust(\"Elapsed:\", item_width);\n\t\t\t\tif (item_fit >= 3) out += cjust(\"IO/R:\", item_width);\n\t\t\t\tif (item_fit >= 4) out += cjust(\"IO/W:\", item_width);\n\t\t\t\tif (item_fit >= 5) out += cjust(\"Parent:\", item_width);\n\t\t\t\tif (item_fit >= 6) out += cjust(\"User:\", item_width);\n\t\t\t\tif (item_fit >= 7) out += cjust(\"Threads:\", item_width);\n\t\t\t\tif (item_fit >= 8) out += cjust(\"Nice:\", item_width);\n\n\n\t\t\t\t//? Command line\n\t\t\t\tfor (int i = 0; const auto& l : {'C', 'M', 'D'})\n\t\t\t\tout += Mv::to(d_y + 5 + i++, d_x + 1) + l;\n\n\t\t\t\tout += Theme::c(\"main_fg\") + Fx::ub;\n\t\t\t\tconst auto san_cmd = replace_ascii_control(detailed.entry.cmd);\n\t\t\t\tconst int cmd_size = ulen(san_cmd, true);\n\t\t\t\tfor (int num_lines = min(3, (int)ceil((double)cmd_size / (d_width - 5))), i = 0; i < num_lines; i++) {\n\t\t\t\t\tout += Mv::to(d_y + 5 + (num_lines == 1 ? 1 : i), d_x + 3)\n\t\t\t\t\t\t+ cjust(luresize(san_cmd, cmd_size - (d_width - 5) * i, true), d_width - 5, true, true);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t//? Filter\n\t\t\tauto filtering = Config::getB(\"proc_filtering\"); // ? filter(20) : Config::getS(\"proc_filter\"))\n\t\t\tconst auto filter_text = (filtering) ? filter(max(6, width - 66)) : uresize(Config::getS(\"proc_filter\"), max(6, width - 66));\n\t\t\tout += Mv::to(y, x+9) + title_left + (not filter_text.empty() ? Fx::b : \"\") + Theme::c(\"hi_fg\") + 'f'\n\t\t\t\t+ Theme::c(\"title\") + (not filter_text.empty() ? ' ' + filter_text : \"ilter\")\n\t\t\t\t+ (not filtering and not filter_text.empty() ? Theme::c(\"hi_fg\") + \" del\" : \"\")\n\t\t\t\t+ (filtering ? Theme::c(\"hi_fg\") + ' ' + Symbols::enter : \"\") + Fx::ub + title_right;\n\t\t\tif (not filtering) {\n\t\t\t\tint f_len = (filter_text.empty() ? 6 : ulen(filter_text) + 2);\n\t\t\t\tInput::mouse_mappings[\"f\"] = {y, x + 10, 1, f_len};\n\t\t\t\tif (filter_text.empty() and Input::mouse_mappings.contains(\"delete\"))\n\t\t\t\t\tInput::mouse_mappings.erase(\"delete\");\n\t\t\t\telse if (not filter_text.empty())\n\t\t\t\t\tInput::mouse_mappings[\"delete\"] = {y, x + 11 + f_len, 1, 3};\n\t\t\t}\n\n\t\t\t//? pause, per-core, reverse, tree and sorting\n\t\t\tconst auto& sorting = Config::getS(\"proc_sorting\");\n\t\t\tconst int sort_len = sorting.size();\n\t\t\tconst int sort_pos = x + width - sort_len - 8;\n\n\t\t\tif (width > 60 + sort_len) {\n\t\t\t    fmt::format_to(std::back_inserter(out), \"{}{}{}{}{}{}{}{}{}{}{}\",\n\t\t\t\t\tMv::to(y, sort_pos - 32), title_left, pause_proc_list ? Fx::b : \"\",\n\t\t\t\t\tTheme::c(\"title\"), \"pa\", Theme::c(\"hi_fg\"), 'u', Theme::c(\"title\"), \"se\",\n\t\t\t    \tFx::ub, title_right);\n\t\t\t    Input::mouse_mappings[\"u\"] = {y, sort_pos - 31, 1, 5};\n\t\t\t}\n\t\t\tif (width > 55 + sort_len) {\n\t\t\t\tout += Mv::to(y, sort_pos - 25) + title_left + (Config::getB(\"proc_per_core\") ? Fx::b : \"\") + Theme::c(\"title\")\n\t\t\t\t\t+ \"per-\" + Theme::c(\"hi_fg\") + 'c' + Theme::c(\"title\") + \"ore\" + Fx::ub + title_right;\n\t\t\t\tInput::mouse_mappings[\"c\"] = {y, sort_pos - 24, 1, 8};\n\t\t\t}\n\t\t\tif (width > 45 + sort_len) {\n\t\t\t\tout += Mv::to(y, sort_pos - 15) + title_left + (Config::getB(\"proc_reversed\") ? Fx::b : \"\") + Theme::c(\"hi_fg\")\n\t\t\t\t\t+ 'r' + Theme::c(\"title\") + \"everse\" + Fx::ub + title_right;\n\t\t\t\tInput::mouse_mappings[\"r\"] = {y, sort_pos - 14, 1, 7};\n\t\t\t}\n\t\t\tif (width > 35 + sort_len) {\n\t\t\t\tout += Mv::to(y, sort_pos - 6) + title_left + (Config::getB(\"proc_tree\") ? Fx::b : \"\") + Theme::c(\"title\") + \"tre\"\n\t\t\t\t\t+ Theme::c(\"hi_fg\") + 'e' + Fx::ub + title_right;\n\t\t\t\tInput::mouse_mappings[\"e\"] = {y, sort_pos - 5, 1, 4};\n\t\t\t}\n\t\t\tout += Mv::to(y, sort_pos) + title_left + Fx::b + Theme::c(\"hi_fg\") + Symbols::left + \" \" + Theme::c(\"title\") + sorting + \" \" + Theme::c(\"hi_fg\")\n\t\t\t\t+ Symbols::right + Fx::ub + title_right;\n\t\t\t\tInput::mouse_mappings[\"left\"] = {y, sort_pos + 1, 1, 2};\n\t\t\t\tInput::mouse_mappings[\"right\"] = {y, sort_pos + sort_len + 3, 1, 2};\n\n\t\t\t//? select, info, signal, and follow buttons\n\t\t\tconst string down_button = (is_last_process_in_list ? Theme::c(\"inactive_fg\") : Theme::c(\"hi_fg\")) + Symbols::down;\n\t\t\tconst bool is_up_button_highlighted = selected != 0 or (follow_process and followed_pid == Config::getI(\"detailed_pid\") and should_selection_return_to_followed);\n\t\t\tconst string up_button = (is_up_button_highlighted ? Theme::c(\"hi_fg\") : Theme::c(\"inactive_fg\")) + Symbols::up;\n\t\t\tconst string t_color = (selected == 0 ? Theme::c(\"inactive_fg\") : Theme::c(\"title\"));\n\t\t\tconst string hi_color = (selected == 0 ? Theme::c(\"inactive_fg\") : Theme::c(\"hi_fg\"));\n\t\t\tint mouse_x = x + 14;\n\t\t\tout += Mv::to(y + height - 1, x + 1) + title_left_down + Fx::b + hi_color + up_button + Theme::c(\"title\") + \" select \" + down_button + Fx::ub + title_right_down\n\t\t\t\t+ title_left_down + Fx::b + t_color + \"info \" + hi_color + Symbols::enter + Fx::ub + title_right_down;\t\n\t\t\t\tif (selected > 0) Input::mouse_mappings[\"info_enter\"] = {y + height - 1, mouse_x, 1, 6};\n\t\t\t\tmouse_x += 8;\n\t\t\tif (width > 60) {\n\t\t\t\tout += title_left_down + Fx::b + hi_color + 't' + t_color + \"erminate\" + Fx::ub + title_right_down;\n\t\t\t\tif (selected > 0) Input::mouse_mappings[\"t\"] = {y + height - 1, mouse_x, 1, 9};\n\t\t\t\tmouse_x += 11;\n\t\t\t}\n\t\t\tif (width > 55) {\n\t\t\t\tout += title_left_down + Fx::b + hi_color + (vim_keys ? 'K' : 'k') + t_color + \"ill\" + Fx::ub + title_right_down;\n\t\t\t\tif (selected > 0) Input::mouse_mappings[vim_keys ? \"K\" : \"k\"] = {y + height - 1, mouse_x, 1, 4};\n\t\t\t\tmouse_x += 6;\n\t\t\t}\n\t\t\tout += title_left_down + Fx::b + hi_color + 's' + t_color + \"ignals\" + Fx::ub + title_right_down;\n\t\t\tif (selected > 0) Input::mouse_mappings[\"s\"] = {y + height - 1, mouse_x, 1, 7};\n\t\t    mouse_x += 9;\n\t\t    out += title_left_down + Fx::b + hi_color + 'N' + t_color + \"ice\" + Fx::ub + title_right_down;\n\t\t    if (selected > 0) Input::mouse_mappings[\"N\"] = {y + height -1, mouse_x, 1, 5};\n\t\t\tmouse_x += 6;\n\t\t\tif (width > 72) {\n\t\t\t    fmt::format_to(std::back_inserter(out), \"{}{}{}{}{}{}{}{}\",\n\t\t\t    \ttitle_left_down, follow_process ? Fx::b : \"\",\n\t\t\t    \thi_color, 'F', t_color, \"ollow\",\n\t\t\t    \tFx::ub, title_right_down);\n\t\t\t    if (selected > 0) Input::mouse_mappings[\"F\"] = {y + height - 1, mouse_x, 1, 6};\n\t\t\t}\n\n\t\t\t//? Labels for fields in list\n\t\t\tif (not proc_tree)\n\t\t\t\tout += Mv::to(y+1, x+1) + Theme::c(\"title\") + Fx::b\n\t\t\t\t\t+ rjust(\"Pid:\", 8) + ' '\n\t\t\t\t\t+ ljust(\"Program:\", prog_size) + ' '\n\t\t\t\t\t+ (cmd_size > 0 ? ljust(\"Command:\", cmd_size) : \"\") + ' ';\n\t\t\telse\n\t\t\t\tout += Mv::to(y+1, x+1) + Theme::c(\"title\") + Fx::b\n\t\t\t\t\t+ ljust(\"Tree:\", tree_size) + ' ';\n\n\t\t\tout += (thread_size > 0 ? Mv::l(4) + \"Threads: \" : \"\")\n\t\t\t\t\t+ ljust(\"User:\", user_size) + ' '\n\t\t\t\t\t+ rjust((mem_bytes ? \"MemB\" : \"Mem%\"), 5) + ' '\n\t\t\t\t\t+ rjust(\"Cpu%\", (show_graphs ? 10 : 5)) + Fx::ub;\n\t\t}\n\t\t//* End of redraw block\n\n\t\t//? Draw details box if shown\n\t\tif (show_detailed) {\n\t\t\tbool alive = detailed.status != \"Dead\";\n\t\t\tconst int item_fit = floor((double)(d_width - 2) / 10);\n\t\t\tconst int item_width = floor((double)(d_width - 2) / min(item_fit, 8));\n\n\t\t\t//? Graph part of box\n\t\t\tfmt::format_to(std::back_inserter(out), \"{move}{unbold}{graph}{move}{fg_color}{bold}{cpu_str}%\",\n\t\t\t\t\"move\"_a = Mv::to(d_y + 1, dgraph_x + 1), \"bold\"_a = Fx::b, \"unbold\"_a = Fx::ub, \"fg_color\"_a = Theme::c(\"title\"),\n\t\t\t\t\"graph\"_a = detailed_cpu_graph(detailed.cpu_percent, (redraw or data_same or not alive)),\n\t\t\t\t\"cpu_str\"_a = (alive or pause_proc_list) ? fmt::format(\"{:>4.{}f}\", detailed.entry.cpu_p, detailed.entry.cpu_p < 9.995f ? 2 : detailed.entry.cpu_p < 99.95f ? 1 : 0) : \"\");\n\t\t\tfor (int i = 0; const auto& l : {'C', 'P', 'U'})\n\t\t\t\tfmt::format_to(std::back_inserter(out), \"{}{}\", Mv::to(d_y + 3 + i++, dgraph_x + 1), l);\n\n\t\t\t//? Info part of box\n\t\t\tconst string stat_color = (not alive ? Theme::c(\"inactive_fg\") : (detailed.status == \"Running\" ? Theme::c(\"proc_misc\") : Theme::c(\"main_fg\")));\n\t\t\tout += Mv::to(d_y + 2, d_x + 1) + stat_color + Fx::ub\n\t\t\t\t\t\t\t\t\t+ cjust(detailed.status, item_width) + Theme::c(\"main_fg\")\n\t\t\t\t\t\t\t\t\t+ cjust(detailed.elapsed, item_width);\n\t\t\tif (item_fit >= 3) out += cjust(detailed.io_read, item_width);\n\t\t\tif (item_fit >= 4) out += cjust(detailed.io_write, item_width);\n\t\t\tif (item_fit >= 5) out += cjust(detailed.parent, item_width, true);\n\t\t\tif (item_fit >= 6) out += cjust(detailed.entry.user, item_width, true);\n\t\t\tif (item_fit >= 7) out += cjust(to_string(detailed.entry.threads), item_width);\n\t\t\tif (item_fit >= 8) out += cjust(to_string(detailed.entry.p_nice), item_width);\n\n\n\t\t\tconst double mem_p = detailed.mem_bytes.back() * 100.0 / totalMem;\n\t\t\tstring mem_str = fmt::format(\"{:.2f}\", mem_p);\n\t\t\tmem_str.resize(4);\n\t\t\tif (mem_str.ends_with('.')) mem_str.pop_back();\n\t\t\tout += Mv::to(d_y + 4, d_x + 1) + Theme::c(\"title\") + Fx::b + rjust((item_fit > 4 ? \"Memory: \" : \"M:\") + rjust(mem_str, 4) + \"% \", (d_width / 3) - 2)\n\t\t\t\t+ Theme::c(\"inactive_fg\") + Fx::ub + graph_bg * (d_width / 3) + Mv::l(d_width / 3)\n\t\t\t\t+ Theme::c(\"proc_misc\") + detailed_mem_graph(detailed.mem_bytes, (redraw or data_same or not alive)) + ' '\n\t\t\t\t+ Theme::c(\"title\") + Fx::b + detailed.memory;\n\t\t}\n\n\t\t//? Check bounds of current selection and view\n\t\tif (start > 0 and numpids <= select_max)\n\t\t\tstart = 0;\n\t\tif (start > numpids - select_max)\n\t\t\tstart = max(0, numpids - select_max);\n\t\tif (selected > select_max)\n\t\t\tselected = select_max;\n\t\tif (selected > numpids)\n\t\t\tselected = numpids;\n\n\t\t//* Iteration over processes\n\t\tint lc = 0;\n\t\tfor (int n=0; auto& p : plist) {\n\t\t\tif (p.filtered or (proc_tree and p.tree_index == plist.size()) or n++ < start) continue;\n\t\t\tbool is_selected = (lc + 1 == selected);\n\t\t\tbool is_followed = followed_pid == (int)p.pid;\n\t\t\tif (is_selected) {\n\t\t\t\tselected_pid = (int)p.pid;\n\t\t\t\tselected_name = p.name;\n\t\t\t\tselected_depth = p.depth;\n\t\t\t}\n\n\t\t\t//? Update graphs for processes with above 0.0% cpu usage, delete if below 0.1% 10x times\n\t\t\tbool has_graph = show_graphs ? p_counters.contains(p.pid) : false;\n\t\t\tif (show_graphs and ((p.cpu_p > 0 and not has_graph) or (not data_same and has_graph))) {\n\t\t\t\tif (not has_graph) {\n\t\t\t\t\tp_graphs[p.pid] = Draw::Graph{5, 1, \"\", {}, graph_symbol};\n\t\t\t\t\tp_counters[p.pid] = 0;\n\t\t\t\t}\n\t\t\t\telse if (p.cpu_p < 0.1 and ++p_counters[p.pid] >= 10) {\n\t\t\t\t\tif (p_graphs.contains(p.pid)) p_graphs.erase(p.pid);\n\t\t\t\t\tp_counters.erase(p.pid);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tp_counters[p.pid] = 0;\n\t\t\t}\n\n\t\t\tout += Fx::reset;\n\n\t\t\t//? Set correct gradient colors if enabled\n\t\t\tstring c_color, m_color, t_color, g_color, end;\n\t\t\tif (is_selected or is_followed) {\n\t\t\t\tc_color = m_color = t_color = g_color = Fx::b;\n\t\t\t\tend = Fx::ub;\n\t\t\t\tconst string highlight = is_followed ? Theme::c(\"followed_bg\") + Theme::c(\"followed_fg\") : Theme::c(\"selected_bg\") + Theme::c(\"selected_fg\");\n\t\t\t\tfmt::format_to(std::back_inserter(out), \"{}{}\", highlight, Fx::b);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tint calc = (selected > lc) ? selected - lc : lc - selected;\n\t\t\t\tif (proc_colors) {\n\t\t\t\t\tend = Theme::c(\"main_fg\") + Fx::ub;\n\t\t\t\t\tarray<string, 3> colors;\n\t\t\t\t\tfor (int i = 0; int v : {(int)round(p.cpu_p), (int)round(p.mem * 100 / totalMem), (int)p.threads / 3}) {\n\t\t\t\t\t\tif (proc_gradient) {\n\t\t\t\t\t\t\tint val = (min(v, 100) + 100) - calc * 100 / select_max;\n\t\t\t\t\t\t\tif (val < 100) colors[i++] = Theme::g(\"proc_color\").at(max(0, val));\n\t\t\t\t\t\t\telse colors[i++] = Theme::g(\"process\").at(clamp(val - 100, 0, 100));\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tcolors[i++] = Theme::g(\"process\").at(clamp(v, 0, 100));\n\t\t\t\t\t}\n\t\t\t\t\tc_color = colors.at(0); m_color = colors.at(1); t_color = colors.at(2);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tc_color = m_color = t_color = Fx::b;\n\t\t\t\t\tend = Fx::ub;\n\t\t\t\t}\n\t\t\t\tif (proc_gradient) {\n\t\t\t\t\tg_color = Theme::g(\"proc\").at(clamp(calc * 100 / select_max, 0, 100));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst auto san_cmd = replace_ascii_control(p.cmd);\n\n\t\t\tif (not p_wide_cmd.contains(p.pid)) p_wide_cmd[p.pid] = ulen(san_cmd) != ulen(san_cmd, true);\n\n\t\t\t//? Normal view line\n\t\t\tif (not proc_tree) {\n\t\t\t\tout += Mv::to(y+2+lc, x+1)\n\t\t\t\t\t+ g_color + rjust(to_string(p.pid), 8) + ' '\n\t\t\t\t\t+ c_color + ljust(p.name, prog_size, true) + ' ' + end\n\t\t\t\t\t+ (cmd_size > 0 ? g_color + ljust(san_cmd, cmd_size, true, p_wide_cmd[p.pid]) + Mv::to(y+2+lc, x+11+prog_size+cmd_size) + ' ' : \"\");\n\t\t\t}\n\t\t\t//? Tree view line\n\t\t\telse {\n\t\t\t\tconst string prefix_pid = p.prefix + to_string(p.pid);\n\t\t\t\tint width_left = tree_size;\n\t\t\t\tout += Mv::to(y+2+lc, x+1) + g_color + uresize(prefix_pid, width_left) + ' ';\n\t\t\t\twidth_left -= ulen(prefix_pid);\n\t\t\t\tif (width_left > 0) {\n\t\t\t\t\tout += c_color + uresize(p.name, width_left - 1) + end + ' ';\n\t\t\t\t\twidth_left -= (ulen(p.name) + 1);\n\t\t\t\t}\n\t\t\t\tif (width_left > 7) {\n\t\t\t\t\tconst string_view cmd = width_left > 40 ? rtrim(san_cmd) : p.short_cmd;\n\t\t\t\t\tif (not cmd.empty() and cmd != p.name) {\n\t\t\t\t\t\tout += g_color + '(' + uresize(string{cmd}, width_left - 3, p_wide_cmd[p.pid]) + \") \";\n\t\t\t\t\t\twidth_left -= (ulen(string{cmd}, true) + 3);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tout += string(max(0, width_left), ' ') + Mv::to(y+2+lc, x+2+tree_size);\n\t\t\t}\n\t\t\t//? Common end of line\n\t\t\tstring cpu_str = fmt::format(\"{:.2f}\", p.cpu_p);\n\t\t\tif (p.cpu_p < 10 or (p.cpu_p >= 100 and p.cpu_p < 1000)) cpu_str.resize(3);\n\t\t\telse if (p.cpu_p >= 10'000) {\n\t\t\t\tcpu_str = fmt::format(\"{:.2f}\", p.cpu_p / 1000);\n\t\t\t\tcpu_str.resize(3);\n\t\t\t\tif (cpu_str.ends_with('.')) cpu_str.pop_back();\n\t\t\t\tcpu_str += \"k\";\n\t\t\t}\n\t\t\tstring mem_str = (mem_bytes ? floating_humanizer(p.mem, true) : \"\");\n\t\t\tif (not mem_bytes) {\n\t\t\t\tdouble mem_p = clamp((double)p.mem * 100 / totalMem, 0.0, 100.0);\n\t\t\t\tmem_str = mem_p < 0.01 ? \"0\" : fmt::format(\"{:.1f}\", mem_p);\n\t\t\t\tif (mem_str.size() > 3) mem_str.resize(3);\n\t\t\t\tif (mem_str.ends_with('.')) mem_str.pop_back();\n\t\t\t\tmem_str += '%';\n\t\t\t}\n\n\t\t\t// Shorten process thread representation when larger than 5 digits: 10000 -> 10K ...\n\t\t\tconst std::string proc_threads_string = [&] {\n\t\t\t\tif (p.threads > 9999) {\n\t\t\t\t\treturn std::to_string(p.threads / 1000) + 'K';\n\t\t\t\t} else {\n\t\t\t\t\treturn std::to_string(p.threads);\n\t\t\t\t}\n\t\t\t}();\n\n\t\t\tout += (thread_size > 0 ? t_color + rjust(proc_threads_string, thread_size) + ' ' + end : \"\" )\n\t\t\t\t+ g_color + ljust((cmp_greater(p.user.size(), user_size) ? p.user.substr(0, user_size - 1) + '+' : p.user), user_size) + ' '\n\t\t\t\t+ m_color + rjust(mem_str, 5) + end + ' '\n\t\t\t\t+ (is_selected or is_followed ? \"\" : Theme::c(\"inactive_fg\")) + (show_graphs ? graph_bg * 5: \"\")\n\t\t\t\t+ (p_graphs.contains(p.pid) ? Mv::l(5) + c_color + p_graphs.at(p.pid)({(p.cpu_p >= 0.1 and p.cpu_p < 5 ? 5ll : (long long)round(p.cpu_p))}, data_same) : \"\") + end + ' '\n\t\t\t\t+ c_color + rjust(cpu_str, 4) + \"  \" + end;\n\t\t\tif (lc++ > height - 5) break;\n\t\t\telse if (lc > height - 5 and proc_banner_shown) break;\n\t\t}\n\n\t\tout += Fx::reset;\n\t\twhile (lc++ < height - 3) out += Mv::to(y+lc+1, x+1) + string(width - 2, ' ');\n\t\tif (proc_banner_shown) {\n\t\t\tfmt::format_to(std::back_inserter(out), \"{}{}{}{}{:^{}}{}\",\n\t\t\t\tMv::to(y + height - 2, x + 1),\n\t\t\t\t(pause_proc_list and follow_process) ? Theme::c(\"proc_banner_bg\")\n\t\t\t\t\t: pause_proc_list ? Theme::c(\"proc_pause_bg\")\n\t\t\t\t\t: Theme::c(\"proc_follow_bg\"), \n\t\t\t\tTheme::c(\"proc_banner_fg\"), Fx::b,\n\t\t\t\t(pause_proc_list and follow_process) ? \"Paused list and Following process\"\n\t\t\t\t\t: pause_proc_list ? \"Process list paused\"\n\t\t\t\t\t: \"Following process\", width - 2,\n\t\t\t\tFx::reset);\n\t\t}\n\n\t\t//? Draw scrollbar if needed\n\t\tif (numpids > select_max) {\n\t\t\tscroll_pos = clamp((int)round((double)start * select_max / (numpids - select_max)), 0, height - 5);\n\t\t\tout += Mv::to(y + 1, x + width - 2) + Fx::b + Theme::c(\"main_fg\") + Symbols::up\n\t\t\t\t+ Mv::to(y + height - 2, x + width - 2) + Symbols::down;\n\n\t\t\tfor (int i = y + 2; i < y + height - 2; i++) {\n\t\t\t\tout += Mv::to(i, x + width - 2) + ((i == y + 2 + scroll_pos) ? \"█\" : \" \");\n\t\t\t}\n\t\t}\n\n\t\t//? Current selection and number of processes\n\t\tstring location = to_string(start + (follow_process ? followed : selected)) + '/' + to_string(numpids);\n\t\tstring loc_clear = Symbols::h_line * max((size_t)0, 9 - location.size());\n\t\tout += Mv::to(y + height - 1, x+width - 3 - max(9, (int)location.size())) + Fx::ub + Theme::c(\"proc_box\") + loc_clear\n\t\t\t+ Symbols::title_left_down + Theme::c(\"title\") + Fx::b + location + Fx::ub + Theme::c(\"proc_box\") + Symbols::title_right_down;\n\n\t\t//? Clear out left over graphs from dead processes at a regular interval\n\t\tif (not data_same and ++counter >= 100) {\n\t\t\tcounter = 0;\n\n\t\t\tstd::erase_if(p_graphs, [&](const auto& pair) {\n\t\t\t\treturn rng::find(plist, pair.first, &proc_info::pid) == plist.end();\n\t\t\t});\n\n\t\t\tstd::erase_if(p_counters, [&](const auto& pair) {\n\t\t\t\treturn rng::find(plist, pair.first, &proc_info::pid) == plist.end();\n\t\t\t});\n\n\t\t\tstd::erase_if(p_wide_cmd, [&](const auto& pair) {\n\t\t\t\treturn rng::find(plist, pair.first, &proc_info::pid) == plist.end();\n\t\t\t});\n\t\t}\n\n\t\t//? Draw hide button if detailed view is shown\n\t\tif (show_detailed) {\n\t\t\tconst bool greyed_out = selected_pid != Config::getI(\"detailed_pid\") && selected > 0; \n\t\t\tfmt::format_to(std::back_inserter(out), \"{}{}{}{}{}{}{}{}{}{}{}\",\n\t\t\t\tMv::to(d_y, d_x + d_width - 10), \n\t\t\t\tTheme::c(\"proc_box\"), Symbols::title_left, Fx::b,\n\t\t\t\tgreyed_out ? Theme::c(\"inactive_fg\") : Theme::c(\"title\"), \"hide \",\n\t\t\t\tgreyed_out ? \"\" : Theme::c(\"hi_fg\"), Symbols::enter,\n\t\t\t\tFx::ub, Theme::c(\"proc_box\"), Symbols::title_right);\n\t\t\tif (not greyed_out) Input::mouse_mappings[\"enter\"] = {d_y, d_x + d_width - 9, 1, 6};\n\t\t\telse Input::mouse_mappings.erase(\"enter\");\n\t\t}\n\n\t\tif (selected == 0 and selected_pid != 0) {\n\t\t\tselected_pid = 0;\n\t\t\tselected_name.clear();\n\t\t}\n\t\tredraw = false;\n\t\treturn out + Fx::reset;\n\t}\n\n}\n\nnamespace Draw {\n\tvoid calcSizes() {\n\t\tatomic_wait(Runner::active);\n\t\tConfig::unlock();\n\t\tauto boxes = Config::getS(\"shown_boxes\");\n\t\tauto cpu_bottom = Config::getB(\"cpu_bottom\");\n\t\tauto mem_below_net = Config::getB(\"mem_below_net\");\n\t\tauto proc_left = Config::getB(\"proc_left\");\n\n\t\tCpu::box.clear();\n\n\t\tMem::box.clear();\n\t\tNet::box.clear();\n\t\tProc::box.clear();\n\t\tGlobal::clock.clear();\n\t\tGlobal::overlay.clear();\n\t\tRunner::pause_output = false;\n\t\tRunner::redraw = true;\n\t\tif (not (Proc::resized or Global::resized)) {\n\t\t\tProc::p_counters.clear();\n\t\t\tProc::p_graphs.clear();\n\t\t}\n\t\tif (Menu::active) Menu::redraw = true;\n\n\t\tInput::mouse_mappings.clear();\n\n\t\tCpu::x = Mem::x = Net::x = Proc::x = 1;\n\t\tCpu::y = Mem::y = Net::y = Proc::y = 1;\n\t\tCpu::width = Mem::width = Net::width = Proc::width = 0;\n\t\tCpu::height = Mem::height = Net::height = Proc::height = 0;\n\t\tCpu::redraw = Mem::redraw = Net::redraw = Proc::redraw = true;\n\n\t\tCpu::shown = boxes.contains(\"cpu\");\n\t#ifdef GPU_SUPPORT\n\t\tGpu::box.clear();\n\t\tGpu::width = 0;\n\t\tGpu::shown_panels.clear();\n\t\tif (Gpu::count > 0) {\n\t\t\tstd::istringstream iss(boxes, std::istringstream::in);\n\t\t\tstring current;\n\t\t\twhile (iss >> current) {\n\t\t\t\tif (current.starts_with(\"gpu\"))\n\t\t\t\t\tGpu::shown_panels.push_back(current.back()-'0');\n\t\t\t}\n\t\t}\n\t\tGpu::shown = Gpu::shown_panels.size();\n\n\t\t// Calculate the minimum possible GPU height, store in total_height\n\t\t// The actual total_height value will of course be overwritten later\n\t\tGpu::total_height = 0;\n\t\tfor (int i = 0; i < Gpu::shown; i++) {\n\t\t\tusing namespace Gpu;\n\t\t\ttotal_height += 4 + gpu_b_height_offsets[shown_panels[i]];\n\t\t}\n\t#endif\n\t\tMem::shown = boxes.contains(\"mem\");\n\t\tNet::shown = boxes.contains(\"net\");\n\t\tProc::shown = boxes.contains(\"proc\");\n\n\t\t//* Calculate and draw cpu box outlines\n\t\tif (Cpu::shown) {\n\t\t\tusing namespace Cpu;\n\t\t#ifdef GPU_SUPPORT\n\t\t\t// inline GPU information\n\t\t\tint gpus_extra_height =\n\t\t\t\tConfig::getS(\"show_gpu_info\") == \"On\" ? Gpu::count\n\t\t\t\t: Config::getS(\"show_gpu_info\") == \"Auto\" ? Gpu::count - Gpu::shown\n\t\t\t\t: 0;\n\t\t#endif\n            const bool show_temp = (Config::getB(\"check_temp\") and got_sensors);\n\t\t\twidth = round((double)Term::width * width_p / 100);\n\t\t#ifdef GPU_SUPPORT\n\t\t\tif (Gpu::shown != 0 and not (Mem::shown or Net::shown or Proc::shown)) {\n\t\t\t\theight = Term::height - Gpu::total_height - gpus_extra_height;\n\t\t\t} else {\n\t\t\t\theight = max(8, (int)ceil((double)Term::height * (trim(boxes) == \"cpu\" ? 100 : height_p/(Gpu::shown+1) + (Gpu::shown != 0)*5) / 100));\n\t\t\t}\n\t\t\tif (height <= Term::height-gpus_extra_height) height += gpus_extra_height;\n\t\t#else\n\t\t\theight = max(8, (int)ceil((double)Term::height * (trim(boxes) == \"cpu\" ? 100 : height_p) / 100));\n\t\t#endif\n\t\t\tx = 1;\n\t\t\ty = cpu_bottom ? Term::height - height + 1 : 1;\n\n\t\t#ifdef GPU_SUPPORT\n\t\t\tb_columns = max(2, (int)ceil((double)(Shared::coreCount + 1) / (height - gpus_extra_height - 5)));\n\t\t#else\n\t\t\tb_columns = max(1, (int)ceil((double)(Shared::coreCount + 1) / (height - 5)));\n\t\t#endif\n\t\t\tif (b_columns * (21 + 12 * show_temp) < width - (width / 3)) {\n\t\t\t\tb_column_size = 2;\n\t\t\t\tb_width =  max(29, (21 + 12 * show_temp) * b_columns - (b_columns - 1));\n\t\t\t}\n\t\t\telse if (b_columns * (15 + 6 * show_temp) < width - (width / 3)) {\n\t\t\t\tb_column_size = 1;\n\t\t\t\tb_width = (15 + 6 * show_temp) * b_columns - (b_columns - 1);\n\t\t\t}\n\t\t\telse if (b_columns * (8 + 6 * show_temp) < width - (width / 3)) {\n\t\t\t\tb_column_size = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tb_columns = (width - width / 3) / (8 + 6 * show_temp);\n\t\t\t\tb_column_size = 0;\n\t\t\t}\n\n\t\t\tif (b_column_size == 0) b_width = (8 + 6 * show_temp) * b_columns + 1;\n\t\t#ifdef GPU_SUPPORT\n\t\t\t//gpus_extra_height = max(0, gpus_extra_height - 1);\n\t\t\tb_height = min(height - 2, (int)ceil((double)Shared::coreCount / b_columns) + 4 + gpus_extra_height);\n\t\t#else\n\t\t\tb_height = min(height - 2, (int)ceil((double)Shared::coreCount / b_columns) + 4);\n\t\t#endif\n\n\t\t\tb_x = x + width - b_width - 1;\n\t\t\tb_y = y + ceil((double)(height - 2) / 2) - ceil((double)b_height / 2) + 1;\n\n\t\t\tbox = createBox(x, y, width, height, Theme::c(\"cpu_box\"), true, (cpu_bottom ? \"\" : \"cpu\"), (cpu_bottom ? \"cpu\" : \"\"), 1);\n\n\t\t\tauto& custom = Config::getS(\"custom_cpu_name\");\n\t\t\tstatic const bool hasCpuHz = not Cpu::get_cpuHz().empty();\n\t\t#ifdef __linux__\n\t\t\tstatic const bool freq_range = Config::getS(\"freq_mode\") == \"range\";\n\t\t#else\n\t\t\tstatic const bool freq_range = false;\n\t\t#endif\n\t\t\tconst string cpu_title = uresize(\n\t\t\t\t\t(custom.empty() ? Cpu::cpuName : custom),\n\t\t\t\t\tb_width - (Config::getB(\"show_cpu_freq\") and hasCpuHz ? (freq_range ? 24 : 14) : 5)\n\t\t\t);\n\t\t\tbox += createBox(b_x, b_y, b_width, b_height, \"\", false, cpu_title);\n\t\t}\n\n\t#ifdef GPU_SUPPORT\n\t\t//* Calculate and draw gpu box outlines\n\t\tif (Gpu::shown != 0) {\n\t\t\tusing namespace Gpu;\n\t\t\tx_vec.resize(shown); y_vec.resize(shown);\n\t\t\tb_x_vec.resize(shown); b_y_vec.resize(shown);\n\t\t\tb_height_vec.resize(shown);\n\t\t\tbox.resize(shown);\n\t\t\tgraph_upper_vec.resize(shown); graph_lower_vec.resize(shown);\n\t\t\ttemp_graph_vec.resize(shown);\n\t\t\tmem_used_graph_vec.resize(shown); mem_util_graph_vec.resize(shown);\n\t\t\tgpu_meter_vec.resize(shown);\n\t\t\tpwr_meter_vec.resize(shown);\n\t\t\tenc_meter_vec.resize(shown);\n\t\t\tredraw.resize(shown);\n\t\t\ttotal_height = 0;\n\t\t\tfor (auto i = 0; i < shown; ++i) {\n\t\t\t\tredraw[i] = true;\n\t\t\t\tint height = 0;\n\t\t\t\twidth = Term::width;\n\t\t\t\tif (Cpu::shown)\n\t\t\t\t\tif (not (Mem::shown or Net::shown or Proc::shown))\n\t\t\t\t\t\theight = min_height;\n\t\t\t\t\telse height = Cpu::height;\n\t\t\t\telse\n\t\t\t\t\tif (not (Mem::shown or Net::shown or Proc::shown))\n\t\t\t\t\t\theight = (Term::height - total_height) / (Gpu::shown - i) + (i == 0) * ((Term::height - total_height) % (Gpu::shown - i));\n\t\t\t\t\telse\n\t\t\t\t\t\theight = max(min_height, (int)ceil((double)Term::height * height_p/Gpu::shown / 100));\n\n\t\t\t\tb_height_vec[i] = gpu_b_height_offsets[shown_panels[i]] + 2;\n\t\t\t\theight += (height+Cpu::height == Term::height-1);\n\t\t\t\theight = max(height, b_height_vec[i] + 2);\n\t\t\t\tx_vec[i] = 1; y_vec[i] = 1 + total_height + (not Config::getB(\"cpu_bottom\"))*Cpu::shown*Cpu::height;\n\t\t\t\tbox[i] = createBox(x_vec[i], y_vec[i], width, height, Theme::c(\"cpu_box\"), true, std::string(\"gpu\") + (char)(shown_panels[i]+'0'), \"\", (shown_panels[i]+5)%10); // TODO gpu_box\n\t\t\t\tb_width = clamp(width/2, min_width, 65);\n\t\t\t\ttotal_height += height;\n\n\t\t\t\t//? Main statistics box\n\t\t\t\tb_x_vec[i] = x_vec[i] + width - b_width - 1;\n\t\t\t\tb_y_vec[i] = y_vec[i] + ceil((double)(height - 2 - b_height_vec[i]) / 2) + 1;\n\n\t\t\t\tstring name = Config::getS(std::string(\"custom_gpu_name\") + (char)(shown_panels[i]+'0'));\n\t\t\t\tif (name.empty()) name = gpu_names[shown_panels[i]];\n\n\t\t\t\tbox[i] += createBox(b_x_vec[i], b_y_vec[i], b_width, b_height_vec[i], \"\", false, name.substr(0, b_width-5));\n\t\t\t\tb_height_vec[i] = height - 2;\n\t\t\t}\n\t\t}\n\t#endif\n\n\t\t//* Calculate and draw mem box outlines\n\t\tif (Mem::shown) {\n\t\t\tusing namespace Mem;\n\t\t\tauto show_disks = Config::getB(\"show_disks\");\n\t\t\tauto swap_disk = Config::getB(\"swap_disk\");\n\t\t\tauto mem_graphs = Config::getB(\"mem_graphs\");\n\n\t\t\twidth = round((double)Term::width * (Proc::shown ? width_p : 100) / 100);\n\t\t#ifdef GPU_SUPPORT\n\t\t\theight = floor(static_cast<double>(Term::height) * (100 - Net::height_p * Net::shown*4 / ((Gpu::shown != 0 and Cpu::shown) + 4)) / 100) - Cpu::height - Gpu::total_height;\n\t\t#else\n\t\t\theight = floor(static_cast<double>(Term::height) * (100 - Cpu::height_p * Cpu::shown - Net::height_p * Net::shown) / 100);\n\t\t#endif\n\t\t\tx = (proc_left and Proc::shown) ? Term::width - width + 1: 1;\n\t\t\tif (mem_below_net and Net::shown)\n\t\t#ifdef GPU_SUPPORT\n\t\t\t\ty = Term::height - height + 1 - (cpu_bottom ? Cpu::height : 0);\n\t\t\telse\n\t\t\t\ty = (cpu_bottom ? 1 : Cpu::height + 1) + Gpu::total_height;\n\t\t#else\n\t\t\t\ty = Term::height - height + 1 - (cpu_bottom ? Cpu::height : 0);\n\t\t\telse\n\t\t\t\ty = cpu_bottom ? 1 : Cpu::height + 1;\n\t\t#endif\n\n\t\t\tif (show_disks) {\n\t\t\t\tmem_width = ceil((double)(width - 3) / 2);\n\t\t\t\tmem_width += mem_width % 2;\n\t\t\t\tdisks_width = width - mem_width - 2;\n\t\t\t\tdivider = x + mem_width;\n\t\t\t}\n\t\t\telse\n\t\t\t\tmem_width = width - 1;\n\n\t\t\titem_height = has_swap and not swap_disk ? 6 : 4;\n\t\t\tif (height - (has_swap and not swap_disk ? 3 : 2) > 2 * item_height)\n\t\t\t\tmem_size = 3;\n\t\t\telse if (mem_width > 25)\n\t\t\t\tmem_size = 2;\n\t\t\telse\n\t\t\t\tmem_size = 1;\n\n\t\t\tmem_meter = max(0, mem_width - (mem_size > 2 ? 7 : 17));\n\t\t\tif (mem_size == 1) mem_meter += 6;\n\n\t\t\tif (mem_graphs) {\n\t\t\t\tgraph_height = max(1, (int)round((double)((height - (has_swap and not swap_disk ? 2 : 1)) - (mem_size == 3 ? 2 : 1) * item_height) / item_height));\n\t\t\t\tif (graph_height > 1) mem_meter += 6;\n\t\t\t}\n\t\t\telse\n\t\t\t\tgraph_height = 0;\n\n\t\t\tif (show_disks) {\n\t\t\t\tdisk_meter = max(-14, width - mem_width - 23);\n\t\t\t\tif (disks_width < 25) disk_meter += 14;\n\t\t\t}\n\n\t\t\tbox = createBox(x, y, width, height, Theme::c(\"mem_box\"), true, \"mem\", \"\", 2);\n\t\t\tbox += Mv::to(y, (show_disks ? divider + 2 : x + width - 9)) + Theme::c(\"mem_box\") + Symbols::title_left + (show_disks ? Fx::b : \"\")\n\t\t\t\t+ Theme::c(\"hi_fg\") + 'd' + Theme::c(\"title\") + \"isks\" + Fx::ub + Theme::c(\"mem_box\") + Symbols::title_right;\n\t\t\tInput::mouse_mappings[\"d\"] = {y, (show_disks ? divider + 3 : x + width - 8), 1, 5};\n\t\t\tif (show_disks) {\n\t\t\t\tbox += Mv::to(y, divider) + Symbols::div_up + Mv::to(y + height - 1, divider) + Symbols::div_down + Theme::c(\"div_line\");\n\t\t\t\tfor (auto i : iota(1, height - 1))\n\t\t\t\t\tbox += Mv::to(y + i, divider) + Symbols::v_line;\n\t\t\t}\n\t\t}\n\n\t\t//* Calculate and draw net box outlines\n\t\tif (Net::shown) {\n\t\t\tusing namespace Net;\n\t\t\twidth = round((double)Term::width * (Proc::shown ? width_p : 100) / 100);\n\t\t#ifdef GPU_SUPPORT\n\t\t\theight = Term::height - Cpu::height - Gpu::total_height - Mem::height;\n\t\t#else\n\t\t\theight = Term::height - Cpu::height - Mem::height;\n\t\t#endif\n\t\t\tx = (proc_left and Proc::shown) ? Term::width - width + 1 : 1;\n\t\t\tif (mem_below_net and Mem::shown)\n\t\t\t#ifdef GPU_SUPPORT\n\t\t\t\ty = (cpu_bottom ? 1 : Cpu::height + 1) + Gpu::total_height;\n\t\t\t#else\n\t\t\t\ty = cpu_bottom ? 1 : Cpu::height + 1;\n\t\t\t#endif\n\t\t\telse\n\t\t\t\ty = Term::height - height + 1 - (cpu_bottom ? Cpu::height : 0);\n\n\t\t\tb_width = (width > 45) ? 27 : 19;\n\t\t\tb_height = (height > 10) ? 9 : height - 2;\n\t\t\tb_x = x + width - b_width - 1;\n\t\t\tb_y = y + ((height - 2) / 2) - b_height / 2 + 1;\n\t\t\td_graph_height = round((double)(height - 2) / 2);\n\t\t\tu_graph_height = height - 2 - d_graph_height;\n\n\t\t\tbox = createBox(x, y, width, height, Theme::c(\"net_box\"), true, \"net\", \"\", 3);\n\t\t\tauto swap_up_down = Config::getB(\"swap_upload_download\");\n\t\t\tif (swap_up_down)\n\t\t\t\tbox += createBox(b_x, b_y, b_width, b_height, \"\", false, \"upload\", \"download\");\n\t\t\telse\n\t\t\t\tbox += createBox(b_x, b_y, b_width, b_height, \"\", false, \"download\", \"upload\");\n\t\t}\n\n\t\t//* Calculate and draw proc box outlines\n\t\tif (Proc::shown) {\n\t\t\tusing namespace Proc;\n\t\t\twidth = Term::width - (Mem::shown ? Mem::width : (Net::shown ? Net::width : 0));\n\t\t#ifdef GPU_SUPPORT\n\t\t\theight = Term::height - Cpu::height - Gpu::total_height;\n\t\t#else\n\t\t\theight = Term::height - Cpu::height;\n\t\t#endif\n\t\t\tx = proc_left ? 1 : Term::width - width + 1;\n\t\t#ifdef GPU_SUPPORT\n\t\t\ty = ((cpu_bottom and Cpu::shown) ? 1 : Cpu::height + 1) + Gpu::total_height;\n\t\t#else\n\t\t\ty = (cpu_bottom and Cpu::shown) ? 1 : Cpu::height + 1;\n\t\t#endif\n\t\t\tselect_max = height - 3;\n\t\t\tbox = createBox(x, y, width, height, Theme::c(\"proc_box\"), true, \"proc\", \"\", 4);\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/btop_draw.hpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#pragma once\n\n#include <array>\n#include <deque>\n#include <string>\n#include <string_view>\n#include <unordered_map>\n#include <vector>\n\nusing std::array;\nusing std::deque;\nusing std::string;\nusing std::vector;\n\nnamespace Symbols {\n\tconst string h_line\t\t\t\t= \"─\";\n\tconst string v_line\t\t\t\t= \"│\";\n\tconst string dotted_v_line\t\t= \"╎\";\n\tconst string left_up\t\t\t= \"┌\";\n\tconst string right_up\t\t\t= \"┐\";\n\tconst string left_down\t\t\t= \"└\";\n\tconst string right_down\t\t\t= \"┘\";\n\tconst string round_left_up\t\t= \"╭\";\n\tconst string round_right_up\t\t= \"╮\";\n\tconst string round_left_down\t= \"╰\";\n\tconst string round_right_down\t= \"╯\";\n\tconst string title_left_down\t= \"┘\";\n\tconst string title_right_down\t= \"└\";\n\tconst string title_left\t\t\t= \"┐\";\n\tconst string title_right\t\t= \"┌\";\n\tconst string div_right\t\t\t= \"┤\";\n\tconst string div_left\t\t\t= \"├\";\n\tconst string div_up\t\t\t\t= \"┬\";\n\tconst string div_down\t\t\t= \"┴\";\n\n\n\tconst string up = \"↑\";\n\tconst string down = \"↓\";\n\tconst string left = \"←\";\n\tconst string right = \"→\";\n\tconst string enter = \"↵\";\n}\n\nnamespace Draw {\n\n\t//* Generate if needed and return the btop++ banner\n\tstring banner_gen(int y=0, int x=0, bool centered=false, bool redraw=false);\n\n\t//* An editable text field\n\tclass TextEdit {\n\t\tsize_t pos{};\n\t\tsize_t upos{};\n\t\tbool numeric = false;\n\tpublic:\n\t\tstring text;\n\t\tTextEdit();\n\t\texplicit TextEdit(string text, bool numeric=false);\n\t\tbool command(const std::string_view key);\n\t\tstring operator()(const size_t limit=0);\n\t\tvoid clear();\n\t};\n\n\t//* Create a box and return as a string\n\tstring createBox(\n\t\t\tconst int x, const int y, const int width, const int height, string line_color = \"\", bool fill = false,\n\t\t\tconst std::string_view title = \"\", const std::string_view title2 = \"\", const int num = 0\n\t);\n\n\tbool update_clock(bool force = false);\n\n\t//* Class holding a percentage meter\n\tclass Meter {\n\t\tint width;\n\t\tstring color_gradient;\n\t\tbool invert;\n\t\tarray<string, 101> cache;\n\tpublic:\n\t\tMeter();\n\t\tMeter(const int width, string color_gradient, bool invert = false);\n\n\t\t//* Return a string representation of the meter with given value\n\t\tstring operator()(int value);\n\t};\n\n\t//* Class holding a percentage graph\n\tclass Graph {\n\t\tint width, height;\n\t\tstring color_gradient;\n\t\tstring out, symbol = \"default\";\n\t\tbool invert, no_zero;\n\t\tlong long offset;\n\t\tlong long last = 0, max_value = 0;\n\t\tbool current = true, tty_mode = false;\n\t\tstd::unordered_map<bool, vector<string>> graphs = { {true, {}}, {false, {}}};\n\n\t\t//* Create two representations of the graph to switch between to represent two values for each braille character\n\t\tvoid _create(const deque<long long>& data, int data_offset);\n\n\tpublic:\n\t\tGraph();\n\t\tGraph(int width, int height,\n\t\t\tconst string& color_gradient,\n\t\t\tconst deque<long long>& data,\n\t\t\tconst string& symbol=\"default\",\n\t\t\tbool invert=false, bool no_zero=false,\n\t\t\tlong long max_value=0, long long offset=0);\n\n\t\t//* Add last value from back of <data> and return string representation of graph\n\t\tstring& operator()(const deque<long long>& data, bool data_same=false);\n\n\t\t//* Return string representation of graph\n\t\tstring& operator()();\n\t};\n\n\t//* Calculate sizes of boxes, draw outlines and save to enabled boxes namespaces\n\tvoid calcSizes();\n}\n\nnamespace Proc {\n\textern Draw::TextEdit filter;\n\textern std::unordered_map<size_t, Draw::Graph> p_graphs;\n\textern std::unordered_map<size_t, int> p_counters;\n}\n"
  },
  {
    "path": "src/btop_input.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include <limits>\n#include <ranges>\n#include <vector>\n#include <thread>\n#include <mutex>\n#include <fmt/format.h>\n#include <signal.h>\n#include <sys/select.h>\n#include <utility>\n#include <cmath>\n\n#include \"btop_input.hpp\"\n#include \"btop_tools.hpp\"\n#include \"btop_config.hpp\"\n#include \"btop_shared.hpp\"\n#include \"btop_menu.hpp\"\n#include \"btop_draw.hpp\"\n\nusing namespace Tools;\nusing namespace std::literals; // for operator\"\"s\nnamespace rng = std::ranges;\n\nnamespace Input {\n\n\t//* Map for translating key codes to readable values\n\tconst std::unordered_map<string, string> Key_escapes = {\n\t\t{\"\\033\",\t\"escape\"},\n\t\t{\"\\x12\",\t\"ctrl_r\"},\n\t\t{\"\\n\",\t\t\"enter\"},\n\t\t{\" \",\t\t\"space\"},\n\t\t{\"\\x7f\",\t\"backspace\"},\n\t\t{\"\\x08\",\t\"backspace\"},\n\t\t{\"[A\", \t\t\"up\"},\n\t\t{\"OA\",\t\t\"up\"},\n\t\t{\"[B\", \t\t\"down\"},\n\t\t{\"OB\",\t\t\"down\"},\n\t\t{\"[D\", \t\t\"left\"},\n\t\t{\"OD\",\t\t\"left\"},\n\t\t{\"[C\", \t\t\"right\"},\n\t\t{\"OC\",\t\t\"right\"},\n\t\t{\"[2~\",\t\t\"insert\"},\n\t\t{\"[4h\",\t\t\"insert\"},\n\t\t{\"[3~\",\t\t\"delete\"},\n\t\t{\"[P\",\t\t\"delete\"},\n\t\t{\"[H\",\t\t\"home\"},\n\t\t{\"[1~\",\t\t\"home\"},\n\t\t{\"[F\",\t\t\"end\"},\n\t\t{\"[4~\",\t\t\"end\"},\n\t\t{\"[5~\",\t\t\"page_up\"},\n\t\t{\"[6~\",\t\t\"page_down\"},\n\t\t{\"\\t\",\t\t\"tab\"},\n\t\t{\"[Z\",\t\t\"shift_tab\"},\n\t\t{\"OP\",\t\t\"f1\"},\n\t\t{\"OQ\",\t\t\"f2\"},\n\t\t{\"OR\",\t\t\"f3\"},\n\t\t{\"OS\",\t\t\"f4\"},\n\t\t{\"[15~\",\t\"f5\"},\n\t\t{\"[17~\",\t\"f6\"},\n\t\t{\"[18~\",\t\"f7\"},\n\t\t{\"[19~\",\t\"f8\"},\n\t\t{\"[20~\",\t\"f9\"},\n\t\t{\"[21~\",\t\"f10\"},\n\t\t{\"[23~\",\t\"f11\"},\n\t\t{\"[24~\",\t\"f12\"}\n\t};\n\n\tsigset_t signal_mask;\n\tstd::atomic<bool> polling (false);\n\tarray<int, 2> mouse_pos;\n\tstd::unordered_map<string, Mouse_loc> mouse_mappings;\n\tbool dragging_scroll;\n\n\tdeque<string> history(50, \"\");\n\tstring old_filter;\n\tstring input;\n\n\tbool poll(const uint64_t timeout) {\n\t\tatomic_lock lck(polling);\n\t\tfd_set fds;\n\t\tFD_ZERO(&fds);\n\t\tFD_SET(STDIN_FILENO, &fds);\n\t\tstruct timespec wait;\n\t\tstruct timespec *waitptr = nullptr;\n\n\t\tif(timeout != std::numeric_limits<uint64_t>::max()) {\n\t\t\twait.tv_sec = timeout / 1000;\n\t\t\twait.tv_nsec = (timeout % 1000) * 1000000;\n\t\t\twaitptr = &wait;\n\t\t}\n\n\t\tif(pselect(STDIN_FILENO + 1, &fds, nullptr, nullptr, waitptr, &signal_mask) > 0) {\n\t\t\tinput.clear();\n\t\t\tchar buf[1024];\n\t\t\tssize_t count = 0;\n\t\t\twhile((count = read(STDIN_FILENO, buf, sizeof(buf))) > 0) {\n\t\t\t\tinput.append(std::string_view(buf, count));\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tstring get() {\n\t\tstring key = input;\n\t\tif (not key.empty()) {\n\t\t\t//? Remove escape code prefix if present\n\t\t\tif (key.length() > 1 and key.at(0) == Fx::e.at(0)) {\n\t\t\t\tkey.erase(0, 1);\n\t\t\t}\n\t\t\t\n\t\t\t//? Detect if input is a mouse event.\n\t\t\tif (key.starts_with(\"[<\")) {\n\t\t\t\tstd::string_view key_view = key;\n\t\t\t\tstring mouse_event;\n\t\t\t\tif (key_view.starts_with(\"[<0;\") and key_view.find('M') != std::string_view::npos) {\n\t\t\t\t\tmouse_event = \"mouse_click\";\n\t\t\t\t\tkey_view.remove_prefix(4);\n\t\t\t\t}\n\t\t\t\telse if (key_view.starts_with(\"[<32;\")) {\n\t\t\t\t\tmouse_event = \"mouse_drag\";\n\t\t\t\t\tkey_view.remove_prefix(5);\n\t\t\t\t}\n\t\t\t\telse if (key_view.starts_with(\"[<0;\") and key_view.ends_with('m')) {\n\t\t\t\t\tmouse_event = \"mouse_release\";\n\t\t\t\t\tkey_view.remove_prefix(4);\n\t\t\t\t}\n\t\t\t\telse if (key_view.starts_with(\"[<64;\")) {\n\t\t\t\t\tmouse_event = \"mouse_scroll_up\";\n\t\t\t\t\tkey_view.remove_prefix(5);\n\t\t\t\t}\n\t\t\t\telse if (key_view.starts_with(\"[<65;\")) {\n\t\t\t\t\tmouse_event = \"mouse_scroll_down\";\n\t\t\t\t\tkey_view.remove_prefix(5);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tkey.clear();\n\n\t\t\t\tif (Config::getB(\"proc_filtering\")) {\n\t\t\t\t\tif (mouse_event == \"mouse_click\") return mouse_event;\n\t\t\t\t\telse return \"\";\n\t\t\t\t}\n\n\t\t\t\t//? Get column and line position of mouse and check for any actions mapped to current position\n\t\t\t\tif (not key.empty()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst auto delim = key_view.find(';');\n\t\t\t\t\t\tmouse_pos[0] = stoi((string)key_view.substr(0, delim));\n\t\t\t\t\t\tmouse_pos[1] = stoi((string)key_view.substr(delim + 1, key_view.find('M', delim)));\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::invalid_argument&) { mouse_event.clear(); }\n\t\t\t\t\tcatch (const std::out_of_range&) { mouse_event.clear(); }\n\n\t\t\t\t\tkey = mouse_event;\n\n\t\t\t\t\tif (key == \"mouse_click\" or key == \"mouse_drag\") {\n\t\t\t\t\t\tconst auto& [col, line] = mouse_pos;\n\n\t\t\t\t\t\tfor (const auto& [mapped_key, pos] : (Menu::active ? Menu::mouse_mappings : mouse_mappings)) {\n\t\t\t\t\t\t\tif (col >= pos.col and col < pos.col + pos.width and line >= pos.line and line < pos.line + pos.height) {\n\t\t\t\t\t\t\t\tkey = mapped_key;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\telse if (auto it = Key_escapes.find(key); it != Key_escapes.end())\n\t\t\t\tkey = it->second;\n\t\t\telse if (ulen(key) > 1)\n\t\t\t\tkey.clear();\n\n\t\t\tif (not key.empty()) {\n\t\t\t\thistory.push_back(key);\n\t\t\t\thistory.pop_front();\n\t\t\t}\n\t\t}\n\t\treturn key;\n\t}\n\n\tstring wait() {\n\t\twhile(not poll(std::numeric_limits<uint64_t>::max())) {}\n\t\treturn get();\n\t}\n\n\tvoid interrupt() {\n\t\tkill(getpid(), SIGUSR1);\n\t}\n\n\tvoid clear() {\n\t\t// do not need it, actually\n\t}\n\n\tvoid process(const std::string_view key) {\n\t\tif (key.empty()) return;\n\t\ttry {\n\t\t\tauto filtering = Config::getB(\"proc_filtering\");\n\t\t\tauto vim_keys = Config::getB(\"vim_keys\");\n\t\t\tauto help_key = (vim_keys ? \"H\" : \"h\");\n\t\t\tauto kill_key = (vim_keys ? \"K\" : \"k\");\n\t\t\t//? Global input actions\n\t\t\tif (not filtering) {\n\t\t\t\tbool keep_going = false;\n\t\t\t\tif (key == \"q\") {\n\t\t\t\t\tclean_quit(0);\n\t\t\t\t}\n\t\t\t\telse if (is_in(key, \"escape\", \"m\")) {\n\t\t\t\t\tMenu::show(Menu::Menus::Main);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (is_in(key, \"f1\", \"?\", help_key)) {\n\t\t\t\t\tMenu::show(Menu::Menus::Help);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (is_in(key, \"f2\", \"o\")) {\n\t\t\t\t\tMenu::show(Menu::Menus::Options);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (key.size() == 1 and isint(key)) {\n\t\t\t\t\tauto intKey = std::atoi(key.data());\n\t\t\t\t#ifdef GPU_SUPPORT\n\t\t\t\t\tstatic const array<string, 10> boxes = {\"gpu5\", \"cpu\", \"mem\", \"net\", \"proc\", \"gpu0\", \"gpu1\", \"gpu2\", \"gpu3\", \"gpu4\"};\n\t\t\t\t\tif ((intKey == 0 and Gpu::count < 5) or (intKey >= 5 and intKey - 4 > Gpu::count))\n\t\t\t\t\t\treturn;\n\t\t\t\t#else\n\t\t\t\tstatic const array<string, 10> boxes = {\"\", \"cpu\", \"mem\", \"net\", \"proc\"};\n\t\t\t\t\tif (intKey == 0 or intKey > 4)\n\t\t\t\t\t\treturn;\n\t\t\t\t#endif\n\t\t\t\t\tatomic_wait(Runner::active);\n\n\t\t\t\t\tif (not Config::toggle_box(boxes.at(intKey))) {\n\t\t\t\t\t\tMenu::show(Menu::Menus::SizeError);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tConfig::current_preset.reset();\n\t\t\t\t\tDraw::calcSizes();\n\t\t\t\t\tDraw::update_clock(true);\n\t\t\t\t\tRunner::run(\"all\", false, true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (is_in(key, \"p\", \"P\") and Config::getS(\"disable_presets\") != \"All\") {\n\t\t\t\t\tif (Config::getS(\"disable_presets\") == \"Default\" and Config::preset_list.size() <= 1) return;\n\t\t\t\t\tconst auto old_preset = Config::current_preset;\n\t\t\t\t\tconst int first_preset = (Config::getS(\"disable_presets\") == \"Default\") ? 1 : 0;\n\t\t\t\t\tif (Config::getS(\"disable_presets\") == \"Custom\") Config::current_preset = 0;\n\t\t\t\t\telse if (Config::current_preset.has_value()) {\n\t\t\t\t\t\tif (key == \"p\") {\n\t\t\t\t\t\t\tif(++(*Config::current_preset) >= static_cast<int>(Config::preset_list.size())) Config::current_preset = first_preset;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (--(*Config::current_preset) < first_preset) Config::current_preset = Config::preset_list.size() - 1;\n\t\t\t\t\t}\n\t\t\t\t\telse Config::current_preset = (key == \"p\") ? first_preset : Config::preset_list.size() - 1;\n\t\t\t\t\tif (Config::current_preset == old_preset) return;\n\t\t\t\t\tatomic_wait(Runner::active);\n\t\t\t\t\tif (not Config::apply_preset(Config::preset_list.at(Config::current_preset.value()))) {\n\t\t\t\t\t\tMenu::show(Menu::Menus::SizeError);\n\t\t\t\t\t\tConfig::current_preset = old_preset;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tDraw::calcSizes();\n\t\t\t\t\tDraw::update_clock(true);\n\t\t\t\t\tRunner::run(\"all\", false, true);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (is_in(key, \"ctrl_r\")) {\n\t\t\t\t\tkill(getpid(), SIGUSR2);\n\t\t\t\t\treturn;\n\t\t\t\t} else if (key == \"mouse_release\") {\n\t\t\t\t\tdragging_scroll = false;\n\t\t\t\t} else\n\t\t\t\t\tkeep_going = true;\n\n\t\t\t\tif (not keep_going) return;\n\t\t\t}\n\n\t\t\t//? Input actions for proc box\n\t\t\tif (Proc::shown) {\n\t\t\t\tbool keep_going = false;\n\t\t\t\tbool no_update = true;\n\t\t\t\tbool redraw = true;\n\t\t\t\tif (filtering) {\n\t\t\t\t\tif (key == \"enter\" or key == \"down\") {\n\t\t\t\t\t\tConfig::set(\"proc_filter\", Proc::filter.text);\n\t\t\t\t\t\tConfig::set(\"proc_filtering\", false);\n\t\t\t\t\t\told_filter.clear();\n\t\t\t\t\t\tif(key == \"down\"){\n\t\t\t\t\t\t\tConfig::unlock();\n\t\t\t\t\t\t\tConfig::lock();\n\t\t\t\t\t\t\tprocess(\"down\");\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (key == \"escape\" or key == \"mouse_click\") {\n\t\t\t\t\t\tConfig::set(\"proc_filter\", old_filter);\n\t\t\t\t\t\tConfig::set(\"proc_filtering\", false);\n\t\t\t\t\t\told_filter.clear();\n\t\t\t\t\t}\n\t\t\t\t\telse if (Proc::filter.command(key)) {\n\t\t\t\t\t\tif (Config::getS(\"proc_filter\") != Proc::filter.text)\n\t\t\t\t\t\t\tConfig::set(\"proc_filter\", Proc::filter.text);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (key == \"left\" or (vim_keys and key == \"h\")) {\n\t\t\t\t\tint cur_i = v_index(Proc::sort_vector, Config::getS(\"proc_sorting\"));\n\t\t\t\t\tif (--cur_i < 0)\n\t\t\t\t\t\tcur_i = Proc::sort_vector.size() - 1;\n\t\t\t\t\tConfig::set(\"proc_sorting\", Proc::sort_vector.at(cur_i));\n\t\t\t\t\tConfig::set(\"update_following\", true);\n\t\t\t\t}\n\t\t\t\telse if (key == \"right\" or (vim_keys and key == \"l\")) {\n\t\t\t\t\tint cur_i = v_index(Proc::sort_vector, Config::getS(\"proc_sorting\"));\n\t\t\t\t\tif (std::cmp_greater(++cur_i, Proc::sort_vector.size() - 1))\n\t\t\t\t\t\tcur_i = 0;\n\t\t\t\t\tConfig::set(\"proc_sorting\", Proc::sort_vector.at(cur_i));\n\t\t\t\t\tConfig::set(\"update_following\", true);\n\t\t\t\t}\n\t\t\t\telse if (is_in(key, \"f\", \"/\")) {\n\t\t\t\t\tConfig::flip(\"proc_filtering\");\n\t\t\t\t\tProc::filter = Draw::TextEdit{Config::getS(\"proc_filter\")};\n\t\t\t\t\told_filter = Proc::filter.text;\n\t\t\t\t}\n\t\t\t\telse if (key == \"e\") {\n\t\t\t\t\tConfig::flip(\"proc_tree\");\n\t\t\t\t\tno_update = false;\n\t\t\t\t\tConfig::set(\"update_following\", true);\n\t\t\t\t}\n\t\t\t\telse if (is_in(key, \"u\")) {\n\t\t\t\t\tConfig::flip(\"pause_proc_list\");\n\t\t\t\t}\n\t\t\t\telse if (is_in(key, \"F\")) {\n\t\t\t\t\tif (Config::getI(\"proc_selected\") != 0 and Config::getI(\"followed_pid\") != Config::getI(\"selected_pid\")) {\n\t\t\t\t\t\tConfig::set(\"follow_process\", true);\n\t\t\t\t\t\tConfig::set(\"followed_pid\", Config::getI(\"selected_pid\"));\n\t\t\t\t\t\tConfig::set(\"update_following\", true);\n\t\t\t\t\t}\n\t\t\t\t\telse if (Config::getB(\"show_detailed\") and Config::getI(\"proc_selected\") == 0 and Config::getI(\"followed_pid\") != Config::getI(\"detailed_pid\")) {\n\t\t\t\t\t\tConfig::set(\"follow_process\", true);\n\t\t\t\t\t\tConfig::set(\"followed_pid\", Config::getI(\"detailed_pid\"));\n\t\t\t\t\t\tConfig::set(\"update_following\", true);\n\t\t\t\t\t}\n\t\t\t\t\telse if (Config::getB(\"follow_process\")) {\n\t\t\t\t\t\tConfig::flip(\"follow_process\");\n\t\t\t\t\t\tif (Config::getB(\"should_selection_return_to_followed\"))\n\t\t\t\t\t\t\tConfig::set(\"proc_selected\", Config::getI(\"proc_followed\"));\n\t\t\t\t\t\telse if (Config::getB(\"show_detailed\") and Config::getI(\"followed_pid\") == Config::getI(\"detailed_pid\"))\n\t\t\t\t\t\t\tConfig::set(\"restore_detailed_pid\", Config::getI(\"detailed_pid\"));\n\t\t\t\t\t\tConfig::set(\"followed_pid\", 0);\n\t\t\t\t\t\tConfig::set(\"proc_followed\", 0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (key == \"r\") {\n\t\t\t\t\tConfig::flip(\"proc_reversed\");\n\t\t\t\t\tConfig::set(\"update_following\", true);\n\t\t\t\t}\n\t\t\t\telse if (key == \"c\")\n\t\t\t\t\tConfig::flip(\"proc_per_core\");\n\n\t\t\t\telse if (key == \"%\")\n\t\t\t\t\tConfig::flip(\"proc_mem_bytes\");\n\n\t\t\t\telse if (key == \"delete\" and not Config::getS(\"proc_filter\").empty())\n\t\t\t\t\tConfig::set(\"proc_filter\", \"\"s);\n\n\t\t\t\telse if (key.starts_with(\"mouse_\")) {\n\t\t\t\t\tredraw = false;\n\t\t\t\t\tconst auto& [col, line] = mouse_pos;\n\t\t\t\t\tconst int y = (Config::getB(\"show_detailed\") ? Proc::y + 8 : Proc::y);\n\t\t\t\t\tconst int height = (Config::getB(\"show_detailed\") ? Proc::height - 8 : Proc::height);\n\t\t\t\t\tconst auto in_proc_box = col >= Proc::x + 1 and col < Proc::x + Proc::width and line >= y + 1 and line < y + height - 1;\n\t\t\t\t\tif (key == \"mouse_click\") {\n\t\t\t\t\t\tif (in_proc_box) {\n\t\t\t\t\t\t\tif (col < Proc::x + Proc::width - 2) {\n\t\t\t\t\t\t\t\tconst auto& current_selection = Config::getI(\"proc_selected\");\n\t\t\t\t\t\t\t\tif (current_selection == line - y - 1) {\n\t\t\t\t\t\t\t\t\tredraw = true;\n\t\t\t\t\t\t\t\t\tif (Config::getB(\"proc_tree\")) {\n\t\t\t\t\t\t\t\t\t\tconst int x_pos = col - Proc::x;\n\t\t\t\t\t\t\t\t\t\tconst int offset = Config::getI(\"selected_depth\") * 3;\n\t\t\t\t\t\t\t\t\t\tif (x_pos > offset and x_pos < 4 + offset) {\n\t\t\t\t\t\t\t\t\t\t\tprocess(\"space\");\n\t\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tprocess(\"enter\");\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if (Config::getB(\"proc_banner_shown\") and line == y + height - 2)\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\telse if (current_selection == 0 or line - y - 1 == 0)\n\t\t\t\t\t\t\t\t\tredraw = true;\n\n\t\t\t\t\t\t\t\tif (Config::getB(\"follow_process\") and not Config::getB(\"pause_proc_list\")) {\n\t\t\t\t\t\t\t\t\tConfig::flip(\"follow_process\");\n\t\t\t\t\t\t\t\t\tConfig::set(\"followed_pid\", 0);\n\t\t\t\t\t\t\t\t\tConfig::set(\"proc_followed\", 0);\n\t\t\t\t\t\t\t\t\tredraw = true;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tConfig::set(\"proc_selected\", line - y - 1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (line == y + 1) {\n\t\t\t\t\t\t\t\tif (Proc::selection(\"page_up\") == -1) return;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (line == y + height - 2) {\n\t\t\t\t\t\t\t\tif (Proc::selection(\"page_down\") == -1) return;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (line == y + 2 + Proc::scroll_pos) {\n\t\t\t\t\t\t\t\tdragging_scroll = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (Proc::selection(\"mousey\" + to_string(line - y - 2)) == -1)\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (Config::getI(\"proc_selected\") > 0){\n\t\t\t\t\t\t\tConfig::set(\"proc_selected\", 0);\n\t\t\t\t\t\t\tif (Config::getB(\"follow_process\") and not Config::getB(\"pause_proc_list\")) {\n\t\t\t\t\t\t\t\tConfig::flip(\"follow_process\");\n\t\t\t\t\t\t\t\tConfig::set(\"followed_pid\", 0);\n\t\t\t\t\t\t\t\tConfig::set(\"proc_followed\", 0);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tredraw = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (key.starts_with(\"mouse_scroll_\") and in_proc_box) {\n\t\t\t\t\t\tgoto proc_mouse_scroll;\n\t\t\t\t\t}\n\t\t\t\t\telse if (key == \"mouse_drag\" and dragging_scroll) {\n\t\t\t\t\t\tProc::selection(\"mousey\" + to_string(line - y - 2));\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tkeep_going = true;\n\t\t\t\t}\n\t\t\t\telse if (is_in(key, \"enter\", \"info_enter\")) {\n\t\t\t\t\tif (Config::getI(\"proc_selected\") == 0 and not Config::getB(\"show_detailed\")) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\telse if (Config::getI(\"proc_selected\") > 0 and Config::getI(\"detailed_pid\") != Config::getI(\"selected_pid\")) {\n\t\t\t\t\t\tConfig::set(\"detailed_pid\", Config::getI(\"selected_pid\"));\n\t\t\t\t\t\tConfig::set(\"proc_last_selected\", Config::getI(\"proc_selected\"));\n\t\t\t\t\t\tConfig::set(\"proc_selected\", 0);\n\t\t\t\t\t\tif (Config::getB(\"proc_follow_detailed\")) {\n\t\t\t\t\t\t\tConfig::set(\"follow_process\", true);\n\t\t\t\t\t\t\tConfig::set(\"followed_pid\", Config::getI(\"selected_pid\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tConfig::set(\"show_detailed\", true);\n\t\t\t\t\t}\n\t\t\t\t\telse if (Config::getB(\"show_detailed\")) {\n\t\t\t\t\t\tif (Config::getB(\"proc_follow_detailed\")) {\n\t\t\t\t\t\t\tConfig::set(\"restore_detailed_pid\", Config::getI(\"detailed_pid\"));\n\t\t\t\t\t\t\tif (Config::getB(\"follow_process\") and Config::getI(\"followed_pid\") == Config::getI(\"detailed_pid\")) {\n\t\t\t\t\t\t\t\tConfig::flip(\"follow_process\");\n\t\t\t\t\t\t\t\tConfig::set(\"followed_pid\", 0);\n\t\t\t\t\t\t\t\tConfig::set(\"proc_followed\", 0);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (Config::getI(\"proc_last_selected\") > 0) Config::set(\"proc_selected\", Config::getI(\"proc_last_selected\"));\n\t\t\t\t\t\tConfig::set(\"proc_last_selected\", 0);\n\t\t\t\t\t\tConfig::set(\"detailed_pid\", 0);\n\t\t\t\t\t\tConfig::set(\"show_detailed\", false);\n\t\t\t\t\t}\n\t\t\t\t\tConfig::set(\"update_following\", true);\n\t\t\t\t}\n\t\t\t\telse if (is_in(key, \"+\", \"-\", \"space\", \"C\") and Config::getB(\"proc_tree\")) {\n\t\t\t\t\tconst bool is_following_detailed = Config::getB(\"follow_process\") and Config::getI(\"followed_pid\") == Config::getI(\"detailed_pid\");\n\t\t\t\t\tif (Config::getI(\"proc_selected\") > 0 or is_following_detailed) {\n\t\t\t\t\t\tatomic_wait(Runner::active);\n\t\t\t\t\t\tauto& pid = is_following_detailed and Config::getI(\"proc_selected\") == 0 ? Config::getI(\"followed_pid\") : Config::getI(\"selected_pid\");\n\t\t\t\t\t\tif (key == \"+\" or key == \"space\") Proc::expand = pid;\n\t\t\t\t\t\tif (key == \"-\" or key == \"space\") Proc::collapse = pid;\n\t\t\t\t\t\tif (key == \"C\")\tProc::toggle_children = pid;\n\t\t\t\t\t\tno_update = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (is_in(key, \"t\", kill_key) and (Config::getB(\"show_detailed\") or Config::getI(\"selected_pid\") > 0)) {\n\t\t\t\t\tatomic_wait(Runner::active);\n\t\t\t\t\tif (Config::getB(\"show_detailed\") and Config::getI(\"proc_selected\") == 0 and Proc::detailed.status == \"Dead\") return;\n\t\t\t\t\tMenu::show(Menu::Menus::SignalSend, (key == \"t\" ? SIGTERM : SIGKILL));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (key == \"s\" and (Config::getB(\"show_detailed\") or Config::getI(\"selected_pid\") > 0)) {\n\t\t\t\t\tatomic_wait(Runner::active);\n\t\t\t\t\tif (Config::getB(\"show_detailed\") and Config::getI(\"proc_selected\") == 0 and Proc::detailed.status == \"Dead\") return;\n\t\t\t\t\tMenu::show(Menu::Menus::SignalChoose);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (key == \"N\" and (Config::getB(\"show_detailed\") or Config::getI(\"selected_pid\") > 0)) {\n\t\t\t\t\tatomic_wait(Runner::active);\n\t\t\t\t    if (Config::getB(\"show_detailed\") and Config::getI(\"proc_selected\") == 0 and Proc::detailed.status == \"Dead\") return;\n\t\t\t\t    Menu::show(Menu::Menus::Renice);\n\t\t\t\t    return;\n\t\t\t    }\n\t\t\t\telse if (is_in(key, \"up\", \"down\", \"page_up\", \"page_down\", \"home\", \"end\") or (vim_keys and is_in(key, \"j\", \"k\", \"g\", \"G\"))) {\n\t\t\t\t\tproc_mouse_scroll:\n\t\t\t\t\tredraw = false;\n\t\t\t\t\tauto old_selected = Config::getI(\"proc_selected\");\n\t\t\t\t\tauto new_selected = Proc::selection(key);\n\t\t\t\t\tif (new_selected == -1)\n\t\t\t\t\t\treturn;\n\t\t\t\t\telse if (old_selected != new_selected and (old_selected == 0 or new_selected == 0))\n\t\t\t\t\t\tredraw = true;\n\t\t\t\t}\n\t\t\t\telse keep_going = true;\n\n\t\t\t\tif (not keep_going) {\n\t\t\t\t\tRunner::run(\"proc\", no_update, redraw);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Input actions for cpu box\n\t\t\tif (Cpu::shown) {\n\t\t\t\tbool keep_going = false;\n\t\t\t\tbool no_update = true;\n\t\t\t\tbool redraw = true;\n\t\t\t\tstatic uint64_t last_press = 0;\n\n\t\t\t\tif (key == \"+\" and Config::getI(\"update_ms\") <= 86399900) {\n\t\t\t\t\tint add = (Config::getI(\"update_ms\") <= 86399000 and last_press >= time_ms() - 200\n\t\t\t\t\t\tand rng::all_of(Input::history, [](const auto& str){ return str == \"+\"; })\n\t\t\t\t\t\t? 1000 : 100);\n\t\t\t\t\tConfig::set(\"update_ms\", Config::getI(\"update_ms\") + add);\n\t\t\t\t\tlast_press = time_ms();\n\t\t\t\t\tredraw = true;\n\t\t\t\t}\n\t\t\t\telse if (key == \"-\" and Config::getI(\"update_ms\") >= 200) {\n\t\t\t\t\tint sub = (Config::getI(\"update_ms\") >= 2000 and last_press >= time_ms() - 200\n\t\t\t\t\t\tand rng::all_of(Input::history, [](const auto& str){ return str == \"-\"; })\n\t\t\t\t\t\t? 1000 : 100);\n\t\t\t\t\tConfig::set(\"update_ms\", Config::getI(\"update_ms\") - sub);\n\t\t\t\t\tlast_press = time_ms();\n\t\t\t\t\tredraw = true;\n\t\t\t\t}\n\t\t\t\telse keep_going = true;\n\n\t\t\t\tif (not keep_going) {\n\t\t\t\t\tRunner::run(\"cpu\", no_update, redraw);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Input actions for mem box\n\t\t\tif (Mem::shown) {\n\t\t\t\tbool keep_going = false;\n\t\t\t\tbool no_update = true;\n\t\t\t\tbool redraw = true;\n\n\t\t\t\tif (key == \"i\") {\n\t\t\t\t\tConfig::flip(\"io_mode\");\n\t\t\t\t}\n\t\t\t\telse if (key == \"d\") {\n\t\t\t\t\tConfig::flip(\"show_disks\");\n\t\t\t\t\tno_update = false;\n\t\t\t\t\tDraw::calcSizes();\n\t\t\t\t}\n\t\t\t\telse keep_going = true;\n\n\t\t\t\tif (not keep_going) {\n\t\t\t\t\tRunner::run(\"mem\", no_update, redraw);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Input actions for net box\n\t\t\tif (Net::shown) {\n\t\t\t\tbool keep_going = false;\n\t\t\t\tbool no_update = true;\n\t\t\t\tbool redraw = true;\n\n\t\t\t\tif (is_in(key, \"b\", \"n\")) {\n\t\t\t\t\tatomic_wait(Runner::active);\n\t\t\t\t\tint c_index = v_index(Net::interfaces, Net::selected_iface);\n\t\t\t\t\tif (c_index != (int)Net::interfaces.size()) {\n\t\t\t\t\t\tif (key == \"b\") {\n\t\t\t\t\t\t\tif (--c_index < 0) c_index = Net::interfaces.size() - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (key == \"n\") {\n\t\t\t\t\t\t\tif (++c_index == (int)Net::interfaces.size()) c_index = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tNet::selected_iface = Net::interfaces.at(c_index);\n\t\t\t\t\t\tNet::rescale = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (key == \"y\") {\n\t\t\t\t\tConfig::flip(\"net_sync\");\n\t\t\t\t\tNet::rescale = true;\n\t\t\t\t}\n\t\t\t\telse if (key == \"a\") {\n\t\t\t\t\tConfig::flip(\"net_auto\");\n\t\t\t\t\tNet::rescale = true;\n\t\t\t\t}\n\t\t\t\telse if (key == \"z\") {\n\t\t\t\t\tatomic_wait(Runner::active);\n\t\t\t\t\tauto& ndev = Net::current_net.at(Net::selected_iface);\n\t\t\t\t\tif (ndev.stat.at(\"download\").offset + ndev.stat.at(\"upload\").offset > 0) {\n\t\t\t\t\t\tndev.stat.at(\"download\").offset = 0;\n\t\t\t\t\t\tndev.stat.at(\"upload\").offset = 0;\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tndev.stat.at(\"download\").offset = ndev.stat.at(\"download\").last + ndev.stat.at(\"download\").rollover;\n\t\t\t\t\t\tndev.stat.at(\"upload\").offset = ndev.stat.at(\"upload\").last + ndev.stat.at(\"upload\").rollover;\n\t\t\t\t\t}\n\t\t\t\t\tno_update = false;\n\t\t\t\t}\n\t\t\t\telse keep_going = true;\n\n\t\t\t\tif (not keep_going) {\n\t\t\t\t\tRunner::run(\"net\", no_update, redraw);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcatch (const std::exception& e) {\n\t\t\tthrow std::runtime_error { fmt::format(R\"(Input::process(\"{}\"))\", e.what()) };\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "src/btop_input.hpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#pragma once\n\n#include <array>\n#include <atomic>\n#include <deque>\n#include <string>\n#include <string_view>\n#include <unordered_map>\n\nusing std::array;\nusing std::atomic;\nusing std::deque;\nusing std::string;\n\n/* The input functions rely on the following termios parameters being set:\n\tNon-canonical mode (c_lflags & ~(ICANON))\n\tVMIN and VTIME (c_cc) set to 0\n\tThese will automatically be set when running Term::init() from btop_tools.cpp\n*/\n\n//* Functions and variables for handling keyboard and mouse input\nnamespace Input {\n\n\tstruct Mouse_loc {\n\t\tint line, col, height, width;\n\t};\n\n\t//? line, col, height, width\n\textern std::unordered_map<string, Mouse_loc> mouse_mappings;\n\n\t//* Signal mask used during polling read\n\textern sigset_t signal_mask;\n\n\textern atomic<bool> polling;\n\n\t//* Mouse column and line position\n\textern array<int, 2> mouse_pos;\n\n\t//* Last entered key\n\textern deque<string> history;\n\n\t//* Poll keyboard & mouse input for <timeout> ms and return input availability as a bool\n\tbool poll(const uint64_t timeout=0);\n\n\t//* Get a key or mouse action from input\n\tstring get();\n\n\t//* Wait until input is available and return key\n\tstring wait();\n\n\t//* Interrupt poll/wait\n\tvoid interrupt();\n\n\t//* Clears last entered key\n\tvoid clear();\n\n\t//* Process actions for input <key>\n\tvoid process(const std::string_view key);\n\n}\n"
  },
  {
    "path": "src/btop_log.cpp",
    "content": "// SPDX-License-Identifier: Apache-2.0\n\n#include \"btop_log.hpp\"\n\n#include \"btop_shared.hpp\"\n\n#include <algorithm>\n#include <cerrno>\n#include <chrono>\n#include <cstring>\n#include <filesystem>\n#include <fstream>\n#include <ios>\n#include <iterator>\n#include <mutex>\n#include <optional>\n#include <stdexcept>\n#include <string>\n#include <string_view>\n#include <system_error>\n#include <utility>\n\n#include <fmt/base.h>\n#include <fmt/chrono.h>\n#include <fmt/format.h>\n#include <fmt/std.h>\n#include <sys/types.h>\n#include <unistd.h>\n\nnamespace fs = std::filesystem;\n\nnamespace Logger {\n\tnamespace {\n\t\tconstexpr auto ONE_MEGABYTE = 1024 << 10;\n\n\t\tstruct State {\n\t\t\tstd::mutex lock {};\n\t\t\tstd::once_flag print_header;\n\t\t\tLevel level = Level::ERROR;\n\t\t\tstd::optional<fs::path> path {};\n\t\t};\n\n\t\t[[nodiscard]] auto get_state() -> State& {\n\t\t\tstatic State state;\n\t\t\treturn state;\n\t\t}\n\n\t\tauto rotate_log_file(fs::path& path) {\n\t\t\tstd::error_code errc {};\n\t\t\tif (fs::exists(path, errc) && !errc && fs::file_size(path, errc) > ONE_MEGABYTE && !errc) {\n\t\t\t\tauto old_path = path;\n\t\t\t\told_path += \".1\";\n\t\t\t\tif (fs::exists(old_path, errc) && !errc) {\n\t\t\t\t\tfs::remove(old_path, errc);\n\t\t\t\t}\n\t\t\t\tif (!errc) {\n\t\t\t\t\tfs::rename(path, old_path, errc);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn !errc;\n\t\t}\n\n\t\tclass DropPrivilegeGuard {\n\t\tprivate:\n\t\t\tuid_t saved_euid {};\n\n\t\tpublic:\n\t\t\tDropPrivilegeGuard() {\n\t\t\t\tsaved_euid = geteuid();\n\t\t\t\tauto real_uid = getuid();\n\t\t\t\tif (saved_euid != real_uid && seteuid(real_uid) != 0) {\n\t\t\t\t\tthrow std::runtime_error(\n\t\t\t\t\t\tfmt::format(\"Failed to drop privileges to write log file: {}\", strerror(errno))\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t~DropPrivilegeGuard() noexcept {\n\t\t\t\tif (saved_euid != geteuid()) {\n\t\t\t\t\t// Silently drop error status.\n\t\t\t\t\t#pragma GCC diagnostic push\n\t\t\t\t\t#pragma GCC diagnostic ignored \"-Wunused-result\"\n\t\t\t\t\tseteuid(saved_euid);\n\t\t\t\t\t#pragma GCC diagnostic pop\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tDropPrivilegeGuard(const DropPrivilegeGuard&) = delete;\n\t\t\tDropPrivilegeGuard& operator=(const DropPrivilegeGuard&) = delete;\n\t\t};\n\t} // namespace\n\n\tvoid init(const fs::path& path) {\n\t\tauto& state = get_state();\n\t\tstd::lock_guard guard { state.lock };\n\t\tstate.path = std::make_optional(path);\n\t}\n\n\tvoid set_log_level(Level level) {\n\t\tauto& state = get_state();\n\t\tstd::lock_guard guard { state.lock };\n\t\tstate.level = level;\n\t}\n\n\tvoid set_log_level(const std::string_view level) {\n\t\tauto& state = get_state();\n\t\tauto it = std::ranges::find(log_levels, level);\n\t\tif (it != log_levels.end()) {\n\t\t\tstd::lock_guard guard { state.lock };\n\t\t\tstate.level = static_cast<Level>(std::distance(log_levels.begin(), it));\n\t\t}\n\t}\n\n\tnamespace detail {\n\t\t[[nodiscard]] auto is_enabled(Level level) -> bool {\n\t\t\tauto& state = get_state();\n\t\t\treturn state.level >= level && state.path.has_value();\n\t\t}\n\n\t\tvoid log_write(Level level, const std::string_view msg) {\n\t\t\tauto& state = get_state();\n\n\t\t\tauto guard = std::lock_guard { state.lock };\n\n\t\t\tif (!is_enabled(level) || !state.path.has_value()) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tstd::string buffer {};\n\t\t\tstd::call_once(state.print_header, [&buffer]() {\n\t\t\t\tfmt::format_to(std::back_inserter(buffer), \"\\n===> btop++ v{}\\n\", Global::Version);\n\t\t\t});\n\t\t\tauto now = std::chrono::system_clock::now();\n\t\t\tauto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);\n\t\t\tfmt::format_to(\n\t\t\t\tstd::back_inserter(buffer),\n\t\t\t\t\"{:%F (%T)} | {}: {}\\n\",\n\t\t\t\tseconds,\n\t\t\t\tlog_levels.at(std::to_underlying(level)),\n\t\t\t\tmsg\n\t\t\t);\n\n\t\t\tDropPrivilegeGuard privilege_guard {};\n\n\t\t\tauto& path = state.path.value();\n\t\t\tif (!rotate_log_file(path)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tauto file = std::ofstream { path, std::ios::app };\n\t\t\tif (!file.is_open()) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfile << buffer;\n\t\t}\n\t} // namespace detail\n\n} // namespace Logger\n"
  },
  {
    "path": "src/btop_log.hpp",
    "content": "// SPDX-License-Identifier: Apache-2.0\n\n#pragma once\n\n#include <cstdint>\n#include <filesystem>\n#include <string>\n#include <string_view>\n#include <utility>\n#include <vector>\n\n#include <fmt/format.h>\n#include <fmt/std.h>\n\nnamespace Logger {\n\tenum class Level : std::uint8_t {\n\t\tDISABLED = 0,\n\t\tERROR = 1,\n\t\tWARNING = 2,\n\t\tINFO = 3,\n\t\tDEBUG = 4,\n\t};\n\n\tconst std::vector<std::string> log_levels { \"DISABLED\", \"ERROR\", \"WARNING\", \"INFO\", \"DEBUG\" };\n\n\tnamespace detail {\n\t\tauto is_enabled(Level level) -> bool;\n\n\t\tvoid log_write(Level level, const std::string_view msg);\n\t} // namespace detail\n\n\tvoid init(const std::filesystem::path& path);\n\n\tvoid set_log_level(Level level);\n\n\tvoid set_log_level(const std::string_view level);\n\n\ttemplate<typename... T>\n\tinline void error(fmt::format_string<T...> fmt, T&&... args) {\n\t\t// Check if log level is enabled before allocating string.\n\t\tif (detail::is_enabled(Level::ERROR)) {\n\t\t\tdetail::log_write(Level::ERROR, fmt::format(fmt, std::forward<T>(args)...));\n\t\t}\n\t}\n\n\ttemplate<typename... T>\n\tinline void warning(fmt::format_string<T...> fmt, T&&... args) {\n\t\t// Check if log level is enabled before allocating string.\n\t\tif (detail::is_enabled(Level::WARNING)) {\n\t\t\tdetail::log_write(Level::WARNING, fmt::format(fmt, std::forward<T>(args)...));\n\t\t}\n\t}\n\n\ttemplate<typename... T>\n\tinline void info(fmt::format_string<T...> fmt, T&&... args) {\n\t\t// Check if log level is enabled before allocating string.\n\t\tif (detail::is_enabled(Level::INFO)) {\n\t\t\tdetail::log_write(Level::INFO, fmt::format(fmt, std::forward<T>(args)...));\n\t\t}\n\t}\n\n\ttemplate<typename... T>\n\tinline void debug(fmt::format_string<T...> fmt, T&&... args) {\n\t\t// Check if log level is enabled before allocating string.\n\t\tif (detail::is_enabled(Level::DEBUG)) {\n\t\t\tdetail::log_write(Level::DEBUG, fmt::format(fmt, std::forward<T>(args)...));\n\t\t}\n\t}\n} // namespace Logger\n"
  },
  {
    "path": "src/btop_menu.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include \"btop_menu.hpp\"\n\n#include \"btop_config.hpp\"\n#include \"btop_draw.hpp\"\n#include \"btop_log.hpp\"\n#include \"btop_shared.hpp\"\n#include \"btop_theme.hpp\"\n#include \"btop_tools.hpp\"\n\n#include <errno.h>\n#include <signal.h>\n\n#include <array>\n#include <cmath>\n#include <filesystem>\n#include <iostream>\n#include <unordered_map>\n#include <utility>\n\n#include <fmt/format.h>\n\nusing std::array;\nusing std::ceil;\nusing std::max;\nusing std::min;\nusing std::ref;\nusing std::views::iota;\n\nusing namespace Tools;\n\nnamespace fs = std::filesystem;\n\nnamespace Menu {\n\n   atomic<bool> active (false);\n   string bg;\n   bool redraw{true};\n   int currentMenu = -1;\n   msgBox messageBox;\n   int signalToSend{};\n   int signalKillRet{};\n\n   const array<string, 32> P_Signals = {\n\t   \"0\",\n#ifdef __linux__\n#if defined(__hppa__)\n\t\t\"SIGHUP\", \"SIGINT\", \"SIGQUIT\", \"SIGILL\",\n\t\t\"SIGTRAP\", \"SIGABRT\", \"SIGSTKFLT\", \"SIGFPE\",\n\t\t\"SIGKILL\", \"SIGBUS\", \"SIGSEGV\", \"SIGXCPU\",\n\t\t\"SIGPIPE\", \"SIGALRM\", \"SIGTERM\", \"SIGUSR1\",\n\t\t\"SIGUSR2\", \"SIGCHLD\", \"SIGPWR\", \"SIGVTALRM\",\n\t\t\"SIGPROF\", \"SIGIO\", \"SIGWINCH\", \"SIGSTOP\",\n\t\t\"SIGTSTP\", \"SIGCONT\", \"SIGTTIN\", \"SIGTTOU\",\n\t\t\"SIGURG\", \"SIGXFSZ\", \"SIGSYS\"\n#elif defined(__mips__)\n\t\t\"SIGHUP\", \"SIGINT\", \"SIGQUIT\", \"SIGILL\",\n\t\t\"SIGTRAP\", \"SIGABRT\", \"SIGEMT\", \"SIGFPE\",\n\t\t\"SIGKILL\", \"SIGBUS\", \"SIGSEGV\", \"SIGSYS\",\n\t\t\"SIGPIPE\", \"SIGALRM\", \"SIGTERM\", \"SIGUSR1\",\n\t\t\"SIGUSR2\", \"SIGCHLD\", \"SIGPWR\", \"SIGWINCH\",\n\t\t\"SIGURG\", \"SIGIO\", \"SIGSTOP\", \"SIGTSTP\",\n\t\t\"SIGCONT\", \"SIGTTIN\", \"SIGTTOU\", \"SIGVTALRM\",\n\t\t\"SIGPROF\", \"SIGXCPU\", \"SIGXFSZ\"\n#elif defined(__alpha__)\n\t\t\"SIGHUP\", \"SIGINT\", \"SIGQUIT\", \"SIGILL\",\n\t\t\"SIGTRAP\", \"SIGABRT\", \"SIGEMT\", \"SIGFPE\",\n\t\t\"SIGKILL\", \"SIGBUS\", \"SIGSEGV\", \"SIGSYS\",\n\t\t\"SIGPIPE\", \"SIGALRM\", \"SIGTERM\", \"SIGURG\",\n\t\t\"SIGSTOP\", \"SIGTSTP\", \"SIGCONT\", \"SIGCHLD\",\n\t\t\"SIGTTIN\", \"SIGTTOU\", \"SIGIO\", \"SIGXCPU\",\n\t\t\"SIGXFSZ\", \"SIGVTALRM\", \"SIGPROF\", \"SIGWINCH\",\n\t\t\"SIGPWR\", \"SIGUSR1\", \"SIGUSR2\"\n#elif defined (__sparc__)\n\t\t\"SIGHUP\", \"SIGINT\", \"SIGQUIT\", \"SIGILL\",\n\t\t\"SIGTRAP\", \"SIGABRT\", \"SIGEMT\", \"SIGFPE\",\n\t\t\"SIGKILL\", \"SIGBUS\", \"SIGSEGV\", \"SIGSYS\",\n\t\t\"SIGPIPE\", \"SIGALRM\", \"SIGTERM\", \"SIGURG\",\n\t\t\"SIGSTOP\", \"SIGTSTP\", \"SIGCONT\", \"SIGCHLD\",\n\t\t\"SIGTTIN\", \"SIGTTOU\", \"SIGIO\", \"SIGXCPU\",\n\t\t\"SIGXFSZ\", \"SIGVTALRM\", \"SIGPROF\", \"SIGWINCH\",\n\t\t\"SIGLOST\", \"SIGUSR1\", \"SIGUSR2\"\n#else\n\t\t\"SIGHUP\", \"SIGINT\",\t\"SIGQUIT\",\t\"SIGILL\",\n\t\t\"SIGTRAP\", \"SIGABRT\", \"SIGBUS\", \"SIGFPE\",\n\t\t\"SIGKILL\", \"SIGUSR1\", \"SIGSEGV\", \"SIGUSR2\",\n\t\t\"SIGPIPE\", \"SIGALRM\", \"SIGTERM\", \"SIGSTKFLT\",\n\t\t\"SIGCHLD\", \"SIGCONT\", \"SIGSTOP\", \"SIGTSTP\",\n\t\t\"SIGTTIN\", \"SIGTTOU\", \"SIGURG\", \"SIGXCPU\",\n\t\t\"SIGXFSZ\", \"SIGVTALRM\", \"SIGPROF\", \"SIGWINCH\",\n\t\t\"SIGIO\", \"SIGPWR\", \"SIGSYS\"\n#endif\n#elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__APPLE__)\n\t\t\"SIGHUP\", \"SIGINT\", \"SIGQUIT\", \"SIGILL\",\n\t\t\"SIGTRAP\", \"SIGABRT\", \"SIGEMT\", \"SIGFPE\",\n\t\t\"SIGKILL\", \"SIGBUS\", \"SIGSEGV\", \"SIGSYS\",\n\t\t\"SIGPIPE\", \"SIGALRM\", \"SIGTERM\", \"SIGURG\",\n\t\t\"SIGSTOP\", \"SIGTSTP\", \"SIGCONT\", \"SIGCHLD\",\n\t\t\"SIGTTIN\", \"SIGTTOU\", \"SIGIO\", \"SIGXCPU\",\n\t\t\"SIGXFSZ\", \"SIGVTALRM\", \"SIGPROF\", \"SIGWINCH\",\n\t\t\"SIGINFO\", \"SIGUSR1\", \"SIGUSR2\"\n#else\n\t\t\"SIGHUP\", \"SIGINT\", \"SIGQUIT\", \"SIGILL\",\n\t\t\"SIGTRAP\", \"SIGABRT\", \"7\", \"SIGFPE\",\n\t\t\"SIGKILL\", \"10\", \"SIGSEGV\", \"12\",\n\t\t\"SIGPIPE\", \"SIGALRM\", \"SIGTERM\", \"16\",\n\t\t\"17\", \"18\", \"19\", \"20\",\n\t\t\"21\", \"22\", \"23\", \"24\",\n\t\t\"25\", \"26\", \"27\", \"28\",\n\t\t\"29\", \"30\", \"31\"\n#endif\n\t};\n\n  std::unordered_map<string, Input::Mouse_loc> mouse_mappings;\n\n   const array<array<string, 3>, 3> menu_normal = {\n\t\tarray<string, 3>{\n\t\t\t\"┌─┐┌─┐┌┬┐┬┌─┐┌┐┌┌─┐\",\n\t\t\t\"│ │├─┘ │ ││ ││││└─┐\",\n\t\t\t\"└─┘┴   ┴ ┴└─┘┘└┘└─┘\"\n\t\t},\n\t\t{\n\t\t\t\"┬ ┬┌─┐┬  ┌─┐\",\n\t\t\t\"├─┤├┤ │  ├─┘\",\n\t\t\t\"┴ ┴└─┘┴─┘┴  \"\n\t\t},\n\t\t{\n\t\t\t\"┌─┐ ┬ ┬ ┬┌┬┐\",\n\t\t\t\"│─┼┐│ │ │ │ \",\n\t\t\t\"└─┘└└─┘ ┴ ┴ \"\n\t\t}\n\t};\n\n\tconst array<array<string, 3>, 3> menu_selected = {\n\t\tarray<string, 3>{\n\t\t\t\"╔═╗╔═╗╔╦╗╦╔═╗╔╗╔╔═╗\",\n\t\t\t\"║ ║╠═╝ ║ ║║ ║║║║╚═╗\",\n\t\t\t\"╚═╝╩   ╩ ╩╚═╝╝╚╝╚═╝\"\n\t\t},\n\t\t{\n\t\t\t\"╦ ╦╔═╗╦  ╔═╗\",\n\t\t\t\"╠═╣╠╣ ║  ╠═╝\",\n\t\t\t\"╩ ╩╚═╝╩═╝╩  \"\n\t\t},\n\t\t{\n\t\t\t\"╔═╗ ╦ ╦ ╦╔╦╗ \",\n\t\t\t\"║═╬╗║ ║ ║ ║  \",\n\t\t\t\"╚═╝╚╚═╝ ╩ ╩  \"\n\t\t}\n\t};\n\n\tconst array<int, 3> menu_width = {19, 12, 12};\n\n\tconst vector<array<string, 2>> help_text = {\n\t\t{\"Mouse 1\", \"Clicks buttons and selects in process list.\"},\n\t\t{\"Mouse scroll\", \"Scrolls any scrollable list/text under cursor.\"},\n\t\t{\"Esc, m\", \"Toggles main menu.\"},\n\t\t{\"p\", \"Cycle view presets forwards.\"},\n\t\t{\"shift + p\", \"Cycle view presets backwards.\"},\n\t\t{\"1\", \"Toggle CPU box.\"},\n\t\t{\"2\", \"Toggle MEM box.\"},\n\t\t{\"3\", \"Toggle NET box.\"},\n\t\t{\"4\", \"Toggle PROC box.\"},\n\t\t{\"5\", \"Toggle GPU box.\"},\n\t\t{\"d\", \"Toggle disks view in MEM box.\"},\n\t\t{\"F2, o\", \"Shows options.\"},\n\t\t{\"F1, ?, h\", \"Shows this window.\"},\n\t\t{\"ctrl + z\", \"Sleep program and put in background.\"},\n\t\t{\"ctrl + r\", \"Reloads config file from disk.\"},\n\t\t{\"q, ctrl + c\", \"Quits program.\"},\n\t\t{\"+, -\", \"Add/Subtract 100ms to/from update timer.\"},\n\t\t{\"Up, Down\", \"Select in process list.\"},\n\t\t{\"Enter\", \"Show detailed information for selected process.\"},\n\t\t{\"Spacebar\", \"Expand/collapse the selected process in tree view.\"},\n\t\t{\"C\", \"Expand/collapse the selected process' children.\"},\n\t\t{\"Pg Up, Pg Down\", \"Jump 1 page in process list.\"},\n\t\t{\"Home, End\", \"Jump to first or last page in process list.\"},\n\t\t{\"Left, Right\", \"Select previous/next sorting column.\"},\n\t\t{\"b, n\", \"Select previous/next network device.\"},\n\t\t{\"i\", \"Toggle disks io mode with big graphs.\"},\n\t\t{\"z\", \"Toggle totals reset for current network device\"},\n\t\t{\"a\", \"Toggle auto scaling for the network graphs.\"},\n\t\t{\"y\", \"Toggle synced scaling mode for network graphs.\"},\n\t\t{\"f, /\", \"To enter a process filter. Start with ! for regex.\"},\n\t\t{\"F\", \"Follow selected process.\"},\n\t\t{\"u\", \"Pause process list.\"},\n\t\t{\"delete\", \"Clear any entered filter.\"},\n\t\t{\"c\", \"Toggle per-core cpu usage of processes.\"},\n\t\t{\"r\", \"Reverse sorting order in processes box.\"},\n\t\t{\"e\", \"Toggle processes tree view.\"},\n\t\t{\"%\", \"Toggles memory display mode in processes box.\"},\n\t\t{\"Selected +, -\", \"Expand/collapse the selected process in tree view.\"},\n\t\t{\"Selected t\", \"Terminate selected process with SIGTERM - 15.\"},\n\t\t{\"Selected k\", \"Kill selected process with SIGKILL - 9.\"},\n\t\t{\"Selected s\", \"Select or enter signal to send to process.\"},\n\t\t{\"Selected N\", \"Select new nice value for selected process.\"},\n\t\t{\"\", \" \"},\n\t\t{\"\", \"For bug reporting and project updates, visit:\"},\n\t\t{\"\", \"https://github.com/aristocratos/btop\"},\n\t};\n\n\tconst vector<vector<vector<string>>> categories = {\n\t\t{\n\t\t\t{\"color_theme\",\n\t\t\t\t\"Set color theme.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Choose from all theme files in (usually)\",\n\t\t\t\t\"\\\"/usr/[local/]share/btop/themes\\\" and\",\n\t\t\t\t\"\\\"~/.config/btop/themes\\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"Default\\\" for builtin default theme.\",\n\t\t\t\t\"\\\"TTY\\\" for builtin 16-color theme.\",\n\t\t\t\t\"\",\n\t\t\t\t\"For theme updates see:\",\n\t\t\t\t\"https://github.com/aristocratos/btop\"},\n\t\t\t{\"theme_background\",\n\t\t\t\t\"If the theme set background should be shown.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Set to False if you want terminal background\",\n\t\t\t\t\"transparency.\"},\n\t\t\t{\"truecolor\",\n\t\t\t\t\"Sets if 24-bit truecolor should be used.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Will convert 24-bit colors to 256 color\",\n\t\t\t\t\"(6x6x6 color cube) if False.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Set to False if your terminal doesn't have\",\n\t\t\t\t\"truecolor support and can't convert to\",\n\t\t\t\t\"256-color.\"},\n\t\t\t{\"force_tty\",\n\t\t\t\t\"TTY mode.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Set to true to force tty mode regardless\",\n\t\t\t\t\"if a real tty has been detected or not.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Will force 16-color mode and TTY theme,\",\n\t\t\t\t\"set all graph symbols to \\\"tty\\\" and swap\",\n\t\t\t\t\"out other non tty friendly symbols.\"},\n\t\t\t{\"vim_keys\",\n\t\t\t\t\"Enable vim keys.\",\n\t\t\t\t\"Set to True to enable \\\"h,j,k,l\\\" keys for\",\n\t\t\t\t\"directional control in lists.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Conflicting keys for\",\n\t\t\t\t\"h (help) and k (kill)\",\n\t\t\t\t\"is accessible while holding shift.\"},\n\t\t\t{\"disable_mouse\",\n\t\t\t\t\"Disable all mouse events.\"},\n\t\t\t{\"disable_presets\",\n\t\t\t\t\"Disable the presets.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"Off\\\" All presets are enabled.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"Default\\\" preset is disabled.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"Custom\\\" presets are disabled.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"All\\\" presets are disabled.\"},\n\t\t\t{\"presets\",\n\t\t\t\t\"Define presets for the layout of the boxes.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Preset 0 is always all boxes shown with\",\n\t\t\t\t\"default settings.\",\n\t\t\t\t\"Max 9 presets.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Format: \\\"box_name:P:G,box_name:P:G\\\"\",\n\t\t\t\t\"P=(0 or 1) for alternate positions.\",\n\t\t\t\t\"G=graph symbol to use for box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Use whitespace \\\" \\\" as separator between\",\n\t\t\t\t\"different presets.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Example:\",\n\t\t\t\t\"\\\"mem:0:tty,proc:1:default cpu:0:braille\\\"\"},\n\t\t\t{\"shown_boxes\",\n\t\t\t\t\"Manually set which boxes to show.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Available values are \\\"cpu mem net proc\\\".\",\n\t\t\t#ifdef GPU_SUPPORT\n\t\t\t\t\"Or \\\"gpu0\\\" through \\\"gpu5\\\" for GPU boxes.\",\n\t\t\t#endif\n\t\t\t\t\"Separate values with whitespace.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Toggle between presets with key \\\"p\\\".\"},\n\t\t\t{\"update_ms\",\n\t\t\t\t\"Update time in milliseconds.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Recommended 2000 ms or above for better\",\n\t\t\t\t\"sample times for graphs.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Min value: 100 ms\",\n\t\t\t\t\"Max value: 86400000 ms = 24 hours.\"},\n\t\t\t{\"rounded_corners\",\n\t\t\t\t\"Rounded corners on boxes.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False\",\n\t\t\t\t\"\",\n\t\t\t\t\"Is always False if TTY mode is ON.\"},\n\t\t\t{\"terminal_sync\",\n\t\t\t\t\"Output synchronization.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Use terminal synchronized output sequences\",\n\t\t\t\t\"to reduce flickering on supported terminals.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"graph_symbol\",\n\t\t\t\t\"Default symbols to use for graph creation.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"braille\\\", \\\"block\\\" or \\\"tty\\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"braille\\\" offers the highest resolution but\",\n\t\t\t\t\"might not be included in all fonts.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"block\\\" has half the resolution of braille\",\n\t\t\t\t\"but uses more common characters.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"tty\\\" uses only 3 different symbols but will\",\n\t\t\t\t\"work with most fonts.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Note that \\\"tty\\\" only has half the horizontal\",\n\t\t\t\t\"resolution of the other two,\",\n\t\t\t\t\"so will show a shorter historical view.\"},\n\t\t\t{\"clock_format\",\n\t\t\t\t\"Draw a clock at top of screen.\",\n\t\t\t\t\"(Only visible if cpu box is enabled!)\",\n\t\t\t\t\"\",\n\t\t\t\t\"Formatting according to strftime, empty\",\n\t\t\t\t\"string to disable.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Custom formatting options:\",\n\t\t\t\t\"\\\"/host\\\" = hostname\",\n\t\t\t\t\"\\\"/user\\\" = username\",\n\t\t\t\t\"\\\"/uptime\\\" = system uptime\",\n\t\t\t\t\"\",\n\t\t\t\t\"Examples of strftime formats:\",\n\t\t\t\t\"\\\"%X\\\" = locale HH:MM:SS\",\n\t\t\t\t\"\\\"%H\\\" = 24h hour, \\\"%I\\\" = 12h hour\",\n\t\t\t\t\"\\\"%M\\\" = minute, \\\"%S\\\" = second\",\n\t\t\t\t\"\\\"%d\\\" = day, \\\"%m\\\" = month, \\\"%y\\\" = year\"},\n\t\t\t{\"base_10_sizes\",\n\t\t\t\t\"Use base 10 for bits and bytes sizes.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Uses KB = 1000 instead of KiB = 1024,\",\n\t\t\t\t\"MB = 1000KB instead of MiB = 1024KiB,\",\n\t\t\t\t\"and so on.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"background_update\",\n\t\t\t\t\"Update main ui when menus are showing.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Set this to false if the menus is flickering\",\n\t\t\t\t\"too much for a comfortable experience.\"},\n\t\t\t{\"show_battery\",\n\t\t\t\t\"Show battery stats.\",\n\t\t\t\t\"(Only visible if cpu box is enabled!)\",\n\t\t\t\t\"\",\n\t\t\t\t\"Show battery stats in the top right corner\",\n\t\t\t\t\"if a battery is present.\"},\n\t\t\t{\"selected_battery\",\n\t\t\t\t\"Select battery.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Which battery to use if multiple are present.\",\n\t\t\t\t\"Can be both batteries and UPS.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"Auto\\\" for auto detection.\"},\n\t\t\t{\"show_battery_watts\",\n\t\t\t\t\"Show battery power.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Show discharge power when discharging.\",\n\t\t\t\t\"Show charging power when charging.\"},\n\t\t\t{\"log_level\",\n\t\t\t\t\"Set loglevel for error.log\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"ERROR\\\", \\\"WARNING\\\", \\\"INFO\\\" and \\\"DEBUG\\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"The level set includes all lower levels,\",\n\t\t\t\t\"i.e. \\\"DEBUG\\\" will show all logging info.\"},\n\t\t\t{\"save_config_on_exit\",\n\t\t\t\t\"Save config on exit.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Automatically save current settings to\",\n\t\t\t\t\"config file on exit.\",\n\t\t\t\t\"\",\n\t\t\t\t\"When this is toggled from True to False\",\n\t\t\t\t\"a save is immediately triggered.\",\n\t\t\t\t\"This way a manual save can be done by\",\n\t\t\t\t\"toggling this setting on and off again.\"}\n\t\t},\n\t\t{\n\t\t\t{\"cpu_bottom\",\n\t\t\t\t\"Cpu box location.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Show cpu box at bottom of screen instead\",\n\t\t\t\t\"of top.\"},\n\t\t\t{\"graph_symbol_cpu\",\n\t\t\t\t\"Graph symbol to use for graphs in cpu box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"default\\\", \\\"braille\\\", \\\"block\\\" or \\\"tty\\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"default\\\" for the general default symbol.\",},\n\t\t\t{\"cpu_graph_upper\",\n\t\t\t\t\"Cpu upper graph.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Sets the CPU/GPU stat shown in upper half of\",\n\t\t\t\t\"the CPU graph.\",\n\t\t\t\t\"\",\n\t\t\t\t\"CPU:\",\n\t\t\t\t\"\\\"total\\\" = Total cpu usage. (Auto)\",\n\t\t\t\t\"\\\"user\\\" = User mode cpu usage.\",\n\t\t\t\t\"\\\"system\\\" = Kernel mode cpu usage.\",\n\t\t\t\t\"+ more depending on kernel.\",\n\t\t#ifdef GPU_SUPPORT\n\t\t\t\t\"\",\n\t\t\t\t\"GPU:\",\n\t\t\t\t\"\\\"gpu-totals\\\" = GPU usage split by device.\",\n\t\t\t\t\"\\\"gpu-vram-totals\\\" = VRAM usage split by GPU.\",\n\t\t\t\t\"\\\"gpu-pwr-totals\\\" = Power usage split by GPU.\",\n\t\t\t\t\"\\\"gpu-average\\\" = Avg usage of all GPUs.\",\n\t\t\t\t\"\\\"gpu-vram-total\\\" = VRAM usage of all GPUs.\",\n\t\t\t\t\"\\\"gpu-pwr-total\\\" = Power usage of all GPUs.\",\n\t\t\t\t\"Not all stats are supported on all devices.\"\n\t\t#endif\n\t\t\t\t},\n\t\t\t{\"cpu_graph_lower\",\n\t\t\t\t\"Cpu lower graph.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Sets the CPU/GPU stat shown in lower half of\",\n\t\t\t\t\"the CPU graph.\",\n\t\t\t\t\"\",\n\t\t\t\t\"CPU:\",\n\t\t\t\t\"\\\"total\\\" = Total cpu usage.\",\n\t\t\t\t\"\\\"user\\\" = User mode cpu usage.\",\n\t\t\t\t\"\\\"system\\\" = Kernel mode cpu usage.\",\n\t\t\t\t\"+ more depending on kernel.\",\n\t\t#ifdef GPU_SUPPORT\n\t\t\t\t\"\",\n\t\t\t\t\"GPU:\",\n\t\t\t\t\"\\\"gpu-totals\\\" = GPU usage split/device. (Auto)\",\n\t\t\t\t\"\\\"gpu-vram-totals\\\" = VRAM usage split by GPU.\",\n\t\t\t\t\"\\\"gpu-pwr-totals\\\" = Power usage split by GPU.\",\n\t\t\t\t\"\\\"gpu-average\\\" = Avg usage of all GPUs.\",\n\t\t\t\t\"\\\"gpu-vram-total\\\" = VRAM usage of all GPUs.\",\n\t\t\t\t\"\\\"gpu-pwr-total\\\" = Power usage of all GPUs.\",\n\t\t\t\t\"Not all stats are supported on all devices.\"\n\t\t#endif\n\t\t\t\t},\n\t\t\t{\"cpu_invert_lower\",\n\t\t\t\t\t\"Toggles orientation of the lower CPU graph.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"True or False.\"},\n\t\t\t{\"cpu_single_graph\",\n\t\t\t\t\t\"Completely disable the lower CPU graph.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Shows only upper CPU graph and resizes it\",\n\t\t\t\t\t\"to fit to box height.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"True or False.\"},\n\t\t#ifdef GPU_SUPPORT\n\t\t\t{\"show_gpu_info\",\n\t\t\t\t\t\"Show gpu info in cpu box.\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"Toggles gpu stats in cpu box and the\",\n\t\t\t\t\t\"gpu graph (if \\\"cpu_graph_lower\\\" is set to\",\n\t\t\t\t\t\"\\\"Auto\\\").\",\n\t\t\t\t\t\"\",\n\t\t\t\t\t\"\\\"Auto\\\" to show when no gpu box is shown.\",\n\t\t\t\t\t\"\\\"On\\\" to always show.\",\n\t\t\t\t\t\"\\\"Off\\\" to never show.\"},\n\t\t#endif\n\t\t\t{\"check_temp\",\n\t\t\t\t\"Enable cpu temperature reporting.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"cpu_sensor\",\n\t\t\t\t\"Cpu temperature sensor.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Select the sensor that corresponds to\",\n\t\t\t\t\"your cpu temperature.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Set to \\\"Auto\\\" for auto detection.\"},\n\t\t\t{\"show_coretemp\",\n\t\t\t\t\"Show temperatures for cpu cores.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Only works if check_temp is True and\",\n\t\t\t\t\"the system is reporting core temps.\"},\n\t\t\t{\"cpu_core_map\",\n\t\t\t\t\"Custom mapping between core and coretemp.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Can be needed on certain cpus to get correct\",\n\t\t\t\t\"temperature for correct core.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Use lm-sensors or similar to see which cores\",\n\t\t\t\t\"are reporting temperatures on your machine.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Format: \\\"X:Y\\\"\",\n\t\t\t\t\"X=core with wrong temp.\",\n\t\t\t\t\"Y=core with correct temp.\",\n\t\t\t\t\"Use space as separator between multiple\",\n\t\t\t\t\"entries.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Example: \\\"4:0 5:1 6:3\\\"\"},\n\t\t\t{\"temp_scale\",\n\t\t\t\t\"Which temperature scale to use.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Celsius, default scale.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Fahrenheit, the american one.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Kelvin, 0 = absolute zero, 1 degree change\",\n\t\t\t\t\"equals 1 degree change in Celsius.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Rankine, 0 = absolute zero, 1 degree change\",\n\t\t\t\t\"equals 1 degree change in Fahrenheit.\"},\n\t\t\t{\"show_cpu_freq\",\n\t\t\t\t\"Show CPU frequency.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Can cause slowdowns on systems with many\",\n\t\t\t\t\"cores and certain kernel versions.\"},\n\t\t#ifdef __linux__\n\t\t\t{\"freq_mode\",\n\t\t\t\t\"How the CPU frequency will be displayed.\",\n\t\t\t\t\"\",\n\t\t\t\t\"First, get the frequency from the first\",\n\t\t\t\t\"core.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Range, show the lowest and the highest\",\n\t\t\t\t\"frequency.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Lowest, the lowest frequency.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Highest, the highest frequency.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Average, sum and divide.\"},\n\t\t#endif\n\t\t\t{\"custom_cpu_name\",\n\t\t\t\t\"Custom cpu model name in cpu percentage box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Empty string to disable.\"},\n\t\t\t{\"show_uptime\",\n\t\t\t\t\"Shows the system uptime in the CPU box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Can also be shown in the clock by using\",\n\t\t\t\t\"\\\"/uptime\\\" in the formatting.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"show_cpu_watts\",\n\t\t\t\t\"Shows the CPU power consumption in watts.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Requires running `make setcap` or\",\n\t\t\t\t\"`make setuid` or running with sudo.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t},\n\t#ifdef GPU_SUPPORT\n\t\t{\n\t\t\t{\"nvml_measure_pcie_speeds\",\n\t\t\t\t\"Measure PCIe throughput on NVIDIA cards.\",\n\t\t\t\t\"\",\n\t\t\t\t\"May impact performance on certain cards.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"rsmi_measure_pcie_speeds\",\n\t\t\t\t\"Measure PCIe throughput on AMD cards.\",\n\t\t\t\t\"\",\n\t\t\t\t\"May impact performance on certain cards.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"graph_symbol_gpu\",\n\t\t\t\t\"Graph symbol to use for graphs in gpu box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"default\\\", \\\"braille\\\", \\\"block\\\" or \\\"tty\\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"default\\\" for the general default symbol.\",},\n\t\t\t{\"gpu_mirror_graph\",\n\t\t\t\t\"Horizontally mirror the GPU graph.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"shown_gpus\",\n\t\t\t\t\"Manually set which gpu vendors to show.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Available values are\",\n\t\t\t\t\"\\\"nvidia\\\", \\\"amd\\\", \\\"intel\\\",\",\n\t\t\t\t\"and \\\"apple\\\".\",\n\t\t\t\t\"Separate values with whitespace.\",\n\t\t\t\t\"\",\n\t\t\t\t\"A restart is required to apply changes.\"},\n\t\t\t{\"custom_gpu_name0\",\n\t\t\t\t\"Custom gpu0 model name in gpu stats box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Empty string to disable.\"},\n\t\t\t{\"custom_gpu_name1\",\n\t\t\t\t\"Custom gpu1 model name in gpu stats box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Empty string to disable.\"},\n\t\t\t{\"custom_gpu_name2\",\n\t\t\t\t\"Custom gpu2 model name in gpu stats box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Empty string to disable.\"},\n\t\t\t{\"custom_gpu_name3\",\n\t\t\t\t\"Custom gpu3 model name in gpu stats box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Empty string to disable.\"},\n\t\t\t{\"custom_gpu_name4\",\n\t\t\t\t\"Custom gpu4 model name in gpu stats box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Empty string to disable.\"},\n\t\t\t{\"custom_gpu_name5\",\n\t\t\t\t\"Custom gpu5 model name in gpu stats box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Empty string to disable.\"},\n\t\t},\n\t#endif\n\t\t{\n\t\t\t{\"mem_below_net\",\n\t\t\t\t\"Mem box location.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Show mem box below net box instead of above.\"},\n\t\t\t{\"graph_symbol_mem\",\n\t\t\t\t\"Graph symbol to use for graphs in mem box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"default\\\", \\\"braille\\\", \\\"block\\\" or \\\"tty\\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"default\\\" for the general default symbol.\",},\n\t\t\t{\"mem_graphs\",\n\t\t\t\t\"Show graphs for memory values.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"show_disks\",\n\t\t\t\t\"Split memory box to also show disks.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"show_io_stat\",\n\t\t\t\t\"Toggle IO activity graphs.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Show small IO graphs that for disk activity\",\n\t\t\t\t\"(disk busy time) when not in IO mode.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"io_mode\",\n\t\t\t\t\"Toggles io mode for disks.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Shows big graphs for disk read/write speeds\",\n\t\t\t\t\"instead of used/free percentage meters.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"io_graph_combined\",\n\t\t\t\t\"Toggle combined read and write graphs.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Only has effect if \\\"io mode\\\" is True.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"io_graph_speeds\",\n\t\t\t\t\"Set top speeds for the io graphs.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Manually set which speed in MiB/s that\",\n\t\t\t\t\"equals 100 percent in the io graphs.\",\n\t\t\t\t\"(100 MiB/s by default).\",\n\t\t\t\t\"\",\n\t\t\t\t\"Format: \\\"device:speed\\\" separate disks with\",\n\t\t\t\t\"whitespace \\\" \\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"Example: \\\"/dev/sda:100, /dev/sdb:20\\\".\"},\n\t\t\t{\"show_swap\",\n\t\t\t\t\"If swap memory should be shown in memory box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"swap_disk\",\n\t\t\t\t\"Show swap as a disk.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Ignores show_swap value above.\",\n\t\t\t\t\"Inserts itself after first disk.\"},\n\t\t\t{\"only_physical\",\n\t\t\t\t\"Filter out non physical disks.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Set this to False to include network disks,\",\n\t\t\t\t\"RAM disks and similar.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"use_fstab\",\n\t\t\t\t\"(Linux) Read disks list from /etc/fstab.\",\n\t\t\t\t\"\",\n\t\t\t\t\"This also disables only_physical.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"zfs_hide_datasets\",\n\t\t\t\t\"(Linux) Hide ZFS datasets in disks list.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Setting this to True will hide all datasets,\",\n\t\t\t\t\"and only show ZFS pools.\",\n\t\t\t\t\"\",\n\t\t\t\t\"(IO stats will be calculated per-pool)\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"disk_free_priv\",\n\t\t\t\t\"(Linux) Type of available disk space.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Set to true to show how much disk space is\",\n\t\t\t\t\"available for privileged users.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Set to false to show available for normal\",\n\t\t\t\t\"users.\"},\n\t\t\t{\"disks_filter\",\n\t\t\t\t\"Optional filter for shown disks.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Should be full path of a mountpoint.\",\n\t\t\t\t\"Separate multiple values with\",\n\t\t\t\t\"whitespace \\\" \\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"Only disks matching the filter will be shown.\",\n\t\t\t\t\"Prepend \\033[3mexclude=\\033[23m to only show disks \",\n\t\t\t\t\"not matching the filter.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Examples:\",\n\t\t\t\t\"/boot /home/user\",\n\t\t\t\t\"exclude=/boot /home/user\"},\n\t\t\t{\"zfs_arc_cached\",\n\t\t\t\t\"(Linux) Count ZFS ARC as cached memory.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Add ZFS ARC used to cached memory and\",\n\t\t\t\t\"ZFS ARC available to available memory.\",\n\t\t\t\t\"These are otherwise reported by the Linux\",\n\t\t\t\t\"kernel as used memory.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t},\n\t\t{\n\t\t\t{\"graph_symbol_net\",\n\t\t\t\t\"Graph symbol to use for graphs in net box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"default\\\", \\\"braille\\\", \\\"block\\\" or \\\"tty\\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"default\\\" for the general default symbol.\",},\n\t\t\t{\"swap_upload_download\",\n\t\t\t\t\"Swap the positions of the upload and download\",\n\t\t\t\t\"graphs.\",\n\t\t\t\t\"\",\n\t\t\t\t\"This allows for a more \\\"intuitive\\\" view\",\n\t\t\t\t\"with download being down, on the bottom.\"},\n\t\t\t{\"net_download\",\n\t\t\t\t\"Fixed network graph download value.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Value in Mebibits, default \\\"100\\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"Can be toggled with auto button.\"},\n\t\t\t{\"net_upload\",\n\t\t\t\t\"Fixed network graph upload value.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Value in Mebibits, default \\\"100\\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"Can be toggled with auto button.\"},\n\t\t\t{\"net_auto\",\n\t\t\t\t\"Start in network graphs auto rescaling mode.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Ignores any values set above at start and\",\n\t\t\t\t\"rescales down to 10Kibibytes at the lowest.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"net_sync\",\n\t\t\t\t\"Network scale sync.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Syncs the scaling for download and upload to\",\n\t\t\t\t\"whichever currently has the highest scale.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"net_iface\",\n\t\t\t\t\"Network Interface.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Manually set the starting Network Interface.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Will otherwise automatically choose the NIC\",\n\t\t\t\t\"with the highest total download since boot.\"},\n\t\t    {\"base_10_bitrate\",\n\t\t\t    \"Base 10 bitrate\",\n\t\t\t    \"\",\n\t\t\t    \"True:  Use SI prefixes for bitrates\",\n\t\t\t    \"       (1000Kbps = 1Mbps)\",\n\t\t\t    \"False: Use binary prefixes for bitrates\",\n\t\t\t    \"       (1024Kibps = 1Mibps)\",\n\t\t\t    \"Auto:  Use the General -> Base 10 Sizes\",\n\t\t\t    \"       setting for bitrates\",\n\t\t\t    \"\",\n\t\t\t    \"True, False, or Auto\",},\n\t\t},\n\t\t{\n\t\t\t{\"proc_left\",\n\t\t\t\t\"Proc box location.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Show proc box on left side of screen\",\n\t\t\t\t\"instead of right.\"},\n\t\t\t{\"graph_symbol_proc\",\n\t\t\t\t\"Graph symbol to use for graphs in proc box.\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"default\\\", \\\"braille\\\", \\\"block\\\" or \\\"tty\\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"default\\\" for the general default symbol.\",},\n\t\t\t{\"proc_sorting\",\n\t\t\t\t\"Processes sorting option.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Possible values:\",\n\t\t\t\t\"\\\"pid\\\", \\\"program\\\", \\\"arguments\\\", \\\"threads\\\",\",\n\t\t\t\t\"\\\"user\\\", \\\"memory\\\", \\\"cpu lazy\\\" and\",\n\t\t\t\t\"\\\"cpu direct\\\".\",\n\t\t\t\t\"\",\n\t\t\t\t\"\\\"cpu lazy\\\" updates top process over time.\",\n\t\t\t\t\"\\\"cpu direct\\\" updates top process\",\n\t\t\t\t\"directly.\"},\n\t\t\t{\"proc_reversed\",\n\t\t\t\t\"Reverse processes sorting order.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"proc_tree\",\n\t\t\t\t\"Processes tree view.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Set true to show processes grouped by\",\n\t\t\t\t\"parents with lines drawn between parent\",\n\t\t\t\t\"and child process.\"},\n\t\t\t{\"proc_aggregate\",\n\t\t\t\t\"Aggregate child's resources in parent.\",\n\t\t\t\t\"\",\n\t\t\t\t\"In tree-view, include all child resources\",\n\t\t\t\t\"with the parent even while expanded.\"},\n\t\t\t{\"proc_colors\",\n\t\t\t\t\"Enable colors in process view.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False.\"},\n\t\t\t{\"proc_gradient\",\n\t\t\t\t\"Enable process view gradient fade.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Fades from top or current selection.\",\n\t\t\t\t\"Max fade value is equal to current themes\",\n\t\t\t\t\"\\\"inactive_fg\\\" color value.\"},\n\t\t\t{\"proc_per_core\",\n\t\t\t\t\"Process usage per core.\",\n\t\t\t\t\"\",\n\t\t\t\t\"If process cpu usage should be of the core\",\n\t\t\t\t\"it's running on or usage of the total\",\n\t\t\t\t\"available cpu power.\",\n\t\t\t\t\"\",\n\t\t\t\t\"If true and process is multithreaded\",\n\t\t\t\t\"cpu usage can reach over 100%.\"},\n\t\t\t{\"proc_mem_bytes\",\n\t\t\t\t\"Show memory as bytes in process list.\",\n\t\t\t\t\" \",\n\t\t\t\t\"Will show percentage of total memory\",\n\t\t\t\t\"if False.\"},\n\t\t\t{\"keep_dead_proc_usage\",\n\t\t\t\t\"Cpu and Mem usage for dead processes\",\n\t\t\t\t\"\",\n\t\t\t\t\"Set true if process should preserve the cpu\",\n\t\t\t\t\"and memory usage of when it died while\",\n\t\t\t\t\"paused.\"},\n\t\t\t{\"proc_cpu_graphs\",\n\t\t\t\t\"Show cpu graph for each process.\",\n\t\t\t\t\"\",\n\t\t\t\t\"True or False\"},\n\t\t\t{\"proc_filter_kernel\",\n\t\t\t\t\"(Linux) Filter kernel processes from output.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Set to 'True' to filter out internal\",\n\t\t\t\t\"processes started by the Linux kernel.\"},\n\t\t\t{\"proc_follow_detailed\",\n\t\t\t\t\"Follow selected process with detailed view\",\n\t\t\t\t\"\",\n\t\t\t\t\"If set to 'True' then when opening the\",\n\t\t\t\t\"detailed view, the process will be\",\n\t\t\t\t\"followed in the list. Pressing enter\",\n\t\t\t\t\"again will close the detailed view\",\n\t\t\t\t\"and stop following the process.\"},\n\t\t}\n\t};\n\n\tmsgBox::msgBox() {}\n\tmsgBox::msgBox(int width, int boxtype, const vector<string>& content, const std::string_view title)\n\t: width(width), boxtype(boxtype) {\n\t\tauto tty_mode = Config::getB(\"tty_mode\");\n\t\tauto rounded = Config::getB(\"rounded_corners\");\n\t\tconst auto& right_up = (tty_mode or not rounded ? Symbols::right_up : Symbols::round_right_up);\n\t\tconst auto& left_up = (tty_mode or not rounded ? Symbols::left_up : Symbols::round_left_up);\n\t\tconst auto& right_down = (tty_mode or not rounded ? Symbols::right_down : Symbols::round_right_down);\n\t\tconst auto& left_down = (tty_mode or not rounded ? Symbols::left_down : Symbols::round_left_down);\n\t\theight = content.size() + 7;\n\t\tx = Term::width / 2 - width / 2;\n\t\ty = Term::height/2 - height/2;\n\t\tif (boxtype == 2) selected = 1;\n\n\n\t\tbutton_left = left_up + Symbols::h_line * 6 + Mv::l(7) + Mv::d(2) + left_down + Symbols::h_line * 6 + Mv::l(7) + Mv::u(1) + Symbols::v_line;\n\t\tbutton_right = Symbols::v_line + Mv::l(7) + Mv::u(1) + Symbols::h_line * 6 + right_up + Mv::l(7) + Mv::d(2) + Symbols::h_line * 6 + right_down + Mv::u(2);\n\n\t\tbox_contents = Draw::createBox(x, y, width, height, Theme::c(\"hi_fg\"), true, title) + Mv::d(1);\n\t\tfor (const auto& line : content) {\n\t\t\tbox_contents += Mv::save + Mv::r(max((size_t)0, (width / 2) - (Fx::uncolor(line).size() / 2) - 1)) + line + Mv::restore + Mv::d(1);\n\t\t}\n\t}\n\n\tstring msgBox::operator()() {\n\t\tstring out;\n\t\tint pos = width / 2 - (boxtype == 0 ? 6 : 14);\n\t\tconst auto first_color = (selected == 0 ? Theme::c(\"hi_fg\") : Theme::c(\"div_line\"));\n\t\tout = Mv::d(1) + Mv::r(pos) + Fx::b + first_color + button_left + (selected == 0 ? Theme::c(\"title\") : Theme::c(\"main_fg\") + Fx::ub)\n\t\t\t+ (boxtype == 0 ? \"    Ok    \" : \"    Yes    \") + first_color + button_right;\n\t\tmouse_mappings[\"button1\"] = Input::Mouse_loc{y + height - 4, x + pos + 1, 3, 12 + (boxtype > 0 ? 1 : 0)};\n\t\tif (boxtype > 0) {\n\t\t\tconst auto second_color = (selected == 1 ? Theme::c(\"hi_fg\") : Theme::c(\"div_line\"));\n\t\t\tout += Mv::r(2) + second_color + button_left + (selected == 1 ? Theme::c(\"title\") : Theme::c(\"main_fg\") + Fx::ub)\n\t\t\t\t+ \"    No    \" + second_color + button_right;\n\t\t\tmouse_mappings[\"button2\"] = Input::Mouse_loc{y + height - 4, x + pos + 15 + (boxtype > 0 ? 1 : 0), 3, 12};\n\t\t}\n\t\treturn box_contents + out + Fx::reset;\n\t}\n\n\t//? Process input\n\tint msgBox::input(const string& key) {\n\t\tif (key.empty()) return Invalid;\n\n\t\tif (is_in(key, \"escape\", \"backspace\", \"q\") or key == \"button2\") {\n\t\t\treturn No_Esc;\n\t\t}\n\t\telse if (key == \"button1\" or (boxtype == 0 and str_to_upper(key) == \"O\")) {\n\t\t\treturn Ok_Yes;\n\t\t}\n\t\telse if (is_in(key, \"enter\", \"space\")) {\n\t\t\treturn selected + 1;\n\t\t}\n\t\telse if (boxtype == 0) {\n\t\t\treturn Invalid;\n\t\t}\n\t\telse if (str_to_upper(key) == \"Y\") {\n\t\t\treturn Ok_Yes;\n\t\t}\n\t\telse if (str_to_upper(key) == \"N\") {\n\t\t\treturn No_Esc;\n\t\t}\n\t\telse if (is_in(key, \"right\", \"tab\")) {\n\t\t\tif (++selected > 1) selected = 0;\n\t\t\treturn Select;\n\t\t}\n\t\telse if (is_in(key, \"left\", \"shift_tab\")) {\n\t\t\tif (--selected < 0) selected = 1;\n\t\t\treturn Select;\n\t\t}\n\n\t\treturn Invalid;\n\t}\n\n\tvoid msgBox::clear() {\n\t\tbox_contents.clear();\n\t\tbox_contents.shrink_to_fit();\n\t\tbutton_left.clear();\n\t\tbutton_left.shrink_to_fit();\n\t\tbutton_right.clear();\n\t\tbutton_right.shrink_to_fit();\n\t\tmouse_mappings.erase(\"button1\");\n\t\tmouse_mappings.erase(\"button2\");\n\t}\n\n\tenum menuReturnCodes {\n\t\tNoChange,\n\t\tChanged,\n\t\tClosed,\n\t\tSwitch\n\t};\n\n\tstatic int signalChoose(const string& key) {\n\t\tauto s_pid = (Config::getB(\"show_detailed\") and Config::getI(\"selected_pid\") == 0 ? Config::getI(\"detailed_pid\") : Config::getI(\"selected_pid\"));\n\t\tstatic int x{};\n\t\tstatic int y{};\n\t\tstatic int selected_signal = -1;\n\n\t\tif (bg.empty()) selected_signal = -1;\n\t\tauto& out = Global::overlay;\n\t\tint retval = Changed;\n\n\t\tif (redraw) {\n\t\t\tx = Term::width/2 - 40;\n\t\t\ty = Term::height/2 - 9;\n\t\t\tbg = Draw::createBox(x + 2, y, 78, 19, Theme::c(\"hi_fg\"), true, \"signals\");\n\t\t\tbg += Mv::to(y+2, x+3) + Theme::c(\"title\") + Fx::b + cjust(\"Send signal to PID \" + to_string(s_pid) + \" (\"\n\t\t\t\t+ uresize((s_pid == Config::getI(\"detailed_pid\") ? Proc::detailed.entry.name : Config::getS(\"selected_name\")), 30) + \")\", 76);\n\t\t}\n\t\telse if (is_in(key, \"escape\", \"q\")) {\n\t\t\treturn Closed;\n\t\t}\n\t\telse if (key.starts_with(\"button_\")) {\n\t\t\tif (int new_select = stoi(key.substr(7)); new_select == selected_signal)\n\t\t\t\tgoto ChooseEntering;\n\t\t\telse\n\t\t\t\tselected_signal = new_select;\n\t\t}\n\t\telse if (is_in(key, \"enter\", \"space\") and selected_signal >= 0) {\n\t\t\tChooseEntering:\n\t\t\tsignalKillRet = 0;\n\t\t\tif (s_pid < 1) {\n\t\t\t\tsignalKillRet = ESRCH;\n\t\t\t\tmenuMask.set(SignalReturn);\n\t\t\t}\n\t\t\telse if (kill(s_pid, selected_signal) != 0) {\n\t\t\t\tsignalKillRet = errno;\n\t\t\t\tmenuMask.set(SignalReturn);\n\t\t\t}\n\t\t\treturn Closed;\n\t\t}\n\t\telse if (key.size() == 1 and isdigit(key.at(0)) and selected_signal < 10) {\n\t\t\tselected_signal = std::min(std::stoi((selected_signal < 1 ? key : to_string(selected_signal) + key)), 64);\n\t\t}\n\t\telse if (key == \"backspace\" and selected_signal != -1) {\n\t\t\tselected_signal = (selected_signal < 10 ? -1 : selected_signal / 10);\n\t\t}\n\t\telse if (is_in(key, \"up\", \"k\") and selected_signal != 16) {\n\t\t\tif (selected_signal == 1) selected_signal = 31;\n\t\t\telse if (selected_signal < 6) selected_signal += 25;\n\t\t\telse {\n\t\t\t\tbool offset = (selected_signal > 16);\n\t\t\t\tselected_signal -= 5;\n\t\t\t\tif (selected_signal <= 16 and offset) selected_signal--;\n\t\t\t}\n\t\t}\n\t\telse if (is_in(key, \"down\", \"j\")) {\n\t\t\tif (selected_signal == 31) selected_signal = 1;\n\t\t\telse if (selected_signal < 1 or selected_signal == 16) selected_signal = 1;\n\t\t\telse if (selected_signal > 26) selected_signal -= 25;\n\t\t\telse {\n\t\t\t\tbool offset = (selected_signal < 16);\n\t\t\t\tselected_signal += 5;\n\t\t\t\tif (selected_signal >= 16 and offset) selected_signal++;\n\t\t\t\tif (selected_signal > 31) selected_signal = 31;\n\t\t\t}\n\t\t}\n\t\telse if (is_in(key, \"left\", \"h\") and selected_signal > 0 and selected_signal != 16) {\n\t\t\tif (--selected_signal < 1) selected_signal = 31;\n\t\t\telse if (selected_signal == 16) selected_signal--;\n\t\t}\n\t\telse if (is_in(key, \"right\", \"l\") and selected_signal <= 31 and selected_signal != 16) {\n\t\t\tif (++selected_signal > 31) selected_signal = 1;\n\t\t\telse if (selected_signal == 16) selected_signal++;\n\t\t}\n\t\telse {\n\t\t\tretval = NoChange;\n\t\t}\n\n\t\tif (retval == Changed) {\n\t\t\tint cy = y+4, cx = x+4;\n\t\t\tout = bg + Mv::to(cy++, x+3) + Theme::c(\"main_fg\") + Fx::ub\n\t\t\t\t+ rjust(\"Enter signal number: \", 48) + Theme::c(\"hi_fg\") + (selected_signal >= 0 ? to_string(selected_signal) : \"\") + Theme::c(\"main_fg\") + Fx::bl + \"█\" + Fx::ubl;\n\n\t\t\tauto sig_str = to_string(selected_signal);\n\t\t\tfor (int count = 0, i = 0; const auto& sig : P_Signals) {\n\t\t\t\tif (count == 0 or count == 16) { count++; continue; }\n\t\t\t\tif (i++ % 5 == 0) { ++cy; cx = x+4; }\n\t\t\t\tout += Mv::to(cy, cx);\n\t\t\t\tif (count == selected_signal) out += Theme::c(\"selected_bg\") + Theme::c(\"selected_fg\") + Fx::b + ljust(to_string(count), 3) + ljust('(' + sig + ')', 12) + Fx::reset;\n\t\t\t\telse out += Theme::c(\"hi_fg\") + ljust(to_string(count), 3) + Theme::c(\"main_fg\") + ljust('(' + sig + ')', 12);\n\t\t\t\tif (redraw) mouse_mappings[\"button_\" + to_string(count)] = {cy, cx, 1, 15};\n\t\t\t\tcount++;\n\t\t\t\tcx += 15;\n\t\t\t}\n\n\t\t\tcy++;\n\t\t\tout += Mv::to(++cy, x+3) + Fx::b + Theme::c(\"hi_fg\") + rjust( \"↑ ↓ ← →\", 33, true) + Theme::c(\"main_fg\") + Fx::ub + \" | To choose signal.\";\n\t\t\tout += Mv::to(++cy, x+3) + Fx::b + Theme::c(\"hi_fg\") + rjust(\"0-9\", 33) + Theme::c(\"main_fg\") + Fx::ub + \" | Enter manually.\";\n\t\t\tout += Mv::to(++cy, x+3) + Fx::b + Theme::c(\"hi_fg\") + rjust(\"ENTER\", 33) + Theme::c(\"main_fg\") + Fx::ub + \" | To send signal.\";\n\t\t\tmouse_mappings[\"enter\"] = {cy, x, 1, 73};\n\t\t\tout += Mv::to(++cy, x+3) + Fx::b + Theme::c(\"hi_fg\") + rjust(\"ESC or \\\"q\\\"\", 33) + Theme::c(\"main_fg\") + Fx::ub + \" | To abort.\";\n\t\t\tmouse_mappings[\"escape\"] = {cy, x, 1, 73};\n\n\t\t\tout += Fx::reset;\n\t\t}\n\n\t\treturn (redraw ? Changed : retval);\n\t}\n\n\tstatic int sizeError(const string& key) {\n\t\tif (redraw) {\n\t\t\tvector<string> cont_vec {\n\t\t\t\tFx::b + Theme::g(\"used\")[100] + \"Error:\" + Theme::c(\"main_fg\") + Fx::ub,\n\t\t\t\t\"Terminal size too small to\" + Fx::reset,\n\t\t\t\t\"display menu or box!\" + Fx::reset };\n\n\t\t\tmessageBox = Menu::msgBox{45, 0, cont_vec, \"error\"};\n\t\t\tGlobal::overlay = messageBox();\n\t\t}\n\n\t\tauto ret = messageBox.input(key);\n\t\tif (ret == msgBox::Ok_Yes or ret == msgBox::No_Esc) {\n\t\t\tmessageBox.clear();\n\t\t\treturn Closed;\n\t\t}\n\t\telse if (redraw) {\n\t\t\treturn Changed;\n\t\t}\n\t\treturn NoChange;\n\t}\n\n\tstatic int signalSend(const string& key) {\n\t\tauto s_pid = (Config::getB(\"show_detailed\") and Config::getI(\"selected_pid\") == 0 ? Config::getI(\"detailed_pid\") : Config::getI(\"selected_pid\"));\n\t\tif (s_pid == 0) return Closed;\n\t\tif (redraw) {\n\t\t\tatomic_wait(Runner::active);\n\t\t\tauto& p_name = (s_pid == Config::getI(\"detailed_pid\") ? Proc::detailed.entry.name : Config::getS(\"selected_name\"));\n\t\t\tvector<string> cont_vec = {\n\t\t\t\tFx::b + Theme::c(\"main_fg\") + \"Send signal: \" + Fx::ub + Theme::c(\"hi_fg\") + to_string(signalToSend)\n\t\t\t\t+ (signalToSend > 0 and signalToSend <= 32 ? Theme::c(\"main_fg\") + \" (\" + P_Signals.at(signalToSend) + ')' : \"\"),\n\n\t\t\t\tFx::b + Theme::c(\"main_fg\") + \"To PID: \" + Fx::ub + Theme::c(\"hi_fg\") + to_string(s_pid) + Theme::c(\"main_fg\") + \" (\"\n\t\t\t\t+ uresize(p_name, 16) + ')' + Fx::reset,\n\t\t\t};\n\t\t\tmessageBox = Menu::msgBox{50, 1, cont_vec, (signalToSend > 1 and signalToSend <= 32 and signalToSend != 17 ? P_Signals.at(signalToSend) : \"signal\")};\n\t\t\tGlobal::overlay = messageBox();\n\t\t}\n\t\tauto ret = messageBox.input(key);\n\t\tif (ret == msgBox::Ok_Yes) {\n\t\t\tsignalKillRet = 0;\n\t\t\tif (kill(s_pid, signalToSend) != 0) {\n\t\t\t\tsignalKillRet = errno;\n\t\t\t\tmenuMask.set(SignalReturn);\n\t\t\t}\n\t\t\tmessageBox.clear();\n\t\t\treturn Closed;\n\t\t}\n\t\telse if (ret == msgBox::No_Esc) {\n\t\t\tmessageBox.clear();\n\t\t\treturn Closed;\n\t\t}\n\t\telse if (ret == msgBox::Select) {\n\t\t\tGlobal::overlay = messageBox();\n\t\t\treturn Changed;\n\t\t}\n\t\telse if (redraw) {\n\t\t\treturn Changed;\n\t\t}\n\t\treturn NoChange;\n\t}\n\n\tstatic int signalReturn(const string& key) {\n\t\tif (redraw) {\n\t\t\tvector<string> cont_vec;\n\t\t\tcont_vec.push_back(Fx::b + Theme::g(\"used\")[100] + \"Failure:\" + Theme::c(\"main_fg\") + Fx::ub);\n\t\t\tif (signalKillRet == EINVAL) {\n\t\t\t\tcont_vec.push_back(\"Unsupported signal!\" + Fx::reset);\n\t\t\t}\n\t\t\telse if (signalKillRet == EPERM) {\n\t\t\t\tcont_vec.push_back(\"Insufficient permissions to send signal!\" + Fx::reset);\n\t\t\t}\n\t\t\telse if (signalKillRet == ESRCH) {\n\t\t\t\tcont_vec.push_back(\"Process not found!\" + Fx::reset);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcont_vec.push_back(\"Unknown error! (errno: \" + to_string(signalKillRet) + ')' + Fx::reset);\n\t\t\t}\n\n\t\t\tmessageBox = Menu::msgBox{50, 0, cont_vec, \"error\"};\n\t\t\tGlobal::overlay = messageBox();\n\t\t}\n\n\t\tauto ret = messageBox.input(key);\n\t\tif (ret == msgBox::Ok_Yes or ret == msgBox::No_Esc) {\n\t\t\tmessageBox.clear();\n\t\t\treturn Closed;\n\t\t}\n\t\telse if (redraw) {\n\t\t\treturn Changed;\n\t\t}\n\t\treturn NoChange;\n\t}\n\n\tstatic int mainMenu(const string& key) {\n\t\tenum MenuItems { Options, Help, Quit };\n\t\tstatic int y{};\n\t\tstatic int selected{};\n\t\tstatic vector<string> colors_selected;\n\t\tstatic vector<string> colors_normal;\n\t\tauto tty_mode = Config::getB(\"tty_mode\");\n\t\tif (bg.empty()) selected = 0;\n\t\tint retval = Changed;\n\n\t\tif (redraw) {\n\t\t\ty = Term::height/2 - 10;\n\t\t\tbg = Draw::banner_gen(y, 0, true);\n\t\t\tif (not tty_mode) {\n\t\t\t\tcolors_selected = {\n\t\t\t\t\tTheme::hex_to_color(Global::Banner_src.at(0).at(0)),\n\t\t\t\t\tTheme::hex_to_color(Global::Banner_src.at(2).at(0)),\n\t\t\t\t\tTheme::hex_to_color(Global::Banner_src.at(4).at(0))\n\t\t\t\t};\n\t\t\t\tcolors_normal = {\n\t\t\t\t\tTheme::hex_to_color(\"#CC\"),\n\t\t\t\t\tTheme::hex_to_color(\"#AA\"),\n\t\t\t\t\tTheme::hex_to_color(\"#80\")\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\telse if (is_in(key, \"escape\", \"q\", \"m\", \"mouse_click\")) {\n\t\t\treturn Closed;\n\t\t}\n\t\telse if (key.starts_with(\"button_\")) {\n\t\t\tif (int new_select = key.back() - '0'; new_select == selected)\n\t\t\t\tgoto MainEntering;\n\t\t\telse\n\t\t\t\tselected = new_select;\n\t\t}\n\t\telse if (is_in(key, \"enter\", \"space\")) {\n\t\t\tMainEntering:\n\t\t\tswitch (selected) {\n\t\t\t\tcase Options:\n\t\t\t\t\tmenuMask.set(Menus::Options);\n\t\t\t\t\tcurrentMenu = Menus::Options;\n\t\t\t\t\treturn Switch;\n\t\t\t\tcase Help:\n\t\t\t\t\tmenuMask.set(Menus::Help);\n\t\t\t\t\tcurrentMenu = Menus::Help;\n\t\t\t\t\treturn Switch;\n\t\t\t\tcase Quit:\n\t\t\t\t\tclean_quit(0);\n\t\t\t}\n\t\t}\n\t\telse if (is_in(key, \"down\", \"tab\", \"mouse_scroll_down\", \"j\")) {\n\t\t\tif (++selected > 2) selected = 0;\n\t\t}\n\t\telse if (is_in(key, \"up\", \"shift_tab\", \"mouse_scroll_up\", \"k\")) {\n\t\t\tif (--selected < 0) selected = 2;\n\t\t}\n\t\telse {\n\t\t\tretval = NoChange;\n\t\t}\n\n\t\tif (retval == Changed) {\n\t\t\tauto& out = Global::overlay;\n\t\t\tout = bg + Fx::reset + Fx::b;\n\t\t\tauto cy = y + 7;\n\t\t\tfor (const auto& i : iota(0, 3)) {\n\t\t\t\tif (tty_mode) out += (i == selected ? Theme::c(\"hi_fg\") : Theme::c(\"main_fg\"));\n\t\t\t\tconst auto& menu = (not tty_mode and i == selected ? menu_selected[i] : menu_normal[i]);\n\t\t\t\tconst auto& colors = (i == selected ? colors_selected : colors_normal);\n\t\t\t\tif (redraw) mouse_mappings[\"button_\" + to_string(i)] = {cy, Term::width/2 - menu_width[i]/2, 3, menu_width[i]};\n\t\t\t\tfor (int ic = 0; const auto& line : menu) {\n\t\t\t\t\tout += Mv::to(cy++, Term::width/2 - menu_width[i]/2) + (tty_mode ? \"\" : colors[ic++]) + line;\n\t\t\t\t}\n\t\t\t}\n\t\t\tout += Fx::reset;\n\t\t}\n\n\t\treturn (redraw ? Changed : retval);\n\t}\n\nstatic int optionsMenu(const string& key) {\n \t\tenum Predispositions { isBool, isInt, isString, is2D, isBrowsable, isEditable};\n\t\tstatic int y{};\n\t\tstatic int x{};\n\t\tstatic int height{};\n\t\tstatic int page{};\n\t\tstatic int pages{};\n\t\tstatic int selected{};\n\t\tstatic int select_max{};\n\t\tstatic int item_height{};\n\t\tstatic int selected_cat{};\n\t\tstatic int max_items{};\n\t\tstatic int last_sel{};\n\t\tstatic bool editing{};\n\t\tstatic Draw::TextEdit editor;\n\t\tstatic string warnings;\n\t\tstatic bitset<8> selPred;\n\t\tstatic const std::unordered_map<string, std::reference_wrapper<const vector<string>>> optionsList = {\n\t\t\t{\"color_theme\", std::cref(Theme::themes)},\n\t\t\t{\"log_level\", std::cref(Logger::log_levels)},\n\t\t\t{\"temp_scale\", std::cref(Config::temp_scales)},\n\t\t#ifdef __linux__\n\t\t\t{\"freq_mode\", std::cref(Config::freq_modes)},\n\t\t#endif\n\t\t\t{\"proc_sorting\", std::cref(Proc::sort_vector)},\n\t\t\t{\"graph_symbol\", std::cref(Config::valid_graph_symbols)},\n\t\t\t{\"graph_symbol_cpu\", std::cref(Config::valid_graph_symbols_def)},\n\t\t\t{\"graph_symbol_mem\", std::cref(Config::valid_graph_symbols_def)},\n\t\t\t{\"graph_symbol_net\", std::cref(Config::valid_graph_symbols_def)},\n\t\t\t{\"graph_symbol_proc\", std::cref(Config::valid_graph_symbols_def)},\n\t\t\t{\"cpu_graph_upper\", std::cref(Cpu::available_fields)},\n\t\t\t{\"cpu_graph_lower\", std::cref(Cpu::available_fields)},\n\t\t\t{\"cpu_sensor\", std::cref(Cpu::available_sensors)},\n\t\t\t{\"selected_battery\", std::cref(Config::available_batteries)},\n\t        {\"base_10_bitrate\", std::cref(Config::base_10_bitrate_values)},\n\t\t\t{\"disable_presets\", std::cref(Config::disable_preset_options)},\n\t\t#ifdef GPU_SUPPORT\n\t\t\t{\"show_gpu_info\", std::cref(Config::show_gpu_values)},\n\t\t\t{\"graph_symbol_gpu\", std::cref(Config::valid_graph_symbols_def)},\n\t\t#endif\n\t\t};\n\t\tauto tty_mode = Config::getB(\"tty_mode\");\n\t\tauto vim_keys = Config::getB(\"vim_keys\");\n\t\tif (max_items == 0) {\n\t\t\tfor (const auto& cat : categories) {\n\t\t\t\tif ((int)cat.size() > max_items) max_items = cat.size();\n\t\t\t}\n\t\t}\n\t\tif (bg.empty()) {\n\t\t\tpage = selected = selected_cat = last_sel = 0;\n\t\t\tredraw = true;\n\t\t\tTheme::updateThemes();\n\t\t}\n\t\tint retval = Changed;\n\t\tbool recollect{};\n\t\tbool screen_redraw{};\n\t\tbool theme_refresh{};\n\n\t\t//? Draw background if needed else process input\n\t\tif (redraw) {\n\t\t\tmouse_mappings.clear();\n\t\t\tselPred.reset();\n\t\t\ty = max(1, Term::height/2 - 3 - max_items);\n\t\t\tx = Term::width/2 - 39;\n\t\t\theight = min(Term::height - 7, max_items * 2 + 4);\n\t\t\tif (height % 2 != 0) height--;\n\t\t\tbg \t= Draw::banner_gen(y, 0, true)\n\t\t\t\t+ Draw::createBox(x, y + 6, 78, height, Theme::c(\"hi_fg\"), true, fmt::format(\"{}tab{}\", Theme::c(\"hi_fg\"), Theme::c(\"main_fg\")) + Symbols::right)\n\t\t\t\t+ Mv::to(y+8, x) + Theme::c(\"hi_fg\") + Symbols::div_left + Theme::c(\"div_line\") + Symbols::h_line * 29\n\t\t\t\t+ Symbols::div_up + Symbols::h_line * (78 - 32) + Theme::c(\"hi_fg\") + Symbols::div_right\n\t\t\t\t+ Mv::to(y+6+height - 1, x+30) + Symbols::div_down + Theme::c(\"div_line\");\n\t\t\tfor (const auto& i : iota(0, height - 4)) {\n\t\t\t\tbg += Mv::to(y+9 + i, x + 30) + Symbols::v_line;\n\t\t\t}\n\t\t}\n\t\telse if (not warnings.empty() and not key.empty()) {\n\t\t\tauto ret = messageBox.input(key);\n\t\t\tif (ret == msgBox::msgReturn::Ok_Yes or ret == msgBox::msgReturn::No_Esc) {\n\t\t\t\twarnings.clear();\n\t\t\t\tmessageBox.clear();\n\t\t\t}\n\t\t}\n\t\telse if (editing and not key.empty()) {\n\t\t\tif (is_in(key, \"escape\", \"mouse_click\")) {\n\t\t\t\teditor.clear();\n\t\t\t\tediting = false;\n\t\t\t}\n\t\t\telse if (key == \"enter\") {\n\t\t\t\tconst auto& option = categories[selected_cat][item_height * page + selected][0];\n\t\t\t\tif (selPred.test(isString) and Config::stringValid(option, editor.text)) {\n\t\t\t\t\tConfig::set(option, editor.text);\n\t\t\t\t\tif (option == \"custom_cpu_name\" or option.starts_with(\"custom_gpu_name\"))\n\t\t\t\t\t\tscreen_redraw = true;\n\t\t\t\t\telse if (is_in(option, \"shown_boxes\", \"presets\")) {\n\t\t\t\t\t\tscreen_redraw = true;\n\t\t\t\t\t\tConfig::current_preset.reset();\n\t\t\t\t\t}\n\t\t\t\t\telse if (option == \"clock_format\") {\n\t\t\t\t\t\tDraw::update_clock(true);\n\t\t\t\t\t\tscreen_redraw = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (option == \"cpu_core_map\") {\n\t\t\t\t\t\tatomic_wait(Runner::active);\n\t\t\t\t\t\tCpu::core_mapping = Cpu::get_core_mapping();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (selPred.test(isInt) and Config::intValid(option, editor.text)) {\n\t\t\t\t\tConfig::set(option, stoi(editor.text));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\twarnings = Config::validError;\n\n\t\t\t\teditor.clear();\n\t\t\t\tediting = false;\n\t\t\t}\n\t\t\telse if (not editor.command(key))\n\t\t\t\tretval = NoChange;\n\t\t}\n\t\telse if (key == \"mouse_click\") {\n\t\t\tconst auto [mouse_x, mouse_y] = Input::mouse_pos;\n\t\t\tif (mouse_x < x or mouse_x > x + 80 or mouse_y < y + 6 or mouse_y > y + 6 + height) {\n\t\t\t\treturn Closed;\n\t\t\t}\n\t\t\telse if (mouse_x < x + 30 and mouse_y > y + 8) {\n\t\t\t\tauto m_select = ceil((double)(mouse_y - y - 8) / 2) - 1;\n\t\t\t\tif (selected != m_select)\n\t\t\t\t\tselected = m_select;\n\t\t\t\telse if (selPred.test(isEditable))\n\t\t\t\t\tgoto mouseEnter;\n\t\t\t\telse retval = NoChange;\n\t\t\t}\n\t\t}\n\t\telse if (is_in(key, \"enter\", \"e\", \"E\") and selPred.test(isEditable)) {\n\t\t\tmouseEnter:\n\t\t\tconst auto& option = categories[selected_cat][item_height * page + selected][0];\n\t\t\teditor = Draw::TextEdit{Config::getAsString(option), selPred.test(isInt)};\n\t\t\tediting = true;\n\t\t\tmouse_mappings.clear();\n\t\t}\n\t\telse if (is_in(key, \"escape\", \"q\", \"o\", \"backspace\")) {\n\t\t\treturn Closed;\n\t\t}\n\t\telse if (is_in(key, \"down\", \"mouse_scroll_down\") or (vim_keys and key == \"j\")) {\n\t\t\tif (++selected > select_max or selected >= item_height) {\n\t\t\t\tif (page < pages - 1) page++;\n\t\t\t\telse if (pages > 1) page = 0;\n\t\t\t\tselected = 0;\n\t\t\t}\n\t\t}\n\t\telse if (is_in(key, \"up\", \"mouse_scroll_up\") or (vim_keys and key == \"k\")) {\n\t\t\tif (--selected < 0) {\n\t\t\t\tif (page > 0) page--;\n\t\t\t\telse if (pages > 1) page = pages - 1;\n\n\t\t\t\tselected = item_height - 1;\n\t\t\t}\n\t\t}\n\t\telse if (pages > 1 and key == \"page_down\") {\n\t\t\tif (++page >= pages) page = 0;\n\t\t\tselected = 0;\n\t\t\tlast_sel = -1;\n\t\t}\n\t\telse if (pages > 1 and key == \"page_up\") {\n\t\t\tif (--page < 0) page = pages - 1;\n\t\t\tselected = 0;\n\t\t\tlast_sel = -1;\n\t\t}\n\t\telse if (key == \"tab\") {\n\t\t\tif (++selected_cat >= (int)categories.size()) selected_cat = 0;\n\t\t\tpage = selected = 0;\n\t\t}\n\t\telse if (key == \"shift_tab\") {\n\t\t\tif (--selected_cat < 0) selected_cat = (int)categories.size() - 1;\n\t\t\tpage = selected = 0;\n\t\t}\n#ifdef GPU_SUPPORT\n\t\telse if (is_in(key, \"1\", \"2\", \"3\", \"4\", \"5\", \"6\") or key.starts_with(\"select_cat_\")) {\n#else\n\t\telse if (is_in(key, \"1\", \"2\", \"3\", \"4\", \"5\") or key.starts_with(\"select_cat_\")) {\n#endif\n\t\tselected_cat = key.back() - '0' - 1;\n\t\t\tpage = selected = 0;\n\t\t}\n\t\telse if (is_in(key, \"left\", \"right\") or (vim_keys and is_in(key, \"h\", \"l\"))) {\n\t\t\tconst auto& option = categories[selected_cat][item_height * page + selected][0];\n\t\t\tif (selPred.test(isInt)) {\n\t\t\t\tconst int mod = (option == \"update_ms\" ? 100 : 1);\n\t\t\t\tlong value = Config::getI(option);\n\t\t\t\tif (key == \"right\" or (vim_keys and key == \"l\")) value += mod;\n\t\t\t\telse value -= mod;\n\n\t\t\t\tif (Config::intValid(option, to_string(value)))\n\t\t\t\t\tConfig::set(option, static_cast<int>(value));\n\t\t\t\telse {\n\t\t\t\t\twarnings = Config::validError;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (selPred.test(isBool)) {\n\t\t\t\tConfig::flip(option);\n\t\t\t\tscreen_redraw = true;\n\n\t\t\t\t// Special handling for options that need additional action.\n\t\t\t\tif (option == \"truecolor\") {\n\t\t\t\t\ttheme_refresh = true;\n\t\t\t\t\tConfig::flip(\"lowcolor\");\n\t\t\t\t}\n\t\t\t#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__NetBSD__)\n\t\t\t\telse if (option == \"force_tty\" and not Term::current_tty.starts_with(\"/dev/tty\")) {\n\t\t\t#else\n\t\t\t\telse if (option == \"force_tty\") {\n\t\t\t#endif\n\t\t\t\t\ttheme_refresh = true;\n\t\t\t\t\tConfig::set(\"tty_mode\", Config::getB(\"force_tty\"));\n\t\t\t\t}\n\t\t\t\telse if (is_in(option, \"rounded_corners\", \"theme_background\"))\n\t\t\t\t\ttheme_refresh = true;\n\t\t\t\telse if (option == \"background_update\") {\n\t\t\t\t\tRunner::pause_output = false;\n\t\t\t\t}\n\t\t\t\telse if (option == \"base_10_sizes\") {\n\t\t\t\t\trecollect = true;\n\t\t\t\t}\n\t\t\t\telse if (option == \"save_config_on_exit\" and not Config::getB(\"save_config_on_exit\")) {\n\t\t\t\t\tconst bool old_write_new = Config::write_new;\n\t\t\t\t\tConfig::write_new = true;\n\t\t\t\t\tConfig::write();\n\t\t\t\t\tConfig::write_new = old_write_new;\n\t\t\t\t}\n\t\t\t\telse if (option == \"disable_mouse\") {\n\t\t\t\t\tconst auto is_mouse_enabled = !Config::getB(\"disable_mouse\");\n\t\t\t\t\tstd::cout << (is_mouse_enabled ? Term::mouse_on : Term::mouse_off) << std::flush;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (selPred.test(isBrowsable)) {\n\t\t\t\tauto& optList = optionsList.at(option).get();\n\t\t\t\tint i = v_index(optList, Config::getS(option));\n\n\t\t\t\tif ((key == \"right\" or (vim_keys and key == \"l\")) and ++i >= (int)optList.size()) i = 0;\n\t\t\t\telse if ((key == \"left\" or (vim_keys and key == \"h\")) and --i < 0) i = optList.size() - 1;\n\t\t\t\tConfig::set(option, optList.at(i));\n\n\t\t\t\tif (option == \"color_theme\")\n\t\t\t\t\ttheme_refresh = true;\n\t\t\t\telse if (option == \"log_level\") {\n\t\t\t\t\tLogger::set_log_level(optList.at(i));\n\t\t\t\t\tLogger::info(\"Logger set to {}\", optList.at(i));\n\t\t\t\t}\n\t\t\t\telse if (option == \"base_10_bitrate\") {\n\t\t\t\t    recollect = true;\n\t\t\t\t}\n\t\t\t\telse if (is_in(option, \"proc_sorting\", \"cpu_sensor\", \"show_gpu_info\") or option.starts_with(\"graph_symbol\") or option.starts_with(\"cpu_graph_\"))\n\t\t\t\t\tscreen_redraw = true;\n\t\t\t\telse if (option == \"disable_presets\" and optList.at(i) != \"Off\")\n\t\t\t\t\tConfig::current_preset.reset();\n\t\t\t}\n\t\t\telse\n\t\t\t\tretval = NoChange;\n\t\t}\n\t\telse {\n\t\t\tretval = NoChange;\n\t\t}\n\n\t\t//? Draw the menu\n\t\tif (retval == Changed) {\n\t\t\tConfig::unlock();\n\t\t\tauto& out = Global::overlay;\n\t\t\tout = bg;\n\t\t\titem_height = min((int)categories[selected_cat].size(), (int)floor((double)(height - 4) / 2));\n\t\t\tpages = ceil((double)categories[selected_cat].size() / item_height);\n\t\t\tif (page > pages - 1) page = pages - 1;\n\t\t\tselect_max = min(item_height - 1, (int)categories[selected_cat].size() - 1 - item_height * page);\n\t\t\tif (selected > select_max) {\n\t\t\t\tselected = select_max;\n\t\t\t}\n\n\t\t\t//? Get variable properties for currently selected option\n\t\t\tif (selPred.none() or last_sel != (selected_cat << 8) + selected) {\n\t\t\t\tselPred.reset();\n\t\t\t\tlast_sel = (selected_cat << 8) + selected;\n\t\t\t\tconst auto& selOption = categories[selected_cat][item_height * page + selected][0];\n\t\t\t\tif (Config::ints.contains(selOption))\n\t\t\t\t\tselPred.set(isInt);\n\t\t\t\telse if (Config::bools.contains(selOption))\n\t\t\t\t\tselPred.set(isBool);\n\t\t\t\telse\n\t\t\t\t\tselPred.set(isString);\n\n\t\t\t\tif (not selPred.test(isString))\n\t\t\t\t\tselPred.set(is2D);\n\t\t\t\telse if (optionsList.contains(selOption)) {\n\t\t\t\t\tselPred.set(isBrowsable);\n\t\t\t\t}\n\t\t\t\tif (not selPred.test(isBrowsable) and (selPred.test(isString) or selPred.test(isInt)))\n\t\t\t\t\tselPred.set(isEditable);\n\t\t\t}\n\n\t\t\t//? Category buttons\n\t\t\tout += Mv::to(y+7, x+4);\n\t\t#ifdef GPU_SUPPORT\n\t\t\tfor (int i = 0; const auto& m : {\"general\", \"cpu\", \"gpu\", \"mem\", \"net\", \"proc\"}) {\n\t\t#else\n\t\t\tfor (int i = 0; const auto& m : {\"general\", \"cpu\", \"mem\", \"net\", \"proc\"}) {\n\t\t#endif\n\t\t\t\tout += Fx::b + (i == selected_cat\n\t\t\t\t\t\t? Theme::c(\"hi_fg\") + '[' + Theme::c(\"title\") + m + Theme::c(\"hi_fg\") + ']'\n\t\t\t\t\t\t: Theme::c(\"hi_fg\") + to_string(i + 1) + Theme::c(\"title\") + m + ' ')\n\t\t\t\t#ifdef GPU_SUPPORT\n\t\t\t\t\t+ Mv::r(7);\n\t\t\t\t#else\n\t\t\t\t\t+ Mv::r(10);\n\t\t\t\t#endif\n\n#if !defined(GPU_SUPPORT)\n\t\t\t\tconstexpr static auto option_menu_tab_width = 15;\n#else\n\t\t\t\tconstexpr static auto option_menu_tab_width = 12;\n#endif\n\t\t\t\tif (const auto button_name = fmt::format(\"select_cat_{}\", i + 1); not editing and not mouse_mappings.contains(button_name)) {\n\t\t\t\t\tmouse_mappings[button_name] = {\n\t\t\t\t\t\t.line = y + 6,\n\t\t\t\t\t\t.col = x + 2 + (option_menu_tab_width * i),\n\t\t\t\t\t\t.height = 3,\n\t\t\t\t\t\t.width = option_menu_tab_width,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tif (pages > 1) {\n\t\t\t\tout += Mv::to(y+6 + height - 1, x+2) + Theme::c(\"hi_fg\") + Symbols::title_left_down + Fx::b + Symbols::up + Theme::c(\"title\") + \" page \"\n\t\t\t\t\t+ to_string(page+1) + '/' + to_string(pages) + ' ' + Theme::c(\"hi_fg\") + Symbols::down + Fx::ub + Symbols::title_right_down;\n\t\t\t}\n\t\t\t//? Option name and value\n\t\t\tauto cy = y+9;\n\t\t\tfor (int c = 0, i = max(0, item_height * page); c++ < item_height and i < (int)categories[selected_cat].size(); i++) {\n\t\t\t\tconst auto& option = categories[selected_cat][i][0];\n\t\t\t\tconst auto& value = (option == \"color_theme\" ? fs::path(Config::getS(\"color_theme\")).stem().string() : Config::getAsString(option));\n\n\t\t\t\tout += Mv::to(cy++, x + 1) + (c-1 == selected ? Theme::c(\"selected_bg\") + Theme::c(\"selected_fg\") : Theme::c(\"title\"))\n\t\t\t\t\t+ Fx::b + cjust(capitalize(s_replace(option, \"_\", \" \"))\n\t\t\t\t\t\t+ (c-1 == selected and selPred.test(isBrowsable)\n\t\t\t\t\t\t\t? ' ' + to_string(v_index(optionsList.at(option).get(), (option == \"color_theme\" ? Config::getS(\"color_theme\") : value)) + 1) + '/' + to_string(optionsList.at(option).get().size())\n\t\t\t\t\t\t\t: \"\"), 29);\n\t\t\t\tout\t+= Mv::to(cy++, x + 1) + (c-1 == selected ? \"\" : Theme::c(\"main_fg\")) + Fx::ub + \"  \"\n\t\t\t\t\t+ (c-1 == selected and editing ? cjust(editor(24), 34, true) : cjust(value, 25, true)) + \"  \";\n\n\t\t\t\tif (c-1 == selected) {\n\t\t\t\t\tif (not editing and (selPred.test(is2D) or selPred.test(isBrowsable))) {\n\t\t\t\t\t\tout += Fx::b + Mv::to(cy-1, x+2) + Symbols::left + Mv::to(cy-1, x+28) + Symbols::right;\n\t\t\t\t\t\tmouse_mappings[\"left\"] = {cy-2, x, 2, 5};\n\t\t\t\t\t\tmouse_mappings[\"right\"] = {cy-2, x+25, 2, 5};\n\t\t\t\t\t}\n\t\t\t\t\tif (selPred.test(isEditable)) {\n\t\t\t\t\t\tout += Fx::b + Mv::to(cy-1, x+28 - (not editing and selPred.test(isInt) ? 2 : 0)) + (tty_mode ? \"E\" : Symbols::enter);\n\t\t\t\t\t}\n\t\t\t\t\t//? Description of selected option\n\t\t\t\t\tout += Fx::reset + Theme::c(\"title\") + Fx::b;\n\t\t\t\t\tfor (int cyy = y+7; const auto& desc : categories[selected_cat][i]) {\n\t\t\t\t\t\tif (cyy++ == y+7) continue;\n\t\t\t\t\t\telse if (cyy == y+10) out += Theme::c(\"main_fg\") + Fx::ub;\n\t\t\t\t\t\telse if (cyy > y + height + 4) break;\n\t\t\t\t\t\tout += Mv::to(cyy, x+32) + desc;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (not warnings.empty()) {\n\t\t\t\tmessageBox = msgBox{min(78, (int)ulen(warnings) + 10), msgBox::BoxTypes::OK, {uresize(warnings, 74)}, \"warning\"};\n\t\t\t\tout += messageBox();\n\t\t\t}\n\n\t\t\tout += Fx::reset;\n\t\t}\n\n\t\tif (theme_refresh) {\n\t\t\tTheme::setTheme();\n\t\t\tDraw::banner_gen(0, 0, false, true);\n\t\t\tscreen_redraw = true;\n\t\t\tredraw = true;\n\t\t\toptionsMenu(\"\");\n\t\t}\n\t\tif (screen_redraw) {\n\t\t\tauto overlay_bkp = std::move(Global::overlay);\n\t\t\tauto clock_bkp = std::move(Global::clock);\n\t\t\tDraw::calcSizes();\n\t\t\tGlobal::overlay = std::move(overlay_bkp);\n\t\t\tGlobal::clock = std::move(clock_bkp);\n\t\t\trecollect = true;\n\t\t}\n\t\tif (recollect) {\n\t\t\tRunner::run(\"all\", false, true);\n\t\t\tretval = NoChange;\n\t\t}\n\n\t\treturn (redraw ? Changed : retval);\n\t}\n\n\tstatic int helpMenu(const string& key) {\n\t\tstatic int y{};\n\t\tstatic int x{};\n\t\tstatic int height{};\n\t\tstatic int page{};\n\t\tstatic int pages{};\n\n\t\tif (bg.empty()) page = 0;\n\t\tint retval = Changed;\n\n\t\tif (redraw) {\n\t\t\ty = max(1, Term::height/2 - 4 - (int)(help_text.size() / 2));\n\t\t\tx = Term::width/2 - 39;\n\t\t\theight = min(Term::height - 6, (int)help_text.size() + 3);\n\t\t\tpages = ceil((double)help_text.size() / (height - 3));\n\t\t\tpage = 0;\n\t\t\tbg = Draw::banner_gen(y, 0, true);\n\t\t\tbg += Draw::createBox(x, y + 6, 78, height, Theme::c(\"hi_fg\"), true, \"help\");\n\t\t}\n\t\telse if (is_in(key, \"escape\", \"q\", \"h\", \"backspace\", \"space\", \"enter\", \"mouse_click\")) {\n\t\t\treturn Closed;\n\t\t}\n\t\telse if (pages > 1 and is_in(key, \"down\", \"j\", \"page_down\", \"tab\", \"mouse_scroll_down\")) {\n\t\t\tif (++page >= pages) page = 0;\n\t\t}\n\t\telse if (pages > 1 and is_in(key, \"up\", \"k\", \"page_up\", \"shift_tab\", \"mouse_scroll_up\")) {\n\t\t\tif (--page < 0) page = pages - 1;\n\t\t}\n\t\telse {\n\t\t\tretval = NoChange;\n\t\t}\n\n\n\t\tif (retval == Changed) {\n\t\t\tauto& out = Global::overlay;\n\t\t\tout = bg;\n\t\t\tif (pages > 1) {\n\t\t\t\tout += Mv::to(y+height+6, x + 2) + Theme::c(\"hi_fg\") + Symbols::title_left_down + Fx::b + Symbols::up + Theme::c(\"title\") + \" page \"\n\t\t\t\t\t+ to_string(page+1) + '/' + to_string(pages) + ' ' + Theme::c(\"hi_fg\") + Symbols::down + Fx::ub + Symbols::title_right_down;\n\t\t\t}\n\t\t\tauto cy = y+7;\n\t\t\tout += Mv::to(cy++, x + 1) + Theme::c(\"title\") + Fx::b + cjust(\"Key:\", 20) + \"Description:\";\n\t\t\tfor (int c = 0, i = max(0, (height - 3) * page); c++ < height - 3 and i < (int)help_text.size(); i++) {\n\t\t\t\tout += Mv::to(cy++, x + 1) + Theme::c(\"hi_fg\") + Fx::b + cjust(help_text[i][0], 20)\n\t\t\t\t\t+ Theme::c(\"main_fg\") + Fx::ub + help_text[i][1];\n\t\t\t}\n\t\t\tout += Fx::reset;\n\t\t}\n\n\n\t\treturn (redraw ? Changed : retval);\n\t}\n\n\tstatic int reniceMenu(const string& key) {\n\t\tauto s_pid = (Config::getB(\"show_detailed\") and Config::getI(\"selected_pid\") == 0 ? Config::getI(\"detailed_pid\") : Config::getI(\"selected_pid\"));\n\t\tstatic int x{};\n\t\tstatic int y{};\n\t\tstatic int selected_nice = 0;\n\t\tstatic string nice_edit;\n\n\t\tif (bg.empty()) {\n\t\t\tselected_nice = 0;\n\t\t\tnice_edit.clear();\n\t\t}\n\t\tauto& out = Global::overlay;\n\t\tint retval = Changed;\n\n\t\tif (redraw) {\n\t\t\tx = Term::width/2 - 25;\n\t\t\ty = Term::height/2 - 6;\n\t\t\tbg = Draw::createBox(x + 2, y, 50, 13, Theme::c(\"hi_fg\"), true, \"renice\");\n\t\t\tbg += Mv::to(y+2, x+3) + Theme::c(\"title\") + Fx::b + cjust(\"Renice PID \" + to_string(s_pid) + \" (\"\n\t\t\t\t+ uresize((s_pid == Config::getI(\"detailed_pid\") ? Proc::detailed.entry.name : Config::getS(\"selected_name\")), 15) + \")\", 48);\n\t\t}\n\t\telse if (is_in(key, \"escape\", \"q\")) {\n\t\t\treturn Closed;\n\t\t}\n\t\telse if (is_in(key, \"enter\", \"space\")) {\n\t\t\tif (s_pid > 0) {\n\t\t\t\tif (not nice_edit.empty()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tselected_nice = stoi(nice_edit);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (...) { selected_nice = 0; }\n\t\t\t\t}\n\t\t\t\tif (not Proc::set_priority(s_pid, selected_nice)) {\n\t\t\t\t\t// TODO: show error message\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Closed;\n\t\t}\n\t\telse if (key.size() == 1 and (isdigit(key.at(0)) or (key.at(0) == '-' and nice_edit.empty()))) {\n\t\t\tnice_edit += key;\n\t\t}\n\t\telse if (key == \"backspace\" and not nice_edit.empty()) {\n\t\t\tnice_edit.pop_back();\n\t\t}\n\t\telse if (is_in(key, \"up\", \"k\")) {\n\t\t\tif (++selected_nice > 19) selected_nice = -20;\n\t\t\tnice_edit.clear();\n\t\t}\n\t\telse if (is_in(key, \"down\", \"j\")) {\n\t\t\tif (--selected_nice < -20) selected_nice = 19;\n\t\t\tnice_edit.clear();\n\t\t}\n\t\telse if (is_in(key, \"left\", \"h\")) {\n\t\t\tif ((selected_nice -= 5) < -20) selected_nice += 40;\n\t\t\tnice_edit.clear();\n\t\t}\n\t\telse if (is_in(key, \"right\", \"l\")) {\n\t\t\tif ((selected_nice += 5) > 19) selected_nice -= 40;\n\t\t\tnice_edit.clear();\n\t\t}\n\t\telse {\n\t\t\tretval = NoChange;\n\t\t}\n\n\t\tif (retval == Changed) {\n\t\t\tint cy = y+4;\n\t\t\tif (not nice_edit.empty()) {\n\t\t\t\ttry {\n\t\t\t\t\tselected_nice = stoi(nice_edit);\n\t\t\t\t}\n\t\t\t\tcatch (...) { selected_nice = 0; }\n\t\t\t}\n\t\t\tout = bg + Mv::to(cy++, x+3) + Theme::c(\"main_fg\") + Fx::ub\n\t\t\t\t+ rjust(\"Enter nice value: \", 30) + Theme::c(\"hi_fg\") + (nice_edit.empty() ? to_string(selected_nice) : nice_edit) + Theme::c(\"main_fg\") + Fx::bl + \"█\" + Fx::ubl;\n\n\t\t\tcy++;\n\t\t\tout += Mv::to(++cy, x+3) + Fx::b + Theme::c(\"hi_fg\") + rjust( \"↑ ↓\", 20, true) + Theme::c(\"main_fg\") + Fx::ub + \" | To change value.\";\n\t\t\tout += Mv::to(++cy, x+3) + Fx::b + Theme::c(\"hi_fg\") + rjust( \"← →\", 20, true) + Theme::c(\"main_fg\") + Fx::ub + \" | To change value by 5.\";\n\t\t\tout += Mv::to(++cy, x+3) + Fx::b + Theme::c(\"hi_fg\") + rjust(\"0-9\", 20) + Theme::c(\"main_fg\") + Fx::ub + \" | Enter manually.\";\n\t\t\tout += Mv::to(++cy, x+3) + Fx::b + Theme::c(\"hi_fg\") + rjust(\"ENTER\", 20) + Theme::c(\"main_fg\") + Fx::ub + \" | To set nice value.\";\n\t\t\tout += Mv::to(++cy, x+3) + Fx::b + Theme::c(\"hi_fg\") + rjust(\"ESC or 'q'\", 20) + Theme::c(\"main_fg\") + Fx::ub + \" | To abort.\";\n\n\t\t\tout += Fx::reset;\n\t\t}\n\n\t\treturn (redraw ? Changed : retval);\n\t}\n\n\t//* Add menus here and update enum Menus in header\n\tconst auto menuFunc = vector{\n\t\tref(sizeError),\n\t\tref(signalChoose),\n\t\tref(signalSend),\n\t\tref(signalReturn),\n\t\tref(optionsMenu),\n\t\tref(helpMenu),\n\t\tref(reniceMenu),\n\t\tref(mainMenu),\n\t};\n\tbitset<8> menuMask;\n\n\tvoid process(const std::string_view key) {\n\t\tif (menuMask.none()) {\n\t\t\tMenu::active = false;\n\t\t\tGlobal::overlay.clear();\n\t\t\tGlobal::overlay.shrink_to_fit();\n\t\t\tRunner::pause_output = false;\n\t\t\tbg.clear();\n\t\t\tbg.shrink_to_fit();\n\t\t\tcurrentMenu = -1;\n\t\t\tRunner::run(\"all\", true, true);\n\t\t\tmouse_mappings.clear();\n\t\t\treturn;\n\t\t}\n\n\t\tif (currentMenu < 0 or not menuMask.test(currentMenu)) {\n\t\t\tMenu::active = true;\n\t\t\tredraw = true;\n\t\t\tif (((menuMask.test(Main) or menuMask.test(Options) or menuMask.test(Help) or menuMask.test(SignalChoose))\n\t\t\tand (Term::width < 80 or Term::height < 24))\n\t\t\tor (Term::width < 50 or Term::height < 20)) {\n\t\t\t\tmenuMask.reset();\n\t\t\t\tmenuMask.set(SizeError);\n\t\t\t}\n\n\t\t\tfor (const auto& i : iota(0, (int)menuMask.size())) {\n\t\t\t\tif (menuMask.test(i)) currentMenu = i;\n\t\t\t}\n\n\t\t}\n\n\t\tauto retCode = menuFunc.at(currentMenu)(key.data());\n\t\tif (retCode == Closed) {\n\t\t\tmenuMask.reset(currentMenu);\n\t\t\tmouse_mappings.clear();\n\t\t\tbg.clear();\n\t\t\tRunner::pause_output = false;\n\t\t\tprocess();\n\t\t}\n\t\telse if (redraw) {\n\t\t\tredraw = false;\n\t\t\tRunner::run(\"all\", true, true);\n\t\t}\n\t\telse if (retCode == Changed)\n\t\t\tRunner::run(\"overlay\");\n\t\telse if (retCode == Switch) {\n\t\t\tRunner::pause_output = false;\n\t\t\tbg.clear();\n\t\t\tredraw = true;\n\t\t\tmouse_mappings.clear();\n\t\t\tprocess();\n\t\t}\n\t}\n\n\tvoid show(int menu, int signal) {\n\t\tmenuMask.set(menu);\n\t\tsignalToSend = signal;\n\t\tprocess();\n\t}\n}\n"
  },
  {
    "path": "src/btop_menu.hpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#pragma once\n\n#include <atomic>\n#include <bitset>\n#include <string>\n#include <string_view>\n#include <vector>\n\n#include \"btop_input.hpp\"\n\nusing std::atomic;\nusing std::bitset;\nusing std::string;\nusing std::vector;\n\nnamespace Menu {\n\n\textern atomic<bool> active;\n\textern string output;\n\textern int signalToSend;\n\textern bool redraw;\n\n\t//? line, col, height, width\n\textern std::unordered_map<string, Input::Mouse_loc> mouse_mappings;\n\n\t//* Creates a message box centered on screen\n\t//? Height of box is determined by size of content vector\n\t//? Boxtypes: 0 = OK button | 1 = YES and NO with YES selected | 2 = Same as 1 but with NO selected\n\t//? Strings in content vector is not checked for box width overflow\n\tclass msgBox {\n\t\tstring box_contents, button_left, button_right;\n\t\tint height{};\n\t\tint width{};\n\t\tint boxtype{};\n\t\tint selected{};\n\t\tint x{};\n\t\tint y{};\n\tpublic:\n\t\tenum BoxTypes { OK, YES_NO, NO_YES };\n\t\tenum msgReturn {\n\t\t\tInvalid,\n\t\t\tOk_Yes,\n\t\t\tNo_Esc,\n\t\t\tSelect\n\t\t};\n\t\tmsgBox();\n\t\tmsgBox(int width, int boxtype, const vector<string>& content, std::string_view title);\n\n\t\t//? Draw and return box as a string\n\t\tstring operator()();\n\n\t\t//? Process input and returns value from enum Ret\n\t\tint input(const string& key);\n\n\t\t//? Clears content vector and private strings\n\t\tvoid clear();\n        int getX() const { return x; }\n        int getY() const { return y; }\n\t};\n\n\textern bitset<8> menuMask;\n\n\t//* Enum for functions in vector menuFuncs\n\tenum Menus {\n\t\tSizeError,\n\t\tSignalChoose,\n\t\tSignalSend,\n\t\tSignalReturn,\n\t\tOptions,\n\t\tHelp,\n\t    Renice,\n\t\tMain\n\t};\n\n\t//* Handles redirection of input for menu functions and handles return codes\n\tvoid process(const std::string_view key = \"\");\n\n\t//* Show a menu from enum Menu::Menus\n\tvoid show(int menu, int signal=-1);\n\n}\n"
  },
  {
    "path": "src/btop_shared.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include <sys/resource.h>\n#include <filesystem>\n#include <fstream>\n#include <ranges>\n#include <regex>\n#include <string>\n\n#include \"btop_config.hpp\"\n#include \"btop_shared.hpp\"\n#include \"btop_tools.hpp\"\n\nnamespace fs = std::filesystem;\nnamespace rng = std::ranges;\nusing namespace Tools;\n\nnamespace Cpu {\n    std::optional<std::string> container_engine;\n\n\tstring trim_name(string name) {\n\t\tauto name_vec = ssplit(name);\n\n\t\tif ((name.contains(\"Xeon\") or v_contains(name_vec, \"Duo\"s)) and v_contains(name_vec, \"CPU\"s)) {\n\t\t\tauto cpu_pos = v_index(name_vec, \"CPU\"s);\n\t\t\tif (cpu_pos < name_vec.size() - 1 and not name_vec.at(cpu_pos + 1).ends_with(')'))\n\t\t\t\tname = name_vec.at(cpu_pos + 1);\n\t\t\telse\n\t\t\t\tname.clear();\n\t\t} else if (v_contains(name_vec, \"Ryzen\"s)) {\n\t\t\tauto ryz_pos = v_index(name_vec, \"Ryzen\"s);\n\t\t\tname = \"Ryzen\";\n\t\t\tint tokens = 0;\n\t\t\tfor (auto i = ryz_pos + 1; i < name_vec.size() && tokens < 2; i++) {\n\t\t\t\tconst std::string& p = name_vec.at(i);\n\t\t\t\tif (p != \"AI\" && p != \"PRO\" && p != \"H\" && p != \"HX\")\n\t\t\t\t\ttokens++;\n\t\t\t\tname += \" \" + p;\n\t\t\t}\n\t\t} else if (name.contains(\"Intel\") and v_contains(name_vec, \"CPU\"s)) {\n\t\t\tauto cpu_pos = v_index(name_vec, \"CPU\"s);\n\t\t\tif (cpu_pos < name_vec.size() - 1 and not name_vec.at(cpu_pos + 1).ends_with(')') and name_vec.at(cpu_pos + 1) != \"@\")\n\t\t\t\tname = name_vec.at(cpu_pos + 1);\n\t\t\telse\n\t\t\t\tname.clear();\n\t\t} else\n\t\t\tname.clear();\n\n\t\tif (name.empty() and not name_vec.empty()) {\n\t\t\tfor (const auto &n : name_vec) {\n\t\t\t\tif (n == \"@\") break;\n\t\t\t\tname += n + ' ';\n\t\t\t}\n\t\t\tname.pop_back();\n\t\t\tfor (const auto& replace : {\"Processor\", \"CPU\", \"(R)\", \"(TM)\", \"Intel\", \"AMD\", \"Apple\", \"Core\"}) {\n\t\t\t\tname = s_replace(name, replace, \"\");\n\t\t\t\tname = s_replace(name, \"  \", \" \");\n\t\t\t}\n\t\t\tname = trim(name);\n\t\t}\n\n\t\treturn name;\n\t}\n}\n\n#ifdef GPU_SUPPORT\nnamespace Gpu {\n\tvector<string> gpu_names;\n\tvector<int> gpu_b_height_offsets;\n\tstd::unordered_map<string, deque<long long>> shared_gpu_percent = {\n\t\t{\"gpu-average\", {}},\n\t\t{\"gpu-vram-total\", {}},\n\t\t{\"gpu-pwr-total\", {}},\n\t};\n\tlong long gpu_pwr_total_max = 0;\n}\n#endif\n\nnamespace Proc {\nbool set_priority(pid_t pid, int priority) {\n  if (setpriority(PRIO_PROCESS, pid, priority) == 0) {\n    return true;\n  }\n  return false;\n}\n\n\tvoid proc_sorter(vector<proc_info>& proc_vec, const string& sorting, bool reverse, bool tree) {\n\t\tif (reverse) {\n\t\t\tswitch (v_index(sort_vector, sorting)) {\n\t\t\tcase 0: rng::stable_sort(proc_vec, rng::less{}, &proc_info::pid); \t\tbreak;\n\t\t\tcase 1: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::name);\t\tbreak;\n\t\t\tcase 2: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::cmd); \t\tbreak;\n\t\t\tcase 3: rng::stable_sort(proc_vec, rng::less{}, &proc_info::threads);\tbreak;\n\t\t\tcase 4: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::user); \t\tbreak;\n\t\t\tcase 5: rng::stable_sort(proc_vec, rng::less{}, &proc_info::mem); \t\tbreak;\n\t\t\tcase 6: rng::stable_sort(proc_vec, rng::less{}, &proc_info::cpu_p);\t\tbreak;\n\t\t\tcase 7: rng::stable_sort(proc_vec, rng::less{}, &proc_info::cpu_c);\t\tbreak;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tswitch (v_index(sort_vector, sorting)) {\n\t\t\tcase 0: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::pid); \t\tbreak;\n\t\t\tcase 1: rng::stable_sort(proc_vec, rng::less{}, &proc_info::name);\t\tbreak;\n\t\t\tcase 2: rng::stable_sort(proc_vec, rng::less{}, &proc_info::cmd); \t\tbreak;\n\t\t\tcase 3: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::threads);\tbreak;\n\t\t\tcase 4: rng::stable_sort(proc_vec, rng::less{}, &proc_info::user);\t\tbreak;\n\t\t\tcase 5: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::mem); \t\tbreak;\n\t\t\tcase 6: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::cpu_p);   \tbreak;\n\t\t\tcase 7: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::cpu_c);   \tbreak;\n\t\t\t}\n\t\t}\n\n\t\t//* When sorting with \"cpu lazy\" push processes over threshold cpu usage to the front regardless of cumulative usage\n\t\tif (not tree and not reverse and sorting == \"cpu lazy\") {\n\t\t\tdouble max = 10.0, target = 30.0;\n\t\t\tfor (size_t i = 0, x = 0, offset = 0; i < proc_vec.size(); i++) {\n\t\t\t\tif (i <= 5 and proc_vec.at(i).cpu_p > max)\n\t\t\t\t\tmax = proc_vec.at(i).cpu_p;\n\t\t\t\telse if (i == 6)\n\t\t\t\t\ttarget = (max > 30.0) ? max : 10.0;\n\t\t\t\tif (i == offset and proc_vec.at(i).cpu_p > 30.0)\n\t\t\t\t\toffset++;\n\t\t\t\telse if (proc_vec.at(i).cpu_p > target) {\n\t\t\t\t\trotate(proc_vec.begin() + offset, proc_vec.begin() + i, proc_vec.begin() + i + 1);\n\t\t\t\t\tif (++x > 10) break;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid tree_sort(vector<tree_proc>& proc_vec, const string& sorting, bool reverse, bool paused, int& c_index, const int index_max, bool collapsed) {\n\t\tif (proc_vec.size() > 1 and not paused) {\n\t\t\tif (reverse) {\n\t\t\t\tswitch (v_index(sort_vector, sorting)) {\n\t\t\t\tcase 3: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().threads < b.entry.get().threads; });\tbreak;\n\t\t\t\tcase 5: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().mem < b.entry.get().mem; });\tbreak;\n\t\t\t\tcase 6: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_p < b.entry.get().cpu_p; });\tbreak;\n\t\t\t\tcase 7: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_c < b.entry.get().cpu_c; });\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tswitch (v_index(sort_vector, sorting)) {\n\t\t\t\tcase 3: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().threads > b.entry.get().threads; });\tbreak;\n\t\t\t\tcase 5: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().mem > b.entry.get().mem; });\tbreak;\n\t\t\t\tcase 6: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_p > b.entry.get().cpu_p; });\tbreak;\n\t\t\t\tcase 7: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_c > b.entry.get().cpu_c; });\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (auto& r : proc_vec) {\n\t\t\tr.entry.get().tree_index = (collapsed or r.entry.get().filtered ? index_max : c_index++);\n\t\t\tif (not r.children.empty()) {\n\t\t\t\ttree_sort(r.children, sorting, reverse, paused, c_index, (collapsed or r.entry.get().collapsed or r.entry.get().tree_index == (size_t)index_max));\n\t\t\t}\n\t\t}\n\t}\n\n\tauto matches_filter(const proc_info& proc, const std::string& filter) -> bool {\n\t\tif (filter.starts_with(\"!\")) {\n\t\t\tif (filter.size() == 1) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// An incomplete regex throws, see issue https://github.com/aristocratos/btop/issues/1133\n\t\t\ttry {\n\t\t\t\tstd::regex regex { filter.substr(1), std::regex::extended };\n\t\t\t\treturn std::regex_search(std::to_string(proc.pid), regex) || std::regex_search(proc.name, regex) ||\n\t\t\t\t\t\t\t std::regex_match(proc.cmd, regex) || std::regex_search(proc.user, regex);\n\t\t\t} catch (std::regex_error& /* unused */) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn std::to_string(proc.pid).contains(filter) || s_contains_ic(proc.name, filter) ||\n\t\t\t\t\t s_contains_ic(proc.cmd, filter) || s_contains_ic(proc.user, filter);\n\t}\n\n\tvoid _tree_gen(proc_info& cur_proc, vector<proc_info>& in_procs, vector<tree_proc>& out_procs,\n\t\tint cur_depth, bool collapsed, const string& filter, bool found, bool no_update, bool should_filter) {\n\t\tbool filtering = false;\n\n\t\t//? If filtering, include children of matching processes\n\t\tif (not found and (should_filter or not filter.empty())) {\n\t\t\tif (!matches_filter(cur_proc, filter)) {\n\t\t\t\tfiltering = true;\n\t\t\t\tcur_proc.filtered = true;\n\t\t\t\tfilter_found++;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tfound = true;\n\t\t\t\tcur_depth = 0;\n\t\t\t}\n\t\t}\n\t\telse if (cur_proc.filtered) cur_proc.filtered = false;\n\n\t\tcur_proc.depth = cur_depth;\n\n\t\t//? Set tree index position for process if not filtered out or currently in a collapsed sub-tree\n\t\tout_procs.push_back({ cur_proc, {} });\n\t\tif (not collapsed and not filtering) {\n\t\t\tcur_proc.tree_index = out_procs.size() - 1;\n\n\t\t\t//? Try to find name of the binary file and append to program name if not the same\n\t\t\tif (cur_proc.short_cmd.empty() and not cur_proc.cmd.empty()) {\n\t\t\t\tstd::string_view cmd_view = cur_proc.cmd;\n\t\t\t\tcmd_view = cmd_view.substr((size_t)0, std::min(cmd_view.find(' '), cmd_view.size()));\n\t\t\t\tcmd_view = cmd_view.substr(std::min(cmd_view.find_last_of('/') + 1, cmd_view.size()));\n\t\t\t\tcur_proc.short_cmd = string{cmd_view};\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tcur_proc.tree_index = in_procs.size();\n\t\t}\n\n\t\t//? Recursive iteration over all children\n\t\tfor (auto& p : rng::equal_range(in_procs, cur_proc.pid, rng::less{}, &proc_info::ppid)) {\n\t\t\tif (collapsed and not filtering) {\n\t\t\t\tcur_proc.filtered = true;\n\t\t\t}\n\n\t\t\t_tree_gen(p, in_procs, out_procs.back().children, cur_depth + 1, (collapsed or cur_proc.collapsed), filter, found, no_update, should_filter);\n\n\t\t\tif (not no_update and not filtering and (collapsed or cur_proc.collapsed)) {\n\t\t\t\t//auto& parent = cur_proc;\n\t\t\t\tif (p.state != 'X') {\n\t\t\t\t\tcur_proc.cpu_p += p.cpu_p;\n\t\t\t\t\tcur_proc.cpu_c += p.cpu_c;\n\t\t\t\t\tcur_proc.mem += p.mem;\n\t\t\t\t\tcur_proc.threads += p.threads;\n\t\t\t\t}\n\t\t\t\tfilter_found++;\n\t\t\t\tp.filtered = true;\n\t\t\t}\n\t\t\telse if (Config::getB(\"proc_aggregate\") and p.state != 'X') {\n\t\t\t\tcur_proc.cpu_p += p.cpu_p;\n\t\t\t\tcur_proc.cpu_c += p.cpu_c;\n\t\t\t\tcur_proc.mem += p.mem;\n\t\t\t\tcur_proc.threads += p.threads;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid _collect_prefixes(tree_proc &t, const bool is_last, const string &header) {\n\t\tconst bool is_filtered = t.entry.get().filtered;\n\t\tif (is_filtered) t.entry.get().depth = 0;\n\n\t\tif (!t.children.empty()) t.entry.get().prefix = header + (t.entry.get().collapsed ? \"[+]─\": \"[-]─\");\n\t\telse t.entry.get().prefix = header + (is_last ? \" └─\": \" ├─\");\n\n\t\tfor (auto child = t.children.begin(); child != t.children.end(); ++child) {\n\t\t\t_collect_prefixes(*child, child == (t.children.end() - 1),\n\t\t\t\tis_filtered ? \"\": header + (is_last ? \"   \": \" │ \"));\n\t\t}\n\t}\n}\n\nauto detect_container() -> std::optional<std::string> {\n    std::error_code err;\n\n    if (fs::exists(fs::path(\"/run/.containerenv\"), err)) {\n        return std::make_optional(std::string { \"podman\" });\n    }\n    if (fs::exists(fs::path(\"/.dockerenv\"), err)) {\n        return std::make_optional(std::string { \"docker\" });\n    }\n    auto systemd_container = fs::path(\"/run/systemd/container\");\n    if (fs::exists(systemd_container, err)) {\n        auto stream = std::ifstream { systemd_container };\n        auto buf = std::string {};\n        stream >> buf;\n        return std::make_optional(buf);\n    }\n\n    return std::nullopt;\n}\n"
  },
  {
    "path": "src/btop_shared.hpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#pragma once\n\n#include <array>\n#include <atomic>\n#include <cstdint>\n#include <deque>\n#include <filesystem>\n#include <optional>\n#include <string>\n#include <string_view>\n#include <tuple>\n#include <unordered_map>\n#include <vector>\n\n#include <unistd.h>\n\n// From `man 3 getifaddrs`: <net/if.h> must be included before <ifaddrs.h>\n// clang-format off\n#include <net/if.h>\n#include <ifaddrs.h>\n// clang-format on\n\n#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)\n# include <kvm.h>\n#endif\n\nusing std::array;\nusing std::atomic;\nusing std::deque;\nusing std::string;\nusing std::tuple;\nusing std::vector;\n\nusing namespace std::literals; // for operator\"\"s\n\nvoid term_resize(bool force=false);\nvoid banner_gen();\n\nextern void clean_quit(int sig);\n\nnamespace Global {\n\textern const vector<array<string, 2>> Banner_src;\n\textern const string Version;\n\textern atomic<bool> quitting;\n\textern string exit_error_msg;\n\textern atomic<bool> thread_exception;\n\textern string banner;\n\textern atomic<bool> resized;\n\textern string overlay;\n\textern string clock;\n\textern uid_t real_uid, set_uid;\n\textern atomic<bool> init_conf;\n}\n\nnamespace Runner {\n\textern atomic<bool> active;\n\textern atomic<bool> reading;\n\textern atomic<bool> stopping;\n\textern atomic<bool> redraw;\n\textern atomic<bool> coreNum_reset;\n\textern bool pause_output;\n\textern string debug_bg;\n\n\tvoid run(const string& box = \"\", bool no_update = false, bool force_redraw = false);\n\tvoid stop();\n}\n\nnamespace Tools {\n\t//* Platform specific function for system_uptime (seconds since last restart)\n\tdouble system_uptime();\n}\n\nnamespace Shared {\n\t//* Initialize platform specific needed variables and check for errors\n\tvoid init();\n\n\textern long coreCount, page_size, clk_tck;\n\n#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)\n\tstruct KvmDeleter {\n\t\tvoid operator()(kvm_t* handle) {\n\t\t\tkvm_close(handle);\n\t\t}\n\t};\n\tusing KvmPtr = std::unique_ptr<kvm_t, KvmDeleter>;\n#endif\n}\n\n#if defined(GPU_SUPPORT)\n\nnamespace Gpu {\n\textern vector<string> box;\n\textern int width, total_height, min_width, min_height;\n\textern vector<int> x_vec, y_vec;\n\textern vector<bool> redraw;\n\textern int shown;\n\textern int count;\n\textern vector<int> shown_panels;\n\textern vector<string> gpu_names;\n\textern vector<int> gpu_b_height_offsets;\n\textern long long gpu_pwr_total_max;\n\n\textern std::unordered_map<string, deque<long long>> shared_gpu_percent; // averages, power/vram total\n\n\tconst array mem_names { \"used\"s, \"free\"s };\n\n\t//* Container for process information // TODO\n\t/*struct proc_info {\n    unsigned int pid;\n    unsigned long long mem;\n\t};*/\n\n\t//* Container for supported Gpu::*::collect() functions\n\tstruct gpu_info_supported {\n\t\tbool gpu_utilization = true,\n\t\t   \t mem_utilization = true,\n\t\t\t\t gpu_clock = true,\n\t\t\t\t mem_clock = true,\n\t\t\t\t pwr_usage = true,\n\t\t\t\t pwr_state = true,\n\t\t\t\t temp_info = true,\n\t\t\t\t mem_total = true,\n\t\t\t\t mem_used = true,\n\t\t\t\t pcie_txrx = true,\n\t\t\t\t encoder_utilization = true,\n\t\t\t\t decoder_utilization = true;\n\t};\n\n\t//* Per-device container for GPU info\n\tstruct gpu_info {\n\t\tstd::unordered_map<string, deque<long long>> gpu_percent = {\n\t\t\t{\"gpu-totals\", {}},\n\t\t\t{\"gpu-vram-totals\", {}},\n\t\t\t{\"gpu-pwr-totals\", {}},\n\t\t};\n\t\tunsigned int gpu_clock_speed; // MHz\n\n\t\tlong long pwr_usage; // mW\n\t\tlong long pwr_max_usage = 255000;\n\t\tlong long pwr_state;\n\n\t\tdeque<long long> temp = {0};\n\t\tlong long temp_max = 110;\n\n\t\tlong long mem_total = 0;\n\t\tlong long mem_used = 0;\n\t\tdeque<long long> mem_utilization_percent = {0}; // TODO: properly handle GPUs that can't report some stats\n\t\tlong long mem_clock_speed = 0; // MHz\n\n\t\tlong long pcie_tx = 0; // KB/s\n\t\tlong long pcie_rx = 0;\n\n\t\tlong long encoder_utilization = 0;\n\t\tlong long decoder_utilization = 0;\n\n\t\tgpu_info_supported supported_functions;\n\n\t\t// vector<proc_info> graphics_processes = {}; // TODO\n\t\t// vector<proc_info> compute_processes = {};\n\t};\n\n\tnamespace Nvml {\n\t\textern bool shutdown();\n\t}\n\tnamespace Rsmi {\n\t\textern bool shutdown();\n\t}\n\t#ifdef __APPLE__\n\tnamespace AppleSilicon {\n\t\textern bool shutdown();\n\t}\n\t#endif\n\n\t//* Collect gpu stats and temperatures\n    auto collect(bool no_update = false) -> vector<gpu_info>&;\n\n\t//* Draw contents of gpu box using <gpus> as source\n  \tstring draw(const gpu_info& gpu, unsigned long index, bool force_redraw, bool data_same);\n}\n\n#endif // GPU_SUPPORT\n\nnamespace Cpu {\n\textern string box;\n\textern int x, y, width, height, min_width, min_height;\n\textern bool shown, redraw, got_sensors, cpu_temp_only, has_battery, supports_watts;\n\textern string cpuName, cpuHz;\n\textern vector<string> available_fields;\n\textern vector<string> available_sensors;\n\textern tuple<int, float, long, string> current_bat;\n\textern std::optional<std::string> container_engine;\n\n\tstruct cpu_info {\n\t\tstd::unordered_map<string, deque<long long>> cpu_percent = {\n\t\t\t{\"total\", {}},\n\t\t\t{\"user\", {}},\n\t\t\t{\"nice\", {}},\n\t\t\t{\"system\", {}},\n\t\t\t{\"idle\", {}},\n\t\t\t{\"iowait\", {}},\n\t\t\t{\"irq\", {}},\n\t\t\t{\"softirq\", {}},\n\t\t\t{\"steal\", {}},\n\t\t\t{\"guest\", {}},\n\t\t\t{\"guest_nice\", {}}\n\t\t};\n\t\tvector<deque<long long>> core_percent;\n\t\tvector<deque<long long>> temp;\n\t\tlong long temp_max = 0;\n\t\tarray<double, 3> load_avg;\n\t\tfloat usage_watts = 0;\n\t\tstd::optional<std::vector<std::int32_t>> active_cpus;\n\t};\n\n\t//* Collect cpu stats and temperatures\n\tauto collect(bool no_update = false) -> cpu_info&;\n\n\t//* Draw contents of cpu box using <cpu> as source\n    string draw(\n\t\tconst cpu_info& cpu,\n#if defined(GPU_SUPPORT)\n\t\tconst vector<Gpu::gpu_info>& gpu,\n#endif\n\t\tbool force_redraw = false,\n\t\tbool data_same = false\n\t);\n\n\t//* Parse /proc/cpu info for mapping of core ids\n\tauto get_core_mapping() -> std::unordered_map<int, int>;\n\textern std::unordered_map<int, int> core_mapping;\n\n\tauto get_cpuHz() -> string;\n\n\t//* Get battery info from /sys\n\tauto get_battery() -> tuple<int, float, long, string>;\n\n\tstring trim_name(string);\n}\n\nnamespace Mem {\n\textern string box;\n\textern int x, y, width, height, min_width, min_height;\n\textern bool has_swap, shown, redraw;\n\tconst array mem_names { \"used\"s, \"available\"s, \"cached\"s, \"free\"s };\n\tconst array swap_names { \"swap_used\"s, \"swap_free\"s };\n\textern int disk_ios;\n\n\tstruct disk_info {\n\t\tstd::filesystem::path dev;\n\t\tstring name;\n\t\tstring fstype{};                // defaults to \"\"\n\t\tstd::filesystem::path stat{};   // defaults to \"\"\n\t\tint64_t total{};\n\t\tint64_t used{};\n\t\tint64_t free{};\n\t\tint used_percent{};\n\t\tint free_percent{};\n\n\t\tarray<int64_t, 3> old_io = {0, 0, 0};\n\t\tdeque<long long> io_read = {};\n\t\tdeque<long long> io_write = {};\n\t\tdeque<long long> io_activity = {};\n\t};\n\n\tstruct mem_info {\n\t\tstd::unordered_map<string, uint64_t> stats =\n\t\t\t{{\"used\", 0}, {\"available\", 0}, {\"cached\", 0}, {\"free\", 0},\n\t\t\t{\"swap_total\", 0}, {\"swap_used\", 0}, {\"swap_free\", 0}};\n\t\tstd::unordered_map<string, deque<long long>> percent =\n\t\t\t{{\"used\", {}}, {\"available\", {}}, {\"cached\", {}}, {\"free\", {}},\n\t\t\t{\"swap_total\", {}}, {\"swap_used\", {}}, {\"swap_free\", {}}};\n\t\tstd::unordered_map<string, disk_info> disks;\n\t\tvector<string> disks_order;\n\t};\n\n\t//?* Get total system memory\n\tuint64_t get_totalMem();\n\n\t//* Collect mem & disks stats\n\tauto collect(bool no_update = false) -> mem_info&;\n\n\t//* Draw contents of mem box using <mem> as source\n\tstring draw(const mem_info& mem, bool force_redraw = false, bool data_same = false);\n\n}\n\nnamespace Net {\n\textern string box;\n\textern int x, y, width, height, min_width, min_height;\n\textern bool shown, redraw;\n\textern string selected_iface;\n\textern vector<string> interfaces;\n\textern bool rescale;\n\textern std::unordered_map<string, uint64_t> graph_max;\n\n\tstruct net_stat {\n\t\tuint64_t speed{};\n\t\tuint64_t top{};\n\t\tuint64_t total{};\n\t\tuint64_t last{};\n\t\tuint64_t offset{};\n\t\tuint64_t rollover{};\n\t};\n\n\tstruct net_info {\n\t\tstd::unordered_map<string, deque<long long>> bandwidth = { {\"download\", {}}, {\"upload\", {}} };\n\t\tstd::unordered_map<string, net_stat> stat = { {\"download\", {}}, {\"upload\", {}} };\n\t\tstring ipv4{};      // defaults to \"\"\n\t\tstring ipv6{};      // defaults to \"\"\n\t\tbool connected{};\n\t};\n\n\tclass IfAddrsPtr {\n\t\tstruct ifaddrs* ifaddr;\n\t\tint status;\n\tpublic:\n\t\tIfAddrsPtr() { status = getifaddrs(&ifaddr); }\n\t\t~IfAddrsPtr() noexcept { freeifaddrs(ifaddr); }\n\t\tIfAddrsPtr(const IfAddrsPtr &) = delete;\n\t\tIfAddrsPtr& operator=(IfAddrsPtr& other) = delete;\n\t\tIfAddrsPtr(IfAddrsPtr &&) = delete;\n\t\tIfAddrsPtr& operator=(IfAddrsPtr&& other) = delete;\n\t\t[[nodiscard]] constexpr auto operator()() -> struct ifaddrs* { return ifaddr; }\n\t\t[[nodiscard]] constexpr auto get() -> struct ifaddrs* { return ifaddr; }\n\t\t[[nodiscard]] constexpr auto get_status() const noexcept -> int { return status; };\n\t};\n\n\textern std::unordered_map<string, net_info> current_net;\n\n\t//* Collect net upload/download stats\n\tauto collect(bool no_update=false) -> net_info&;\n\n\t//* Draw contents of net box using <net> as source\n\tstring draw(const net_info& net, bool force_redraw = false, bool data_same = false);\n}\n\nnamespace Proc {\n\textern atomic<int> numpids;\n\n\textern string box;\n\textern int x, y, width, height, min_width, min_height;\n\textern bool shown, redraw;\n\textern int select_max;\n\textern atomic<int> detailed_pid;\n\textern int selected_pid, start, selected, collapse, expand, filter_found, selected_depth, toggle_children;\n\textern int scroll_pos;\n\textern string selected_name;\n\textern atomic<bool> resized;\n\n\t//? Contains the valid sorting options for processes\n\tconst vector<string> sort_vector = {\n\t\t\"pid\",\n\t\t\"name\",\n\t\t\"command\",\n\t\t\"threads\",\n\t\t\"user\",\n\t\t\"memory\",\n\t\t\"cpu direct\",\n\t\t\"cpu lazy\",\n\t};\n\n\t//? Translation from process state char to explanative string\n\tconst std::unordered_map<char, string> proc_states = {\n\t\t{'R', \"Running\"},\n\t\t{'S', \"Sleeping\"},\n\t\t{'D', \"Waiting\"},\n\t\t{'Z', \"Zombie\"},\n\t\t{'T', \"Stopped\"},\n\t\t{'t', \"Tracing\"},\n\t\t{'X', \"Dead\"},\n\t\t{'x', \"Dead\"},\n\t\t{'K', \"Wakekill\"},\n\t\t{'W', \"Unknown\"},\n\t\t{'P', \"Parked\"}\n\t};\n\n\t//* Container for process information\n\tstruct proc_info {\n\t\tsize_t pid{};\n\t\tstring name{};          // defaults to \"\"\n\t\tstring cmd{};           // defaults to \"\"\n\t\tstring short_cmd{};     // defaults to \"\"\n\t\tsize_t threads{};\n\t\tint name_offset{};\n\t\tstring user{};          // defaults to \"\"\n\t\tuint64_t mem{};\n\t\tdouble cpu_p{};         // defaults to = 0.0\n\t\tdouble cpu_c{};         // defaults to = 0.0\n\t\tchar state = '0';\n\t\tint64_t p_nice{};\n\t\tuint64_t ppid{};\n\t\tuint64_t cpu_s{};\n\t\tuint64_t cpu_t{};\n\t\tuint64_t death_time{};\n\t\tstring prefix{};        // defaults to \"\"\n\t\tsize_t depth{};\n\t\tsize_t tree_index{};\n\t\tbool collapsed{};\n\t\tbool filtered{};\n\t};\n\n\t//* Container for process info box\n\tstruct detail_container {\n\t\tsize_t last_pid{};\n\t\tbool skip_smaps{};\n\t\tproc_info entry;\n\t\tstring elapsed, parent, status, io_read, io_write, memory;\n\t\tlong long first_mem = -1;\n\t\tdeque<long long> cpu_percent;\n\t\tdeque<long long> mem_bytes;\n\t};\n\n\t//? Contains all info for proc detailed box\n\textern detail_container detailed;\n\n\t//* Collect and sort process information from /proc\n\tauto collect(bool no_update = false) -> vector<proc_info>&;\n\n\t//* Update current selection and view, returns -1 if no change otherwise the current selection\n\tint selection(const std::string_view cmd_key);\n\n\t//* Draw contents of proc box using <plist> as data source\n\tstring draw(const vector<proc_info>& plist, bool force_redraw = false, bool data_same = false);\n\n\tstruct tree_proc {\n\t\tstd::reference_wrapper<proc_info> entry;\n\t\tvector<tree_proc> children;\n\t};\n\n\t//* Change priority (nice) of pid, returns true on success otherwise false\n\tbool set_priority(pid_t pid, int priority);\n\n\t//* Sort vector of proc_info's\n\tvoid proc_sorter(vector<proc_info>& proc_vec, const string& sorting, bool reverse, bool tree = false);\n\n\t//* Recursive sort of process tree\n\tvoid tree_sort(vector<tree_proc>& proc_vec, const string& sorting, bool reverse, bool paused,\n\t\t\t\t\tint& c_index, const int index_max, bool collapsed = false);\n\n\tauto matches_filter(const proc_info& proc, const std::string& filter) -> bool;\n\n\t//* Generate process tree list\n\tvoid _tree_gen(proc_info& cur_proc, vector<proc_info>& in_procs, vector<tree_proc>& out_procs,\n\t\t\t\t   int cur_depth, bool collapsed, const string& filter,\n\t\t\t\t   bool found = false, bool no_update = false, bool should_filter = false);\n\n\t//* Build prefixes for tree view\n\tvoid _collect_prefixes(tree_proc& t, bool is_last, const string &header = \"\");\n}\n\n/// Detect container engine.\nauto detect_container() -> std::optional<std::string>;\n"
  },
  {
    "path": "src/btop_theme.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include <cmath>\n#include <fstream>\n#include <unistd.h>\n\n#include \"btop_config.hpp\"\n#include \"btop_log.hpp\"\n#include \"btop_theme.hpp\"\n#include \"btop_tools.hpp\"\n\nusing std::round;\nusing std::stoi;\nusing std::to_string;\nusing std::vector;\nusing std::views::iota;\n\nusing namespace Tools;\n\nnamespace fs = std::filesystem;\n\nstring Term::fg, Term::bg;\nstring Fx::reset = reset_base;\n\nnamespace Theme {\n\n\tfs::path theme_dir;\n\tfs::path user_theme_dir;\n\tfs::path custom_theme_dir;\n\tvector<string> themes;\n\tstd::unordered_map<string, string> colors;\n\tstd::unordered_map<string, array<int, 3>> rgbs;\n\tstd::unordered_map<string, array<string, 101>> gradients;\n\n\tconst std::unordered_map<string, string> Default_theme = {\n\t\t{ \"main_bg\", \"#00\" },\n\t\t{ \"main_fg\", \"#cc\" },\n\t\t{ \"title\", \"#ee\" },\n\t\t{ \"hi_fg\", \"#b54040\" },\n\t\t{ \"selected_bg\", \"#6a2f2f\" },\n\t\t{ \"selected_fg\", \"#ee\" },\n\t\t{ \"inactive_fg\", \"#40\" },\n\t\t{ \"graph_text\", \"#60\" },\n\t\t{ \"meter_bg\", \"#40\" },\n\t\t{ \"proc_misc\", \"#0de756\" },\n\t\t{ \"cpu_box\", \"#556d59\" },\n\t\t{ \"mem_box\", \"#6c6c4b\" },\n\t\t{ \"net_box\", \"#5c588d\" },\n\t\t{ \"proc_box\", \"#805252\" },\n\t\t{ \"div_line\", \"#30\" },\n\t\t{ \"temp_start\", \"#4897d4\" },\n\t\t{ \"temp_mid\", \"#5474e8\" },\n\t\t{ \"temp_end\", \"#ff40b6\" },\n\t\t{ \"cpu_start\", \"#77ca9b\" },\n\t\t{ \"cpu_mid\", \"#cbc06c\" },\n\t\t{ \"cpu_end\", \"#dc4c4c\" },\n\t\t{ \"free_start\", \"#384f21\" },\n\t\t{ \"free_mid\", \"#b5e685\" },\n\t\t{ \"free_end\", \"#dcff85\" },\n\t\t{ \"cached_start\", \"#163350\" },\n\t\t{ \"cached_mid\", \"#74e6fc\" },\n\t\t{ \"cached_end\", \"#26c5ff\" },\n\t\t{ \"available_start\", \"#4e3f0e\" },\n\t\t{ \"available_mid\", \"#ffd77a\" },\n\t\t{ \"available_end\", \"#ffb814\" },\n\t\t{ \"used_start\", \"#592b26\" },\n\t\t{ \"used_mid\", \"#d9626d\" },\n\t\t{ \"used_end\", \"#ff4769\" },\n\t\t{ \"download_start\", \"#291f75\" },\n\t\t{ \"download_mid\", \"#4f43a3\" },\n\t\t{ \"download_end\", \"#b0a9de\" },\n\t\t{ \"upload_start\", \"#620665\" },\n\t\t{ \"upload_mid\", \"#7d4180\" },\n\t\t{ \"upload_end\", \"#dcafde\" },\n\t\t{ \"process_start\", \"#80d0a3\" },\n\t\t{ \"process_mid\", \"#dcd179\" },\n\t\t{ \"process_end\", \"#d45454\" },\n\t\t{ \"proc_pause_bg\", \"#b54040\" },\n\t\t{ \"proc_follow_bg\", \"#4040b5\"},\n\t\t{ \"proc_banner_bg\", \"#7b407b\"},\n\t\t{ \"proc_banner_fg\", \"#ee\"},\n\t\t{ \"followed_bg\", \"#4040b5\"},\n\t\t{ \"followed_fg\", \"#ee\"},\n\t};\n\n\tconst std::unordered_map<string, string> TTY_theme = {\n\t\t{ \"main_bg\", \"\\x1b[0;40m\" },\n\t\t{ \"main_fg\", \"\\x1b[37m\" },\n\t\t{ \"title\", \"\\x1b[97m\" },\n\t\t{ \"hi_fg\", \"\\x1b[91m\" },\n\t\t{ \"selected_bg\", \"\\x1b[41m\" },\n\t\t{ \"selected_fg\", \"\\x1b[97m\" },\n\t\t{ \"inactive_fg\", \"\\x1b[90m\" },\n\t\t{ \"graph_text\", \"\\x1b[90m\" },\n\t\t{ \"meter_bg\", \"\\x1b[90m\" },\n\t\t{ \"proc_misc\", \"\\x1b[92m\" },\n\t\t{ \"cpu_box\", \"\\x1b[32m\" },\n\t\t{ \"mem_box\", \"\\x1b[33m\" },\n\t\t{ \"net_box\", \"\\x1b[35m\" },\n\t\t{ \"proc_box\", \"\\x1b[31m\" },\n\t\t{ \"div_line\", \"\\x1b[90m\" },\n\t\t{ \"temp_start\", \"\\x1b[94m\" },\n\t\t{ \"temp_mid\", \"\\x1b[96m\" },\n\t\t{ \"temp_end\", \"\\x1b[95m\" },\n\t\t{ \"cpu_start\", \"\\x1b[92m\" },\n\t\t{ \"cpu_mid\", \"\\x1b[93m\" },\n\t\t{ \"cpu_end\", \"\\x1b[91m\" },\n\t\t{ \"free_start\", \"\\x1b[32m\" },\n\t\t{ \"free_mid\", \"\" },\n\t\t{ \"free_end\", \"\\x1b[92m\" },\n\t\t{ \"cached_start\", \"\\x1b[36m\" },\n\t\t{ \"cached_mid\", \"\" },\n\t\t{ \"cached_end\", \"\\x1b[96m\" },\n\t\t{ \"available_start\", \"\\x1b[33m\" },\n\t\t{ \"available_mid\", \"\" },\n\t\t{ \"available_end\", \"\\x1b[93m\" },\n\t\t{ \"used_start\", \"\\x1b[31m\" },\n\t\t{ \"used_mid\", \"\" },\n\t\t{ \"used_end\", \"\\x1b[91m\" },\n\t\t{ \"download_start\", \"\\x1b[34m\" },\n\t\t{ \"download_mid\", \"\" },\n\t\t{ \"download_end\", \"\\x1b[94m\" },\n\t\t{ \"upload_start\", \"\\x1b[35m\" },\n\t\t{ \"upload_mid\", \"\" },\n\t\t{ \"upload_end\", \"\\x1b[95m\" },\n\t\t{ \"process_start\", \"\\x1b[32m\" },\n\t\t{ \"process_mid\", \"\\x1b[33m\" },\n\t\t{ \"process_end\", \"\\x1b[31m\" },\n\t\t{ \"proc_pause_bg\", \"\\x1b[41m\" },\n\t\t{ \"proc_follow_bg\", \"\\x1b[44m\" },\n\t\t{ \"proc_banner_bg\", \"\\x1b[45m\" },\n\t\t{ \"proc_banner_fg\", \"\\x1b[97m\" },\n\t\t{ \"followed_bg\", \"\\x1b[44m\" },\n\t\t{ \"followed_fg\", \"\\x1b[97m\" },\n\t};\n\n\tnamespace {\n\t\t//* Convert 24-bit colors to 256 colors\n\t\tint truecolor_to_256(const int& r, const int& g, const int& b) {\n\t\t\t//? Use upper 232-255 greyscale values if the downscaled red, green and blue are the same value\n\t\t\tif (const int red = round((double)r / 11); red == round((double)g / 11) and red == round((double)b / 11)) {\n\t\t\t\treturn 232 + red;\n\t\t\t}\n\t\t\t//? Else use 6x6x6 color cube to calculate approximate colors\n\t\t\telse {\n\t\t\t\treturn round((double)r / 51) * 36 + round((double)g / 51) * 6 + round((double)b / 51) + 16;\n\t\t\t}\n\t\t}\n\t}\n\n\tstring hex_to_color(string hexa, bool t_to_256, const string& depth) {\n\t\tif (hexa.size() > 1) {\n\t\t\thexa.erase(0, 1);\n\t\t\tfor (auto& c : hexa) {\n\t\t\t\tif (not isxdigit(c)) {\n\t\t\t\t\tLogger::error(\"Invalid hex value: {}\", hexa);\n\t\t\t\t\treturn \"\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tstring pre = Fx::e + (depth == \"fg\" ? \"38\" : \"48\") + \";\" + (t_to_256 ? \"5;\" : \"2;\");\n\n\t\t\tif (hexa.size() == 2) {\n\t\t\t\tint h_int = stoi(hexa, nullptr, 16);\n\t\t\t\tif (t_to_256) {\n\t\t\t\t\treturn pre + to_string(truecolor_to_256(h_int, h_int, h_int)) + \"m\";\n\t\t\t\t} else {\n\t\t\t\t\tstring h_str = to_string(h_int);\n\t\t\t\t\treturn pre + h_str + \";\" + h_str + \";\" + h_str + \"m\";\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (hexa.size() == 6) {\n\t\t\t\tif (t_to_256) {\n\t\t\t\t\treturn pre + to_string(truecolor_to_256(\n\t\t\t\t\t\tstoi(hexa.substr(0, 2), nullptr, 16),\n\t\t\t\t\t\tstoi(hexa.substr(2, 2), nullptr, 16),\n\t\t\t\t\t\tstoi(hexa.substr(4, 2), nullptr, 16))) + \"m\";\n\t\t\t\t} else {\n\t\t\t\t\treturn pre +\n\t\t\t\t\t\tto_string(stoi(hexa.substr(0, 2), nullptr, 16)) + \";\" +\n\t\t\t\t\t\tto_string(stoi(hexa.substr(2, 2), nullptr, 16)) + \";\" +\n\t\t\t\t\t\tto_string(stoi(hexa.substr(4, 2), nullptr, 16)) + \"m\";\n\t\t\t\t}\n\t\t\t}\n\t\t\telse Logger::error(\"Invalid size of hex value: {}\", hexa);\n\t\t}\n\t\telse Logger::error(\"Hex value missing: {}\", hexa);\n\t\treturn \"\";\n\t}\n\n\tstring dec_to_color(int r, int g, int b, bool t_to_256, const string& depth) {\n\t\tstring pre = Fx::e + (depth == \"fg\" ? \"38\" : \"48\") + \";\" + (t_to_256 ? \"5;\" : \"2;\");\n\t\tr = std::clamp(r, 0, 255);\n\t\tg = std::clamp(g, 0, 255);\n\t\tb = std::clamp(b, 0, 255);\n\t\tif (t_to_256) return pre + to_string(truecolor_to_256(r, g, b)) + \"m\";\n\t\telse return pre + to_string(r) + \";\" + to_string(g) + \";\" + to_string(b) + \"m\";\n\t}\n\n\tnamespace {\n\t\t//* Convert hex color to a array of decimals\n\t\tarray<int, 3> hex_to_dec(string hexa) {\n\t\t\tif (hexa.size() > 1) {\n\t\t\t\thexa.erase(0, 1);\n\t\t\t\tfor (auto& c : hexa) {\n\t\t\t\t\tif (not isxdigit(c))\n\t\t\t\t\t\treturn array{-1, -1, -1};\n\t\t\t\t}\n\n\t\t\t\tif (hexa.size() == 2) {\n\t\t\t\t\tint h_int = stoi(hexa, nullptr, 16);\n\t\t\t\t\treturn array{h_int, h_int, h_int};\n\t\t\t\t}\n\t\t\t\telse if (hexa.size() == 6) {\n\t\t\t\t\t\treturn array{\n\t\t\t\t\t\t\tstoi(hexa.substr(0, 2), nullptr, 16),\n\t\t\t\t\t\t\tstoi(hexa.substr(2, 2), nullptr, 16),\n\t\t\t\t\t\t\tstoi(hexa.substr(4, 2), nullptr, 16)\n\t\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {-1 ,-1 ,-1};\n\t\t}\n\n\t\t//* Generate colors and rgb decimal vectors for the theme\n\t\tvoid generateColors(const std::unordered_map<string, string>& source) {\n\t\t\tvector<string> t_rgb;\n\t\t\tstring depth;\n\t\t\tbool t_to_256 = Config::getB(\"lowcolor\");\n\t\t\tcolors.clear(); rgbs.clear();\n\t\t\tfor (const auto& [name, color] : Default_theme) {\n\t\t\t\tif (name == \"main_bg\" and not Config::getB(\"theme_background\")) {\n\t\t\t\t\t\tcolors[name] = \"\\x1b[49m\";\n\t\t\t\t\t\trgbs[name] = {-1, -1, -1};\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tdepth = (name.ends_with(\"bg\") and name != \"meter_bg\") ? \"bg\" : \"fg\";\n\t\t\t\tif (source.contains(name)) {\n\t\t\t\t\tif (name == \"main_bg\" and source.at(name).empty()) {\n\t\t\t\t\t\tcolors[name] = \"\\x1b[49m\";\n\t\t\t\t\t\trgbs[name] = {-1, -1, -1};\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse if (source.at(name).empty() and (name.ends_with(\"_mid\") or name.ends_with(\"_end\"))) {\n\t\t\t\t\t\tcolors[name] = \"\";\n\t\t\t\t\t\trgbs[name] = {-1, -1, -1};\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\telse if (source.at(name).starts_with('#')) {\n\t\t\t\t\t\tcolors[name] = hex_to_color(source.at(name), t_to_256, depth);\n\t\t\t\t\t\trgbs[name] = hex_to_dec(source.at(name));\n\t\t\t\t\t}\n\t\t\t\t\telse if (not source.at(name).empty()) {\n\t\t\t\t\t\tt_rgb = ssplit(source.at(name));\n\t\t\t\t\t\tif (t_rgb.size() != 3) {\n\t\t\t\t\t\t\tLogger::error(\"Invalid RGB decimal value: \\\"{}\\\"\", source.at(name));\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcolors[name] = dec_to_color(stoi(t_rgb[0]), stoi(t_rgb[1]), stoi(t_rgb[2]), t_to_256, depth);\n\t\t\t\t\t\t\trgbs[name] = array{stoi(t_rgb[0]), stoi(t_rgb[1]), stoi(t_rgb[2])};\n\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (not colors.contains(name) and not is_in(name, \"meter_bg\", \"process_start\", \"process_mid\", \"process_end\", \"graph_text\")) {\n\t\t\t\t\tLogger::debug(\"Missing color value for \\\"{}\\\". Using value from default.\", name);\n\t\t\t\t\tcolors[name] = hex_to_color(color, t_to_256, depth);\n\t\t\t\t\trgbs[name] = hex_to_dec(color);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//? Set fallback values for optional colors not defined in theme file\n\t\t\tif (not colors.contains(\"meter_bg\")) {\n\t\t\t\tcolors[\"meter_bg\"] = colors.at(\"inactive_fg\");\n\t\t\t\trgbs[\"meter_bg\"] = rgbs.at(\"inactive_fg\");\n\t\t\t}\n\t\t\tif (not colors.contains(\"process_start\")) {\n\t\t\t\tcolors[\"process_start\"] = colors.at(\"cpu_start\");\n\t\t\t\tcolors[\"process_mid\"] = colors.at(\"cpu_mid\");\n\t\t\t\tcolors[\"process_end\"] = colors.at(\"cpu_end\");\n\t\t\t\trgbs[\"process_start\"] = rgbs.at(\"cpu_start\");\n\t\t\t\trgbs[\"process_mid\"] = rgbs.at(\"cpu_mid\");\n\t\t\t\trgbs[\"process_end\"] = rgbs.at(\"cpu_end\");\n\t\t\t}\n\t\t\tif (not colors.contains(\"graph_text\")) {\n\t\t\t\tcolors[\"graph_text\"] = colors.at(\"inactive_fg\");\n\t\t\t\trgbs[\"graph_text\"] = rgbs.at(\"inactive_fg\");\n\t\t\t}\n\t\t}\n\n\t\t//* Generate color gradients from two or three colors, 101 values indexed 0-100\n\t\tvoid generateGradients() {\n\t\t\tgradients.clear();\n\t\t\tbool t_to_256 = Config::getB(\"lowcolor\");\n\n\t\t\t//? Insert values for processes greyscale gradient and processes color gradient\n\t\t\trgbs.insert({\n\t\t\t\t{ \"proc_start\", \t\trgbs[\"main_fg\"]\t\t\t},\n\t\t\t\t{ \"proc_mid\", \t\t\t{-1, -1, -1}\t\t\t},\n\t\t\t\t{ \"proc_end\", \t\t\trgbs[\"inactive_fg\"]\t\t},\n\t\t\t\t{ \"proc_color_start\", \trgbs[\"inactive_fg\"]\t\t},\n\t\t\t\t{ \"proc_color_mid\", \t{-1, -1, -1}\t\t\t},\n\t\t\t\t{ \"proc_color_end\", \trgbs[\"process_start\"]\t},\n\t\t\t});\n\n\t\t\tfor (const auto& [name, source_arr] : rgbs) {\n\t\t\t\tif (not name.ends_with(\"_start\")) continue;\n\t\t\t\tconst string color_name { rtrim(name, \"_start\") };\n\n\t\t\t\t//? input_colors[start,mid,end][red,green,blue]\n\t\t\t\tconst array<array<int, 3>, 3> input_colors = {\n\t\t\t\t\tsource_arr,\n\t\t\t\t\trgbs[color_name + \"_mid\"],\n\t\t\t\t\trgbs[color_name + \"_end\"]\n\t\t\t\t};\n\n\t\t\t\t//? output_colors[red,green,blue][0-100]\n\t\t\t\tarray<array<int, 3>, 101> output_colors;\n\t\t\t\toutput_colors[0][0] = -1;\n\n\t\t\t\t//? Only start iteration if gradient has an end color defined\n\t\t\t\tif (input_colors[2][0] >= 0) {\n\n\t\t\t\t\t//? Split iteration in two passes of 50 + 51 instead of one pass of 101 if gradient has start, mid and end values defined\n\t\t\t\t\tint current_range = (input_colors[1][0] >= 0) ? 50 : 100;\n\t\t\t\t\tfor (int rgb : iota(0, 3)) {\n\t\t\t\t\t\tint start = 0, offset = 0;\n\t\t\t\t\t\tint end = (current_range == 50) ? 1 : 2;\n\t\t\t\t\t\tfor (int i : iota(0, 101)) {\n\t\t\t\t\t\t\toutput_colors[i][rgb] = input_colors[start][rgb] + (i - offset) * (input_colors[end][rgb] - input_colors[start][rgb]) / current_range;\n\n\t\t\t\t\t\t\t//? Switch source arrays from start->mid to mid->end at 50 passes if mid is defined\n\t\t\t\t\t\t\tif (i == current_range) { ++start; ++end; offset = 50; }\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? Generate color escape codes for the generated rgb decimals\n\t\t\t\tarray<string, 101> color_gradient;\n\t\t\t\tif (output_colors[0][0] != -1) {\n\t\t\t\t\tfor (int y = 0; const auto& [red, green, blue] : output_colors)\n\t\t\t\t\t\tcolor_gradient[y++] = dec_to_color(red, green, blue, t_to_256);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t//? If only start was defined fill array with start color\n\t\t\t\t\tcolor_gradient.fill(colors[name]);\n\t\t\t\t}\n\t\t\t\tgradients[color_name] = std::move(color_gradient);\n\t\t\t}\n\t\t}\n\n\t\t//* Set colors and generate gradients for the TTY theme\n\t\tvoid generateTTYColors() {\n\t\t\trgbs.clear();\n\t\t\tgradients.clear();\n\t\t\tcolors = TTY_theme;\n\t\t\tif (not Config::getB(\"theme_background\"))\n\t\t\t\tcolors[\"main_bg\"] = \"\\x1b[49m\";\n\n\t\t\tfor (const auto& c : colors) {\n\t\t\t\tif (not c.first.ends_with(\"_start\")) continue;\n\t\t\t\tconst string base_name { rtrim(c.first, \"_start\") };\n\t\t\t\tstring section = \"_start\";\n\t\t\t\tint split = colors.at(base_name + \"_mid\").empty() ? 50 : 33;\n\t\t\t\tfor (int i : iota(0, 101)) {\n\t\t\t\t\tgradients[base_name][i] = colors.at(base_name + section);\n\t\t\t\t\tif (i == split) {\n\t\t\t\t\t\tsection = (split == 33) ? \"_mid\" : \"_end\";\n\t\t\t\t\t\tsplit *= 2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//* Load a .theme file from disk\n\t\tauto loadFile(const string& filename) {\n\t\t\tconst fs::path filepath = filename;\n\t\t\tif (not fs::exists(filepath))\n\t\t\t\treturn Default_theme;\n\n\t\t\tstd::ifstream themefile(filepath);\n\t\t\tif (themefile.good()) {\n\t\t\t\tstd::unordered_map<string, string> theme_out;\n\t\t\t\tLogger::debug(\"Loading theme file: {}\", filename);\n\t\t\t\twhile (not themefile.bad()) {\n\t\t\t\t\tif (themefile.peek() == '#') {\n\t\t\t\t\t\tthemefile.ignore(SSmax, '\\n');\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthemefile.ignore(SSmax, '[');\n\t\t\t\t\tif (themefile.eof()) break;\n\t\t\t\t\tstring name, value;\n\t\t\t\t\tgetline(themefile, name, ']');\n\t\t\t\t\tif (not Default_theme.contains(name)) {\n\t\t\t\t\t\tthemefile.ignore(SSmax, '\\n');\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthemefile.ignore(SSmax, '=');\n\t\t\t\t\tthemefile >> std::ws;\n\t\t\t\t\tif (themefile.eof()) break;\n\t\t\t\t\tif (themefile.peek() == '\"') {\n\t\t\t\t\t\tthemefile.ignore(1);\n\t\t\t\t\t\tgetline(themefile, value, '\"');\n\t\t\t\t\t\tthemefile.ignore(SSmax, '\\n');\n\t\t\t\t\t}\n\t\t\t\t\telse getline(themefile, value, '\\n');\n\n\t\t\t\t\ttheme_out[name] = value;\n\t\t\t\t}\n\t\t\t\treturn theme_out;\n\t\t\t}\n\t\t\treturn Default_theme;\n\t\t}\n\t}\n\n\tvoid updateThemes() {\n\t\tthemes.clear();\n\t\tthemes.push_back(\"Default\");\n\t\tthemes.push_back(\"TTY\");\n\n\t\t//? Priority: custom_theme_dir -> user_theme_dir -> theme_dir\n\t\tfor (const auto& path : { custom_theme_dir, user_theme_dir, theme_dir } ) {\n\t\t\tif (path.empty()) continue;\n\t\t\tfor (auto& file : fs::directory_iterator(path)) {\n\t\t\t\tif (file.path().extension() == \".theme\" and access(file.path().c_str(), R_OK) != -1 and not v_contains(themes, file.path().c_str())) {\n\t\t\t\t\tthemes.push_back(file.path().c_str());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tvoid setTheme() {\n\t\tconst auto& theme = Config::getS(\"color_theme\");\n\t\tfs::path theme_path;\n\t\tfor (const fs::path p : themes) {\n\t\t\tif (p == theme or p.stem() == theme or p.filename() == theme) {\n\t\t\t\ttheme_path = p;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (theme == \"TTY\" or Config::getB(\"tty_mode\"))\n\t\t\tgenerateTTYColors();\n\t\telse {\n\t\t\tgenerateColors((theme == \"Default\" or theme_path.empty() ? Default_theme : loadFile(theme_path)));\n\t\t\tgenerateGradients();\n\t\t}\n\t\tTerm::fg = colors.at(\"main_fg\");\n\t\tTerm::bg = colors.at(\"main_bg\");\n\t\tFx::reset = Fx::reset_base + Term::fg + Term::bg;\n\t}\n\n}\n"
  },
  {
    "path": "src/btop_theme.hpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#pragma once\n\n#include <array>\n#include <filesystem>\n#include <string>\n#include <vector>\n#include <unordered_map>\n\nusing std::array;\nusing std::string;\nusing std::vector;\n\nnamespace Theme {\n\textern std::filesystem::path theme_dir;\n\textern std::filesystem::path user_theme_dir;\n\textern std::filesystem::path custom_theme_dir;\n\n\t//* Contains \"Default\" and \"TTY\" at indices 0 and 1, otherwise full paths to theme files\n\textern vector<string> themes;\n\n\t//* Generate escape sequence for 24-bit or 256 color and return as a string\n\t//* Args\thexa: [\"#000000\"-\"#ffffff\"] for color, [\"#00\"-\"#ff\"] for greyscale\n\t//*\t\t\tt_to_256: [true|false] convert 24bit value to 256 color value\n\t//* \t\tdepth: [\"fg\"|\"bg\"] for either a foreground color or a background color\n\tstring hex_to_color(string hexa, bool t_to_256=false, const string& depth=\"fg\");\n\n\t//* Generate escape sequence for 24-bit or 256 color and return as a string\n\t//* Args\tr: [0-255], g: [0-255], b: [0-255]\n\t//*\t\t\tt_to_256: [true|false] convert 24bit value to 256 color value\n\t//* \t\tdepth: [\"fg\"|\"bg\"] for either a foreground color or a background color\n\tstring dec_to_color(int r, int g, int b, bool t_to_256=false, const string& depth=\"fg\");\n\n\t//* Update list of paths for available themes\n\tvoid updateThemes();\n\n\t//* Set current theme from current \"color_theme\" value in config\n\tvoid setTheme();\n\n\textern std::unordered_map<string, string> colors;\n\textern std::unordered_map<string, array<int, 3>> rgbs;\n\textern std::unordered_map<string, array<string, 101>> gradients;\n\n\t//* Return escape code for color <name>\n\tinline const string& c(const string& name) { return colors.at(name); }\n\n\t//* Return array of escape codes for color gradient <name>\n\tinline const array<string, 101>& g(const string& name) { return gradients.at(name); }\n\n\t//* Return array of red, green and blue in decimal for color <name>\n\tinline const std::array<int, 3>& dec(const string& name) { return rgbs.at(name); }\n\n}\n"
  },
  {
    "path": "src/btop_tools.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include <cmath>\n#include <ctime>\n#include <filesystem>\n#include <fstream>\n#include <iomanip>\n#include <iostream>\n#include <sstream>\n#include <string_view>\n#include <utility>\n#include <cstdlib>\n\n#include <fcntl.h>\n#include <sys/ioctl.h>\n#include <termios.h>\n#include <unistd.h>\n\n#include \"widechar_width.hpp\"\n#include \"btop_log.hpp\"\n#include \"btop_shared.hpp\"\n#include \"btop_tools.hpp\"\n#include \"btop_config.hpp\"\n\nusing std::cout;\nusing std::floor;\nusing std::flush;\nusing std::max;\nusing std::string_view;\nusing std::to_string;\n\nusing namespace std::literals; // to use operator\"\"s\n\nnamespace fs = std::filesystem;\n\n//? ------------------------------------------------- NAMESPACES ------------------------------------------------------\n\n//* Collection of escape codes and functions for terminal manipulation\nnamespace Term {\n\n\tatomic<bool> initialized{};\n\tatomic<int> width{};\n\tatomic<int> height{};\n\tstring current_tty;\n\n\tnamespace {\n\t\tstruct termios initial_settings;\n\n\t\t//* Toggle terminal input echo\n\t\tbool echo(bool on=true) {\n\t\t\tstruct termios settings;\n\t\t\tif (tcgetattr(STDIN_FILENO, &settings)) return false;\n\t\t\tif (on) settings.c_lflag |= ECHO;\n\t\t\telse settings.c_lflag &= ~(ECHO);\n\t\t\treturn 0 == tcsetattr(STDIN_FILENO, TCSANOW, &settings);\n\t\t}\n\n\t\t//* Toggle need for return key when reading input\n\t\tbool linebuffered(bool on=true) {\n\t\t\tstruct termios settings;\n\t\t\tif (tcgetattr(STDIN_FILENO, &settings)) return false;\n\t\t\tif (on) settings.c_lflag |= ICANON;\n\t\t\telse {\n\t\t\t\tsettings.c_lflag &= ~(ICANON);\n\t\t\t\tsettings.c_cc[VMIN] = 0;\n\t\t\t\tsettings.c_cc[VTIME] = 0;\n\t\t\t}\n\t\t\tif (tcsetattr(STDIN_FILENO, TCSANOW, &settings)) return false;\n\t\t\tif (on) setlinebuf(stdin);\n\t\t\telse setbuf(stdin, nullptr);\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tbool refresh(bool only_check) {\n\t\t// Query dimensions of '/dev/tty' of the 'STDOUT_FILENO' isn't available.\n\t\t// This variable is set in those cases to avoid calls to ioctl\n\t\tconstinit static bool uses_dev_tty = false;\n\t\tstruct winsize wsize {};\n\t\tif (uses_dev_tty || ioctl(STDOUT_FILENO, TIOCGWINSZ, &wsize) < 0 || (wsize.ws_col == 0 && wsize.ws_row == 0)) {\n\t\t\tLogger::error(R\"(Couldn't determine terminal size of \"STDOUT_FILENO\"!)\");\n\t\t\tauto dev_tty = open(\"/dev/tty\", O_RDONLY | O_CLOEXEC);\n\t\t\tif (dev_tty != -1) {\n\t\t\t\tioctl(dev_tty, TIOCGWINSZ, &wsize);\n\t\t\t\tclose(dev_tty);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tLogger::error(R\"(Couldn't determine terminal size of \"/dev/tty\"!)\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tuses_dev_tty = true;\n\t\t}\n\t\tif (width != wsize.ws_col or height != wsize.ws_row) {\n\t\t\tif (not only_check) {\n\t\t\t\twidth = wsize.ws_col;\n\t\t\t\theight = wsize.ws_row;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tauto get_min_size(const string& boxes) -> array<int, 2> {\n        bool cpu = boxes.find(\"cpu\") != string::npos;\n        bool mem = boxes.find(\"mem\") != string::npos;\n        bool net = boxes.find(\"net\") != string::npos;\n        bool proc = boxes.find(\"proc\") != string::npos;\n\t#ifdef GPU_SUPPORT\n\t\tint gpu = 0;\n        if (Gpu::count > 0)\n        \tfor (char i = '0'; i <= '5'; i++)\n        \t\tgpu += (boxes.contains(\"gpu\"s + i) ? 1 : 0);\n\t#endif\n        int width = 0;\n\t\tif (mem) width = Mem::min_width;\n\t\telse if (net) width = Mem::min_width;\n\t\twidth += (proc ? Proc::min_width : 0);\n\t\tif (cpu and width < Cpu::min_width) width = Cpu::min_width;\n\t#ifdef GPU_SUPPORT\n\t\tif (gpu != 0 and width < Gpu::min_width) width = Gpu::min_width;\n\t#endif\n\n\t\tint height = (cpu ? Cpu::min_height : 0);\n\t\tif (proc) height += Proc::min_height;\n\t\telse height += (mem ? Mem::min_height : 0) + (net ? Net::min_height : 0);\n\t#ifdef GPU_SUPPORT\n\t\tfor (int i = 0; i < gpu; i++)\n\t\t\theight += Gpu::gpu_b_height_offsets[i] + 4;\n\t#endif\n\n\t\treturn { width, height };\n\t}\n\n\tbool init() {\n\t\tif (not initialized) {\n\t\t\tinitialized = (bool)isatty(STDIN_FILENO);\n\t\t\tif (initialized) {\n\t\t\t\ttcgetattr(STDIN_FILENO, &initial_settings);\n\t\t\t\tcurrent_tty = (ttyname(STDIN_FILENO) != nullptr ? static_cast<string>(ttyname(STDIN_FILENO)) : \"unknown\");\n\n\t\t\t\t//? Disable stream sync - this does not seem to work on OpenBSD\n#ifndef __OpenBSD__\n\t\t\t\tcout.sync_with_stdio(false);\n#endif\n\n\t\t\t\t//? Disable stream ties\n\t\t\t\tcout.tie(nullptr);\n\t\t\t\techo(false);\n\t\t\t\tlinebuffered(false);\n\t\t\t\trefresh();\n\n\t\t\t\tconst auto is_mouse_enabled = !Config::getB(\"disable_mouse\");\n\t\t\t\tcout << alt_screen << hide_cursor << (is_mouse_enabled ? mouse_on : mouse_off) << flush;\n\t\t\t\tGlobal::resized = false;\n\t\t\t}\n\t\t}\n\t\treturn initialized;\n\t}\n\n\tvoid restore() {\n\t\tif (initialized) {\n\t\t\ttcsetattr(STDIN_FILENO, TCSANOW, &initial_settings);\n\t\t\tcout << mouse_off << clear << Fx::reset << normal_screen << show_cursor << flush;\n\t\t\tinitialized = false;\n\t\t}\n\t}\n}\n\n//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------\n\n// ! Disabled due to issue when compiling with musl, reverted back to using regex\n// namespace Fx {\n// \tstring uncolor(const string& s) {\n// \t\tstring out = s;\n// \t\tfor (size_t offset = 0, start_pos = 0, end_pos = 0;;) {\n// \t\t\tstart_pos = (offset == 0) ? out.find('\\x1b') : offset;\n// \t\t\tif (start_pos == string::npos)\n// \t\t\t\tbreak;\n// \t\t\toffset = start_pos + 1;\n// \t\t\tend_pos = out.find('m', offset);\n// \t\t\tif (end_pos == string::npos)\n// \t\t\t\tbreak;\n// \t\t\telse if (auto next_pos = out.find('\\x1b', offset); not isdigit(out[end_pos - 1]) or end_pos > next_pos) {\n// \t\t\t \toffset = next_pos;\n// \t\t\t\tcontinue;\n// \t\t\t}\n\n// \t\t\tout.erase(start_pos, (end_pos - start_pos)+1);\n// \t\t\toffset = 0;\n// \t\t}\n// \t\tout.shrink_to_fit();\n// \t\treturn out;\n// \t}\n// }\n\nnamespace Tools {\n\n\tstring replace_ascii_control(string str, const char replacement) {\n\t\tif (str.empty())\n\t\t\treturn str;\n\t\tconst char* str_data = &str.data()[0];\n\t\tsize_t w_len = 1 + std::mbstowcs(nullptr, str_data, 0);\n\t\tif (w_len <= 1)\t{\n\t\t\tstd::ranges::for_each(str, [&replacement](char& c) { if (c < 0x20) c = replacement; });\n\t\t\treturn str;\n\t\t}\n\t\tvector<wchar_t> w_str(w_len);\n\t\tstd::mbstowcs(&w_str[0], str_data, w_len);\n\t\tfor (size_t i = 0; i < w_str.size(); i++) {\n\t\t\tif (widechar_wcwidth(w_str[i]) > 1)\n\t\t\t\tcontinue;\n\t\t\tif (w_str[i] < 0x20)\n\t\t\t\tw_str[i] = replacement;\n\t\t}\n\t\tstr.resize(w_str.size());\n\t\tstd::wcstombs(&str[0], &w_str[0], w_str.size());\n\n\t\treturn str;\n\t}\n\n\tsize_t wide_ulen(const std::string_view str) {\n\t\tif (str.empty())\n\t\t\treturn 0;\n\t\tunsigned int chars = 0;\n\n\t\tconst char* str_data = &str.data()[0];\n\t\t\tsize_t w_len = 1 + std::mbstowcs(nullptr, str_data, 0);\n\t\tif (w_len <= 1)\n\t\t\treturn ulen(str);\n\t\tvector<wchar_t> w_str(w_len);\n\t\tstd::mbstowcs(&w_str[0], str_data, w_len);\n\n\t\tfor (auto c : w_str) {\n\t\t\tchars += widechar_wcwidth(c);\n\t\t}\n\n\t\treturn chars;\n\t}\n\n\tsize_t wide_ulen(const vector<wchar_t> w_str) {\n\t\tunsigned int chars = 0;\n\n\t\tfor (auto c : w_str) {\n\t\t\tchars += widechar_wcwidth(c);\n\t\t}\n\n\t\treturn chars;\n\t}\n\n\tstring uresize(string str, const size_t len, bool wide) {\n\t\tif (len < 1 or str.empty())\n\t\t\treturn \"\";\n\n\t\tif (wide) {\n\t\t\tconst char* str_data = &str.data()[0];\n\t\t\tsize_t w_len = 1 + std::mbstowcs(nullptr, str_data, 0);\n\t\t\tif (w_len <= 1)\n\t\t\t\treturn uresize(str, len, false);\n\t\t\tvector<wchar_t> w_str(w_len);\n\t\t\tstd::mbstowcs(&w_str[0], str_data, w_len);\n\n\t\t\twhile (wide_ulen(w_str) > len) w_str.pop_back();\n\n\t\t\tstring n_str;\n\t\t\tn_str.resize(w_str.size());\n\t\t\tstd::wcstombs(&n_str[0], &w_str[0], w_str.size());\n\n\t\t\treturn n_str;\n\t\t}\n\t\telse {\n\t\t\tfor (size_t x = 0, i = 0; i < str.size(); i++) {\n\t\t\t\tif ((static_cast<unsigned char>(str.at(i)) & 0xC0) != 0x80) x++;\n\t\t\t\tif (x >= len + 1) {\n\t\t\t\t\tstr.resize(i);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstr.shrink_to_fit();\n\t\treturn str;\n\t}\n\n\tstring luresize(string str, const size_t len, bool wide) {\n\t\tif (len < 1 or str.empty())\n\t\t\treturn \"\";\n\n\t\tfor (size_t x = 0, last_pos = 0, i = str.size() - 1; i > 0 ; i--) {\n\t\t\tif (wide and static_cast<unsigned char>(str.at(i)) > 0xef) {\n\t\t\t\tx += 2;\n\t\t\t\tlast_pos = max((size_t)0, i - 1);\n\t\t\t}\n\t\t\telse if ((static_cast<unsigned char>(str.at(i)) & 0xC0) != 0x80) {\n\t\t\t\tx++;\n\t\t\t\tlast_pos = i;\n\t\t\t}\n\t\t\tif (x >= len) {\n\t\t\t\tstr = str.substr(last_pos);\n\t\t\t\tstr.shrink_to_fit();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn str;\n\t}\n\n\tstring s_replace(const string& str, const string& from, const string& to) {\n\t\tstring out = str;\n\t\tfor (size_t start_pos = out.find(from); start_pos != std::string::npos; start_pos = out.find(from)) {\n\t\t\tout.replace(start_pos, from.length(), to);\n\t\t}\n\t\treturn out;\n\t}\n\n\tstring_view ltrim(string_view str, const string_view t_str) {\n\t\twhile (str.starts_with(t_str))\n\t\t\tstr.remove_prefix(t_str.size());\n\n\t\treturn str;\n\t}\n\n\tstring_view rtrim(string_view str, const string_view t_str) {\n\t\twhile (str.ends_with(t_str))\n\t\t\tstr.remove_suffix(t_str.size());\n\n\t\treturn str;\n\t}\n\n\tstring ljust(string str, const size_t x, bool utf, bool wide, bool limit) {\n\t\tif (utf) {\n\t\t\tif (limit and ulen(str, wide) > x)\n\t\t\t\treturn uresize(str, x, wide);\n\n\t\t\treturn str + string(max((int)(x - ulen(str)), 0), ' ');\n\t\t}\n\t\telse {\n\t\t\tif (limit and str.size() > x) {\n\t\t\t\tstr.resize(x);\n\t\t\t\treturn str;\n\t\t\t}\n\t\t\treturn str + string(max((int)(x - str.size()), 0), ' ');\n\t\t}\n\t}\n\n\tstring rjust(string str, const size_t x, bool utf, bool wide, bool limit) {\n\t\tif (utf) {\n\t\t\tif (limit and ulen(str, wide) > x)\n\t\t\t\treturn uresize(str, x, wide);\n\n\t\t\treturn string(max((int)(x - ulen(str)), 0), ' ') + str;\n\t\t}\n\t\telse {\n\t\t\tif (limit and str.size() > x) {\n\t\t\t\tstr.resize(x);\n\t\t\t\treturn str;\n\t\t\t};\n\t\t\treturn string(max((int)(x - str.size()), 0), ' ') + str;\n\t\t}\n\t}\n\n\tstring cjust(string str, const size_t x, bool utf, bool wide, bool limit) {\n\t\tif (utf) {\n\t\t\tif (limit and ulen(str, wide) > x)\n\t\t\t\treturn uresize(str, x, wide);\n\n\t\t\treturn string(max((int)ceil((double)(x - ulen(str)) / 2), 0), ' ') + str + string(max((int)floor((double)(x - ulen(str)) / 2), 0), ' ');\n\t\t}\n\t\telse {\n\t\t\tif (limit and str.size() > x) {\n\t\t\t\tstr.resize(x);\n\t\t\t\treturn str;\n\t\t\t}\n\t\t\treturn string(max((int)ceil((double)(x - str.size()) / 2), 0), ' ') + str + string(max((int)floor((double)(x - str.size()) / 2), 0), ' ');\n\t\t}\n\t}\n\n\tstring trans(const string& str) {\n\t\tstd::string_view oldstr{str};\n\t\tstring newstr;\n\t\tnewstr.reserve(str.size());\n\t\tfor (size_t pos; (pos = oldstr.find(' ')) != string::npos;) {\n\t\t\tnewstr.append(oldstr.substr(0, pos));\n\t\t\tsize_t x = 0;\n\t\t\twhile (pos + x < oldstr.size() and oldstr.at(pos + x) == ' ') x++;\n\t\t\tnewstr.append(Mv::r(x));\n\t\t\toldstr.remove_prefix(pos + x);\n\t\t}\n\t\treturn (newstr.empty()) ? str : newstr + string{oldstr};\n\t}\n\n\tstring sec_to_dhms(size_t seconds, bool no_days, bool no_seconds) {\n\t\tsize_t days = seconds / 86400; seconds %= 86400;\n\t\tsize_t hours = seconds / 3600; seconds %= 3600;\n\t\tsize_t minutes = seconds / 60; seconds %= 60;\n\t\tstring out \t= (not no_days and days > 0 ? to_string(days) + \"d \" : \"\")\n\t\t\t\t\t+ (hours < 10 ? \"0\" : \"\") + to_string(hours) + ':'\n\t\t\t\t\t+ (minutes < 10 ? \"0\" : \"\") + to_string(minutes)\n\t\t\t\t\t+ (not no_seconds ? \":\" + string(std::cmp_less(seconds, 10) ? \"0\" : \"\") + to_string(seconds) : \"\");\n\t\treturn out;\n\t}\n\n\tstring floating_humanizer(uint64_t value, bool shorten, size_t start, bool bit, bool per_second) {\n\t\tstring out;\n\t\tconst size_t mult = (bit) ? 8 : 1;\n\n\t\tbool mega = Config::getB(\"base_10_sizes\");\n\n\t\t// Bitrates\n\t    if(bit && per_second) {\n\t\t\tconst auto& base_10_bitrate = Config::getS(\"base_10_bitrate\");\n\t\t\tif(base_10_bitrate == \"True\") {\n\t\t\t\tmega = true;\n\t\t\t} else if(base_10_bitrate == \"False\") {\n\t\t\t\tmega = false;\n\t\t\t}\n\t\t\t// Default or \"Auto\": Uses base_10_sizes for bitrates\n\t\t}\n\n\t\t// taking advantage of type deduction for array creation (since C++17)\n\t\t// combined with string literals (operator\"\"s)\n\t\tstatic const array mebiUnits_bit {\n\t\t\t\"bit\"s, \"Kib\"s, \"Mib\"s,\n\t\t\t\"Gib\"s, \"Tib\"s, \"Pib\"s,\n\t\t\t\"Eib\"s, \"Zib\"s, \"Yib\"s,\n\t\t\t\"Bib\"s, \"GEb\"s\n\t\t};\n\t\tstatic const array mebiUnits_byte {\n\t\t\t\"Byte\"s, \"KiB\"s, \"MiB\"s,\n\t\t\t\"GiB\"s, \"TiB\"s, \"PiB\"s,\n\t\t\t\"EiB\"s, \"ZiB\"s, \"YiB\"s,\n\t\t\t\"BiB\"s, \"GEB\"s\n\t\t};\n\t\tstatic const array megaUnits_bit {\n\t\t\t\"bit\"s, \"Kb\"s, \"Mb\"s,\n\t\t\t\"Gb\"s, \"Tb\"s, \"Pb\"s,\n\t\t\t\"Eb\"s, \"Zb\"s, \"Yb\"s,\n\t\t\t\"Bb\"s, \"Gb\"s\n\t\t};\n\t\tstatic const array megaUnits_byte {\n\t\t\t\"Byte\"s, \"KB\"s, \"MB\"s,\n\t\t\t\"GB\"s, \"TB\"s, \"PB\"s,\n\t\t\t\"EB\"s, \"ZB\"s, \"YB\"s,\n\t\t\t\"BB\"s, \"GB\"s\n\t\t};\n\t\tconst auto& units = (bit) ? ( mega ? megaUnits_bit : mebiUnits_bit) : ( mega ? megaUnits_byte : mebiUnits_byte);\n\n\t\tvalue *= 100 * mult;\n\n\t\tif (mega) {\n\t\t\twhile (value >= 100000) {\n\t\t\t\tvalue /= 1000;\n\t\t\t\tstart++;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\twhile (value >= 102400) {\n\t\t\t\tvalue >>= 10;\n\t\t\t\tstart++;\n\t\t\t}\n\t\t}\n\t\tif (out.empty()) {\n\t\t\tout = fmt::format(\"{}\", value);\n\t\t\tif (not mega and out.size() == 4 and start > 0) {\n\t\t\t\tout.pop_back();\n\t\t\t\tout.insert(2, \".\");\n\t\t\t}\n\t\t\telse if (out.size() == 3 and start > 0) {\n\t\t\t\tout.insert(1, \".\");\n\t\t\t}\n\t\t\telse if (out.size() >= 2) {\n\t\t\t\tout.resize(out.size() - 2);\n\t\t\t}\n\t\t\tif (out.empty()) {\n\t\t\t\tout = \"0\";\n\t\t\t}\n\t\t}\n\n\t\tif (shorten) {\n\t\t\tauto has_sep = out.find(\".\") != string::npos;\n\t\t\tif (has_sep) {\n\t\t\t\tout = fmt::format(\"{:.1f}\", stod(out));\n\t\t\t}\n\t\t\tif (out.size() > 3) {\n\t\t\t\t// if out is of the form xy.z\n\t\t\t\tif (has_sep) {\n\t\t\t\t\tout = fmt::format(\"{:.0f}\", stod(out));\n\t\t\t\t}\n\t\t\t\t// if out is of the form xyzw (only when not using base 10)\n\t\t\t\telse {\n\t\t\t\t\tout = fmt::format(\"{:d}.0\", out[0] - '0');\n\t\t\t\t\tstart++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tout.push_back(units[start][0]);\n\t\t}\n\t\telse out += \" \" + units[start];\n\n\t\tif (per_second) out += (bit) ? \"ps\" : \"/s\";\n\t\treturn out;\n\t}\n\n\tstd::string operator*(const string& str, int64_t n) {\n\t\tif (n < 1 or str.empty()) {\n\t\t\treturn \"\";\n\t\t}\n\t\telse if (n == 1) {\n\t\t\treturn str;\n\t\t}\n\n\t\tstring new_str;\n\t\tnew_str.reserve(str.size() * n);\n\n\t\tfor (; n > 0; n--)\n\t\t\tnew_str.append(str);\n\n\t\treturn new_str;\n\t}\n\n\tstring strf_time(const string& strf) {\n\t\tauto in_time_t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n\t\tstd::tm bt {};\n\t\tstd::stringstream ss;\n\t\tss << std::put_time(localtime_r(&in_time_t, &bt), strf.c_str());\n\t\treturn ss.str();\n\t}\n\n\tvoid atomic_wait(const atomic<bool>& atom, bool old) noexcept {\n\t\tatom.wait(old, std::memory_order_relaxed);\n\t}\n\n\tvoid atomic_wait_for(const atomic<bool>& atom, bool old, const uint64_t wait_ms) noexcept {\n\t\tconst uint64_t start_time = time_ms();\n\t\twhile (atom.load(std::memory_order_relaxed) == old and (time_ms() - start_time < wait_ms)) sleep_ms(1);\n\t}\n\n\tatomic_lock::atomic_lock(atomic<bool>& atom, bool wait) : atom(atom) {\n\t\tif (wait) while (not this->atom.compare_exchange_strong(this->not_true, true));\n\t\telse this->atom.store(true);\n\t\tthis->atom.notify_all();\n\t}\n\n\tatomic_lock::~atomic_lock() noexcept {\n\t\tthis->atom.store(false);\n\t\tthis->atom.notify_all();\n\t}\n\n\tstring readfile(const std::filesystem::path& path, const string& fallback) {\n\t\tif (not fs::exists(path)) return fallback;\n\t\tstring out;\n\t\ttry {\n\t\t\tstd::ifstream file(path);\n\t\t\tfor (string readstr; getline(file, readstr); out += readstr);\n\t\t}\n\t\tcatch (const std::exception& e) {\n\t\t\tLogger::error(\"readfile() : Exception when reading {} : {}\", path, e.what());\n\t\t\treturn fallback;\n\t\t}\n\t\treturn (out.empty() ? fallback : out);\n\t}\n\n\tauto celsius_to(const long long& celsius, const string& scale) -> tuple<long long, string> {\n\t\tif (scale == \"celsius\")\n\t\t\treturn {celsius, \"°C\"};\n\t\telse if (scale == \"fahrenheit\")\n\t\t\treturn {(long long)round((double)celsius * 1.8 + 32), \"°F\"};\n\t\telse if (scale == \"kelvin\")\n\t\t\treturn {(long long)round((double)celsius + 273.15), \"K \"};\n\t\telse if (scale == \"rankine\")\n\t\t\treturn {(long long)round((double)celsius * 1.8 + 491.67), \"°R\"};\n\t\treturn {0, \"\"};\n\t}\n\n\tstring hostname() {\n\t\tchar host[HOST_NAME_MAX];\n\t\tgethostname(host, HOST_NAME_MAX);\n\t\thost[HOST_NAME_MAX - 1] = '\\0';\n\t\treturn string{host};\n\t}\n\n\tstring username() {\n\t\tauto user = getenv(\"LOGNAME\");\n\t\tif (user == nullptr or strlen(user) == 0) user = getenv(\"USER\");\n\t\treturn (user != nullptr ? user : \"\");\n\t}\n\n\tDebugTimer::DebugTimer(string name, bool start, bool delayed_report)\n\t\t\t: name(std::move(name)), delayed_report(delayed_report) {\n\t\tif (start)\n\t\t\tthis->start();\n\t}\n\n\tDebugTimer::~DebugTimer() {\n\t\tif (running)\n\t\t\tthis->stop(true);\n\t\tthis->force_report();\n\t}\n\n\tvoid DebugTimer::start() {\n\t\tif (running) return;\n\t\trunning = true;\n\t\tstart_time = time_micros();\n\t}\n\n\tvoid DebugTimer::stop(bool report) {\n\t\tif (not running) return;\n\t\trunning = false;\n\t\telapsed_time = time_micros() - start_time;\n\t\tif (report) this->report();\n\t}\n\n\tvoid DebugTimer::reset(bool restart) {\n\t\trunning = false;\n\t\tstart_time = 0;\n\t\telapsed_time = 0;\n\t\tif (restart) this->start();\n\t}\n\n\tvoid DebugTimer::stop_rename_reset(const string &new_name, bool report, bool restart) {\n\t\tthis->stop(report);\n\t\tname = new_name;\n\t\tthis->reset(restart);\n\t}\n\n\tvoid DebugTimer::report() {\n\t\tstring report_line;\n\t\tif (start_time == 0 and elapsed_time == 0)\n\t\t\treport_line = fmt::format(\"DebugTimer::report() warning -> Timer [{}] has not been started!\", name);\n\t\telse if (running)\n\t\t\treport_line = fmt::format(custom_locale, \"Timer [{}] (running) currently at {:L} μs\", name, time_micros() - start_time);\n\t\telse\n\t\t\treport_line = fmt::format(custom_locale, \"Timer [{}] took {:L} μs\", name, elapsed_time);\n\n\t\tif (delayed_report)\n\t\t\treport_buffer.emplace_back(report_line);\n\t\telse\n\t\t\tLogger::debug(\"{}\", report_line);\n\t}\n\n\tvoid DebugTimer::force_report() {\n\t\tif (report_buffer.empty()) return;\n\t\tfor (const auto& line : report_buffer)\n\t\t\tLogger::debug(\"{}\", line);\n\t\treport_buffer.clear();\n\t}\n\n\tuint64_t DebugTimer::elapsed() {\n\t\tif (running)\n\t\t\treturn time_micros() - start_time;\n\t\treturn elapsed_time;\n\t}\n\n\tbool DebugTimer::is_running() {\n\t\treturn running;\n\t}\n}\n"
  },
  {
    "path": "src/btop_tools.hpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#pragma once\n\n#if !defined(NDEBUG)\n# define BTOP_DEBUG\n#endif\n\n#include <algorithm>        // for std::ranges::count_if\n#include <array>\n#include <atomic>\n#include <chrono>\n#include <cstdint>\n#include <filesystem>\n#include <limits.h>\n#include <ranges>\n#include <regex>\n#include <string>\n#include <string_view>\n#include <thread>\n#include <tuple>\n#include <unordered_map>\n#include <vector>\n#ifdef BTOP_DEBUG\n#include <source_location>\n#endif\n#ifndef HOST_NAME_MAX\n\t#ifdef __APPLE__\n\t\t#define HOST_NAME_MAX 255\n\t#else\n\t\t#define HOST_NAME_MAX 64\n\t#endif\n#endif\n\n#include <fmt/core.h>\n#include <fmt/format.h>\n\n#include \"btop_log.hpp\"\n\nusing std::array;\nusing std::atomic;\nusing std::string;\nusing std::to_string;\nusing std::string_view;\nusing std::tuple;\nusing std::vector;\nusing namespace fmt::literals;\n\n//? ------------------------------------------------- NAMESPACES ------------------------------------------------------\n\n//* Collection of escape codes for text style and formatting\nnamespace Fx {\n\tconst string e = \"\\x1b[\";\t\t\t\t//* Escape sequence start\n\tconst string b = e + \"1m\";\t\t\t\t//* Bold on/off\n\tconst string ub = e + \"22m\";\t\t\t//* Bold off\n\tconst string d = e + \"2m\";\t\t\t\t//* Dark on\n\tconst string ud = e + \"22m\";\t\t\t//* Dark off\n\tconst string i = e + \"3m\";\t\t\t\t//* Italic on\n\tconst string ui = e + \"23m\";\t\t\t//* Italic off\n\tconst string ul = e + \"4m\";\t\t\t\t//* Underline on\n\tconst string uul = e + \"24m\";\t\t\t//* Underline off\n\tconst string bl = e + \"5m\";\t\t\t\t//* Blink on\n\tconst string ubl = e + \"25m\";\t\t\t//* Blink off\n\tconst string s = e + \"9m\";\t\t\t\t//* Strike/crossed-out on\n\tconst string us = e + \"29m\";\t\t\t//* Strike/crossed-out on/off\n\n\t//* Reset foreground/background color and text effects\n\tconst string reset_base = e + \"0m\";\n\n\t//* Reset text effects and restore theme foregrund and background color\n\textern string reset;\n\n\t//* Regex for matching color, style and cursor move escape sequences\n\tconst std::regex escape_regex(\"\\033\\\\[\\\\d+;?\\\\d?;?\\\\d*;?\\\\d*;?\\\\d*(m|f|s|u|C|D|A|B){1}\");\n\n\t//* Regex for matching only color and style escape sequences\n\tconst std::regex color_regex(\"\\033\\\\[\\\\d+;?\\\\d?;?\\\\d*;?\\\\d*;?\\\\d*(m){1}\");\n\n\t//* Return a string with all colors and text styling removed\n\tinline string uncolor(const string& s) { return std::regex_replace(s, color_regex, \"\"); }\n\t// string uncolor(const string& s);\n\n}\n\n//* Collection of escape codes and functions for cursor manipulation\nnamespace Mv {\n\t//* Move cursor to <line>, <column>\n\tinline string to(int line, int col) { return Fx::e + to_string(line) + ';' + to_string(col) + 'f'; }\n\n\t//* Move cursor right <x> columns\n\tinline string r(int x) { return Fx::e + to_string(x) + 'C'; }\n\n\t//* Move cursor left <x> columns\n\tinline string l(int x) { return Fx::e + to_string(x) + 'D'; }\n\n\t//* Move cursor up x lines\n\tinline string u(int x) { return Fx::e + to_string(x) + 'A'; }\n\n\t//* Move cursor down x lines\n\tinline string d(int x) { return Fx::e + to_string(x) + 'B'; }\n\n\t//* Save cursor position\n\tconst string save = Fx::e + \"s\";\n\n\t//* Restore saved cursor position\n\tconst string restore = Fx::e + \"u\";\n}\n\n//* Collection of escape codes and functions for terminal manipulation\nnamespace Term {\n\textern atomic<bool> initialized;\n\textern atomic<int> width;\n\textern atomic<int> height;\n\textern string fg, bg, current_tty;\n\n\tconst string hide_cursor = Fx::e + \"?25l\";\n\tconst string show_cursor = Fx::e + \"?25h\";\n\tconst string alt_screen = Fx::e + \"?1049h\";\n\tconst string normal_screen = Fx::e + \"?1049l\";\n\tconst string clear = Fx::e + \"2J\" + Fx::e + \"0;0f\";\n\tconst string clear_end = Fx::e + \"0J\";\n\tconst string clear_begin = Fx::e + \"1J\";\n\tconst string mouse_on = Fx::e + \"?1002h\" + Fx::e + \"?1015h\" + Fx::e + \"?1006h\"; //? Enable reporting of mouse position on click and release\n\tconst string mouse_off = Fx::e + \"?1002l\" + Fx::e + \"?1015l\" + Fx::e + \"?1006l\";\n\tconst string mouse_direct_on = Fx::e + \"?1003h\"; //? Enable reporting of mouse position at any movement\n\tconst string mouse_direct_off = Fx::e + \"?1003l\";\n\tconst string sync_start = Fx::e + \"?2026h\"; //? Start of terminal synchronized output\n\tconst string sync_end = Fx::e + \"?2026l\"; //? End of terminal synchronized output\n\n\t//* Returns true if terminal has been resized and updates width and height\n\tbool refresh(bool only_check=false);\n\n\t//* Returns an array with the lowest possible width, height with current box config\n\tauto get_min_size(const string& boxes) -> array<int, 2>;\n\n\t//* Check for a valid tty, save terminal options and set new options\n\tbool init();\n\n\t//* Restore terminal options\n\tvoid restore();\n}\n\n//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------\n\nnamespace Tools {\n\tconstexpr auto SSmax = std::numeric_limits<std::streamsize>::max();\n\n\tclass MyNumPunct : public std::numpunct<char> {\n\tprotected:\n\t\tvirtual char do_thousands_sep() const override { return '\\''; }\n\t\tvirtual std::string do_grouping() const override { return \"\\03\"; }\n\t};\n\n\tsize_t wide_ulen(const std::string_view str);\n\tsize_t wide_ulen(const vector<wchar_t> w_str);\n\n\t//* Return number of UTF8 characters in a string (wide=true for column size needed on terminal)\n\tinline size_t ulen(const std::string_view str, bool wide = false) {\n\t\treturn (wide ? wide_ulen(str) : std::ranges::count_if(str, [](char c) { return (static_cast<unsigned char>(c) & 0xC0) != 0x80; }));\n\t}\n\n\t//* Resize a string consisting of UTF8 characters (only reduces size)\n\tstring uresize(const string str, const size_t len, bool wide = false);\n\n\t//* Resize a string consisting of UTF8 characters from left (only reduces size)\n\tstring luresize(const string str, const size_t len, bool wide = false);\n\n\t//* Replace <from> in <str> with <to> and return new string\n\tstring s_replace(const string& str, const string& from, const string& to);\n\n\t//* Replace ascii control characters with <replacement> in <str> and return new string\n\tstring replace_ascii_control(string str, const char replacement = ' ');\n\n\t//* Capitalize <str>\n\tinline string capitalize(string str) {\n\t\tstr.at(0) = toupper(str.at(0));\n\t\treturn str;\n\t}\n\n\t//* Return <str> with only uppercase characters\n\tinline auto str_to_upper(string str) {\n\t\tstd::ranges::for_each(str, [](auto& c) { c = ::toupper(c); } );\n\t\treturn str;\n\t}\n\n\t//* Return <str> with only lowercase characters\n\tinline auto str_to_lower(string str) {\n\t\tstd::ranges::for_each(str, [](char& c) { c = ::tolower(c); } );\n\t\treturn str;\n\t}\n\n\t//* Check if vector <vec> contains value <find_val>\n\ttemplate <typename T, typename T2>\n\tinline bool v_contains(const vector<T>& vec, const T2& find_val) {\n\t\treturn std::ranges::find(vec, find_val) != vec.end();\n\t}\n\n\t//* Check if string <str> contains string <find_val>, while ignoring case\n\tinline bool s_contains_ic(const std::string_view str, const std::string_view find_val) {\n\t\tauto it = std::search(\n\t\t\tstr.begin(), str.end(),\n\t\t\tfind_val.begin(), find_val.end(),\n\t\t\t[](char ch1, char ch2) { return std::toupper(ch1) == std::toupper(ch2); }\n\t\t);\n\t\treturn it != str.end();\n\t}\n\n\t//* Return index of <find_val> from vector <vec>, returns size of <vec> if <find_val> is not present\n\ttemplate <typename T>\n\tinline size_t v_index(const vector<T>& vec, const T& find_val) {\n\t\treturn std::ranges::distance(vec.begin(), std::ranges::find(vec, find_val));\n\t}\n\n\t//* Compare <first> with all following values\n\ttemplate<typename First, typename ... T>\n\tinline bool is_in(const First& first, const T& ... t) {\n\t\treturn ((first == t) or ...);\n\t}\n\n\t//* Return current time since epoch in seconds\n\tinline uint64_t time_s() {\n\t\treturn std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();\n\t}\n\n\t//* Return current time since epoch in milliseconds\n\tinline uint64_t time_ms() {\n\t\treturn std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();\n\t}\n\n\t//* Return current time since epoch in microseconds\n\tinline uint64_t time_micros() {\n\t\treturn std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();\n\t}\n\n\t//* Check if a string is a valid bool value\n\tinline bool isbool(const std::string_view str) {\n\t\treturn is_in(str, \"true\", \"false\", \"True\", \"False\");\n\t}\n\n\t//* Convert string to bool, returning any value not equal to \"true\" or \"True\" as false\n\tinline bool stobool(const std::string_view str) {\n\t\treturn is_in(str, \"true\", \"True\");\n\t}\n\n\t//* Check if a string is a valid integer value (only positive)\n\tconstexpr bool isint(const std::string_view str) {\n\t\treturn std::ranges::all_of(str, ::isdigit);\n\t}\n\n\t//* Left-trim <t_str> from <str> and return new string\n\tstring_view ltrim(string_view str, string_view t_str = \" \");\n\n\t//* Right-trim <t_str> from <str> and return new string\n\tstring_view rtrim(string_view str, string_view t_str = \" \");\n\n\t//* Left/right-trim <t_str> from <str> and return new string\n\tinline string_view trim(string_view str, string_view t_str = \" \") {\n\t\treturn ltrim(rtrim(str, t_str), t_str);\n\t}\n\n\t//* Split <string> at all occurrences of <delim> and return as vector of strings\n\tconstexpr auto ssplit(std::string_view str, char delim = ' ') {\n\t\treturn str | std::views::split(delim) | std::views::filter([](auto&& range) { return !std::ranges::empty(range); }) |\n\t\t\t   std::ranges::to<std::vector<std::string>>();\n\t}\n\n\t//* Put current thread to sleep for <ms> milliseconds\n\tinline void sleep_ms(const size_t& ms) {\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(ms));\n\t}\n\n\t//* Put current thread to sleep for <micros> microseconds\n\tinline void sleep_micros(const size_t& micros) {\n\t\tstd::this_thread::sleep_for(std::chrono::microseconds(micros));\n\t}\n\n\t//* Left justify string <str> if <x> is greater than <str> length, limit return size to <x> by default\n\tstring ljust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true);\n\n\t//* Right justify string <str> if <x> is greater than <str> length, limit return size to <x> by default\n\tstring rjust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true);\n\n\t//* Center justify string <str> if <x> is greater than <str> length, limit return size to <x> by default\n\tstring cjust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true);\n\n\t//* Replace whitespaces \" \" with escape code for move right\n\tstring trans(const string& str);\n\n\t//* Convert seconds to format \"<days>d <hours>:<minutes>:<seconds>\" and return string\n\tstring sec_to_dhms(size_t seconds, bool no_days = false, bool no_seconds = false);\n\n\t//* Scales up in steps of 1024 to highest positive value unit and returns string with unit suffixed\n\t//* bit=true or defaults to bytes\n\t//* start=int to set 1024 multiplier starting unit\n\t//* shorten=true shortens value to at most 3 characters and shortens unit to 1 character\n\tstring floating_humanizer(uint64_t value, bool shorten = false, size_t start = 0, bool bit = false, bool per_second = false);\n\n\t//* Add std::string operator * : Repeat string <str> <n> number of times\n\tstd::string operator*(const string& str, int64_t n);\n\n\ttemplate <typename K, typename T>\n#ifdef BTOP_DEBUG\n\tconst T& safeVal(const std::unordered_map<K, T>& map, const K& key, const T& fallback = T{}, std::source_location loc = std::source_location::current()) {\n\t\tif (auto it = map.find(key); it != map.end()) {\n\t\t\treturn it->second;\n\t\t} else {\n\t\t\tLogger::error(\"safeVal() called with invalid key: [{}] in file: {} on line: {}\", key, loc.file_name(), loc.line());\n\t\t\treturn fallback;\n\t\t}\n\t};\n#else\n\tconst T& safeVal(const std::unordered_map<K, T>& map, const K& key, const T& fallback = T{}) {\n\t\tif (auto it = map.find(key); it != map.end()) {\n\t\t\treturn it->second;\n\t\t} else {\n\t\t\tLogger::error(\"safeVal() called with invalid key: [{}] (Compile btop with DEBUG=true for more extensive logging!)\", key);\n\t\t\treturn fallback;\n\t\t}\n\t};\n#endif\n\n\ttemplate <typename T>\n#ifdef BTOP_DEBUG\n\tconst T& safeVal(const std::vector<T>& vec, const size_t& index, const T& fallback = T{}, std::source_location loc = std::source_location::current()) {\n\t\tif (index < vec.size()) {\n\t\t\treturn vec[index];\n\t\t} else {\n\t\t\tLogger::error(\"safeVal() called with invalid index: [{}] in file: {} on line: {}\", index, loc.file_name(), loc.line());\n\t\t\treturn fallback;\n\t\t}\n\t};\n#else\n\tconst T& safeVal(const std::vector<T>& vec, const size_t& index, const T& fallback = T{}) {\n\t\tif (index < vec.size()) {\n\t\t\treturn vec[index];\n\t\t} else {\n\t\t\tLogger::error(\"safeVal() called with invalid index: [{}] (Compile btop with DEBUG=true for more extensive logging!)\", index);\n\t\t\treturn fallback;\n\t\t}\n\t};\n#endif\n\n\n\n\t//* Return current time in <strf> format\n\tstring strf_time(const string& strf);\n\n\tstring hostname();\n\tstring username();\n\n\tvoid atomic_wait(const atomic<bool>& atom, bool old = true) noexcept;\n\n\tvoid atomic_wait_for(const atomic<bool>& atom, bool old = true, const uint64_t wait_ms = 0) noexcept;\n\n\t//* Sets atomic<bool> to true on construct, sets to false on destruct\n\tclass atomic_lock {\n\t\tatomic<bool>& atom;\n\t\tbool not_true{};\n\tpublic:\n\t\texplicit atomic_lock(atomic<bool>& atom, bool wait = false);\n\t\t~atomic_lock() noexcept;\n\t\tatomic_lock(const atomic_lock& other) = delete;\n\t\tatomic_lock& operator=(const atomic_lock& other) = delete;\n\t\tatomic_lock(atomic_lock&& other) = delete;\n\t\tatomic_lock& operator=(atomic_lock&& other) = delete;\n\t};\n\n\t//* Read a complete file and return as a string\n\tstring readfile(const std::filesystem::path& path, const string& fallback = \"\");\n\n\t//* Convert a celsius value to celsius, fahrenheit, kelvin or rankin and return tuple with new value and unit.\n\tauto celsius_to(const long long& celsius, const string& scale) -> tuple<long long, string>;\n}\n\nnamespace Tools {\n\t//* Creates a named timer that is started on construct (by default) and reports elapsed time in microseconds to Logger::debug() on destruct if running\n\t//* Unless delayed_report is set to false, all reporting is buffered and delayed until DebugTimer is destructed or .force_report() is called\n\t//* Usage example: Tools::DebugTimer timer(name:\"myTimer\", [start:true], [delayed_report:true]) // Create timer and start\n\t//* timer.stop(); // Stop timer and report elapsed time\n\t//* timer.stop_rename_reset(\"myTimer2\"); // Stop timer, report elapsed time, rename timer, reset and restart\n\tclass DebugTimer {\n\t\tuint64_t start_time{};\n\t\tuint64_t elapsed_time{};\n\t\tbool running{};\n\t\tstd::locale custom_locale = std::locale(std::locale::classic(), new Tools::MyNumPunct);\n\t\tvector<string> report_buffer{};\n\t\tstring name{};\n\t\tbool delayed_report{};\n\tpublic:\n\t\tDebugTimer() = default;\n\t\texplicit DebugTimer(string name, bool start = true, bool delayed_report = true);\n\t\t~DebugTimer();\n\t\tDebugTimer(const DebugTimer& other) = delete;\n\t\tDebugTimer& operator=(const DebugTimer& other) = delete;\n\t\tDebugTimer(DebugTimer&& other) = delete;\n\t\tDebugTimer& operator=(DebugTimer&& other) = delete;\n\n\t\tvoid start();\n\t\tvoid stop(bool report = true);\n\t\tvoid reset(bool restart = true);\n\t\t//* Stops and reports (default), renames timer then resets and restarts (default)\n\t\tvoid stop_rename_reset(const string& new_name, bool report = true, bool restart = true);\n\t\tvoid report();\n\t\tvoid force_report();\n\t\tuint64_t elapsed();\n\t\tbool is_running();\n\t};\n\n}\n"
  },
  {
    "path": "src/config.h.in",
    "content": "// SPDX-License-Identifier: Apache-2.0\n\n#pragma once\n\n#include <string_view>\n\nconstexpr std::string_view GIT_COMMIT        = \"@GIT_COMMIT@\";\nconstexpr std::string_view COMPILER          = \"@COMPILER@\";\nconstexpr std::string_view COMPILER_VERSION  = \"@COMPILER_VERSION@\";\nconstexpr std::string_view CONFIGURE_COMMAND = \"@CONFIGURE_COMMAND@\";\n"
  },
  {
    "path": "src/freebsd/btop_collect.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n#include <arpa/inet.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <libproc.h>\n// man 3 getifaddrs: \"BUGS: If\tboth <net/if.h>\tand <ifaddrs.h>\tare being included, <net/if.h> must be included before <ifaddrs.h>\"\n#include <net/if.h>\n#include <ifaddrs.h>\n#include <net/if_dl.h>\n#include <net/route.h>\n#include <netdb.h>\n#include <netinet/tcp_fsm.h>\n#include <netinet/in.h> // for inet_ntop stuff\n#include <pwd.h>\n#include <sys/_timeval.h>\n#include <sys/endian.h>\n#include <sys/resource.h>\n#include <sys/socket.h>\n#include <sys/statvfs.h>\n#include <sys/sysctl.h>\n#include <sys/types.h>\n#include <sys/user.h>\n#include <sys/param.h>\n#include <sys/ucred.h>\n#include <sys/mount.h>\n#include <sys/vmmeter.h>\n#include <sys/limits.h>\n#include <vector>\n#include <vm/vm_param.h>\n#include <kvm.h>\n#include <paths.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <devstat.h>\n\n#include <stdexcept>\n#include <cmath>\n#include <fstream>\n#include <numeric>\n#include <ranges>\n#include <regex>\n#include <string>\n#include <memory>\n#include <utility>\n#include <unordered_set>\n\n#include <fmt/format.h>\n\n#include \"../btop_config.hpp\"\n#include \"../btop_log.hpp\"\n#include \"../btop_shared.hpp\"\n#include \"../btop_tools.hpp\"\n\nusing std::clamp, std::string_literals::operator\"\"s, std::cmp_equal, std::cmp_less, std::cmp_greater;\nusing std::ifstream, std::numeric_limits, std::streamsize, std::round, std::max, std::min;\nnamespace fs = std::filesystem;\nnamespace rng = std::ranges;\nusing namespace Tools;\n\n//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------\n\nnamespace Cpu {\n\tvector<long long> core_old_totals;\n\tvector<long long> core_old_idles;\n\tvector<string> available_fields = {\"Auto\", \"total\"};\n\tvector<string> available_sensors = {\"Auto\"};\n\tcpu_info current_cpu;\n\tbool got_sensors = false, cpu_temp_only = false, supports_watts = false;\n\n\t//* Populate found_sensors map\n\tbool get_sensors();\n\n\t//* Get current cpu clock speed\n\tstring get_cpuHz();\n\n\t//* Search /proc/cpuinfo for a cpu name\n\tstring get_cpuName();\n\n\tstruct Sensor {\n\t\tfs::path path;\n\t\tstring label;\n\t\tint64_t temp = 0;\n\t\tint64_t high = 0;\n\t\tint64_t crit = 0;\n\t};\n\n\tstring cpu_sensor;\n\tvector<string> core_sensors;\n\tstd::unordered_map<int, int> core_mapping;\n}  // namespace Cpu\n\nnamespace Mem {\n\tdouble old_uptime;\n\tstd::vector<string> zpools;\n\n\tvoid get_zpools();\n}\n\nnamespace Shared {\n\n\tfs::path passwd_path;\n\tuint64_t totalMem;\n\tlong pageSize, clkTck, coreCount, physicalCoreCount, arg_max;\n\tint totalMem_len, kfscale;\n\tlong bootTime;\n\n\tvoid init() {\n\t\t//? Shared global variables init\n\t\tint mib[2];\n\t\tmib[0] = CTL_HW;\n\t\tmib[1] = HW_NCPU;\n\t\tint ncpu;\n\t\tsize_t len = sizeof(ncpu);\n\t\tif (sysctl(mib, 2, &ncpu, &len, nullptr, 0) == -1) {\n\t\t\tLogger::warning(\"Could not determine number of cores, defaulting to 1.\");\n\t\t} else {\n\t\t\tcoreCount = ncpu;\n\t\t}\n\n\t\tpageSize = sysconf(_SC_PAGE_SIZE);\n\t\tif (pageSize <= 0) {\n\t\t\tpageSize = 4096;\n\t\t\tLogger::warning(\"Could not get system page size. Defaulting to 4096, processes memory usage might be incorrect.\");\n\t\t}\n\n\t\tclkTck = sysconf(_SC_CLK_TCK);\n\t\tif (clkTck <= 0) {\n\t\t\tclkTck = 100;\n\t\t\tLogger::warning(\"Could not get system clock ticks per second. Defaulting to 100, processes cpu usage might be incorrect.\");\n\t\t}\n\n\t\tint64_t memsize = 0;\n\t\tsize_t size = sizeof(memsize);\n\t\tif (sysctlbyname(\"hw.physmem\", &memsize, &size, nullptr, 0) < 0) {\n\t\t\tLogger::warning(\"Could not get memory size\");\n\t\t}\n\t\ttotalMem = memsize;\n\n\t\tstruct timeval result;\n\t\tsize = sizeof(result);\n\t\tif (sysctlbyname(\"kern.boottime\", &result, &size, nullptr, 0) < 0) {\n\t\t\tLogger::warning(\"Could not get boot time\");\n\t\t} else {\n\t\t\tbootTime = result.tv_sec;\n\t\t}\n\n\t\tsize = sizeof(kfscale);\n\t\tif (sysctlbyname(\"kern.fscale\", &kfscale, &size, nullptr, 0) == -1) {\n\t\t\tkfscale = 2048;\n\t\t}\n\n\t\t//* Get maximum length of process arguments\n\t\targ_max = sysconf(_SC_ARG_MAX);\n\n\t\t//? Init for namespace Cpu\n\t\tCpu::current_cpu.core_percent.insert(Cpu::current_cpu.core_percent.begin(), Shared::coreCount, {});\n\t\tCpu::current_cpu.temp.insert(Cpu::current_cpu.temp.begin(), Shared::coreCount + 1, {});\n\t\tCpu::core_old_totals.insert(Cpu::core_old_totals.begin(), Shared::coreCount, 0);\n\t\tCpu::core_old_idles.insert(Cpu::core_old_idles.begin(), Shared::coreCount, 0);\n\t\tLogger::debug(\"Init -> Cpu::collect()\");\n\t\tCpu::collect();\n\t\tfor (auto &[field, vec] : Cpu::current_cpu.cpu_percent) {\n\t\t\tif (not vec.empty() and not v_contains(Cpu::available_fields, field)) Cpu::available_fields.push_back(field);\n\t\t}\n\t\tLogger::debug(\"Init -> Cpu::get_cpuName()\");\n\t\tCpu::cpuName = Cpu::get_cpuName();\n\t\tLogger::debug(\"Init -> Cpu::get_sensors()\");\n\t\tCpu::got_sensors = Cpu::get_sensors();\n\t\tLogger::debug(\"Init -> Cpu::get_core_mapping()\");\n\t\tCpu::core_mapping = Cpu::get_core_mapping();\n\n\t\t//? Init for namespace Mem\n\t\tMem::old_uptime = system_uptime();\n\t\tLogger::debug(\"Init -> Mem::collect()\");\n\t\tMem::collect();\n\t\tLogger::debug(\"Init -> Mem::get_zpools()\");\n\t\tMem::get_zpools();\n\t}\n}  // namespace Shared\n\nnamespace Cpu {\n\tstring cpuName;\n\tstring cpuHz;\n\tbool has_battery = true;\n\ttuple<int, float, long, string> current_bat;\n\n\tconst array<string, 10> time_names = {\"user\", \"nice\", \"system\", \"idle\"};\n\n\tstd::unordered_map<string, long long> cpu_old = {\n\t\t{\"totals\", 0},\n\t\t{\"idles\", 0},\n\t\t{\"user\", 0},\n\t\t{\"nice\", 0},\n\t\t{\"system\", 0},\n\t\t{\"idle\", 0}\n\t};\n\n\tstring get_cpuName() {\n\t\tstring name;\n\t\tchar buffer[1024];\n\t\tsize_t size = sizeof(buffer);\n\t\tif (sysctlbyname(\"hw.model\", &buffer, &size, nullptr, 0) < 0) {\n\t\t\tLogger::error(\"Failed to get CPU name\");\n\t\t\treturn name;\n\t\t}\n\t\treturn trim_name(string(buffer));\n\t}\n\n\tbool get_sensors() {\n\t\tgot_sensors = false;\n\t\tif (Config::getB(\"show_coretemp\") and Config::getB(\"check_temp\")) {\n\t\t\tint32_t temp;\n\t\t\tsize_t size = sizeof(temp);\n\t\t\tif (sysctlbyname(\"dev.cpu.0.temperature\", &temp, &size, nullptr, 0) < 0) {\n\t\t\t\tLogger::warning(\"Could not get temp sensor - maybe you need to load the coretemp module\");\n\t\t\t} else {\n\t\t\t\tgot_sensors = true;\n\t\t\t\tint temp;\n\t\t\t\tsize_t size = sizeof(temp);\n\t\t\t\tsysctlbyname(\"dev.cpu.0.coretemp.tjmax\", &temp, &size, nullptr, 0); //assuming the max temp is same for all cores\n\t\t\t\ttemp = (temp - 2732) / 10; // since it's an int, it's multiplied by 10, and offset to absolute zero...\n\t\t\t\tcurrent_cpu.temp_max = temp;\n\t\t\t}\n\t\t}\n\t\treturn got_sensors;\n\t}\n\n\tvoid update_sensors() {\n\t\tint temp = 0;\n\t\tint p_temp = 0;\n\t\tint found = 0;\n\t\tbool got_package = false;\n\t\tsize_t size = sizeof(p_temp);\n\t\tif (sysctlbyname(\"hw.acpi.thermal.tz0.temperature\", &p_temp, &size, nullptr, 0) >= 0) {\n\t\t\tgot_package = true;\n\t\t\tp_temp = (p_temp - 2732) / 10; // since it's an int, it's multiplied by 10, and offset to absolute zero...\n\t\t}\n\n\t\tsize = sizeof(temp);\n\t\tfor (int i = 0; i < Shared::coreCount; i++) {\n\t\t\tstring s = \"dev.cpu.\" + std::to_string(i) + \".temperature\";\n\t\t\tif (sysctlbyname(s.c_str(), &temp, &size, nullptr, 0) >= 0) {\n\t\t\t\ttemp = (temp - 2732) / 10;\n\t\t\t\tif (not got_package) {\n\t\t\t\t\tp_temp += temp;\n\t\t\t\t\tfound++;\n\t\t\t\t}\n\t\t\t\tif (cmp_less(i + 1, current_cpu.temp.size())) {\n\t\t\t\t\tcurrent_cpu.temp.at(i + 1).push_back(temp);\n\t\t\t\t\tif (current_cpu.temp.at(i + 1).size() > 20)\n\t\t\t\t\t\tcurrent_cpu.temp.at(i + 1).pop_front();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (not got_package) p_temp /= found;\n\t\tcurrent_cpu.temp.at(0).push_back(p_temp);\n\t\tif (current_cpu.temp.at(0).size() > 20)\n\t\t\tcurrent_cpu.temp.at(0).pop_front();\n\n\t}\n\n\tstring get_cpuHz() {\n\t\tunsigned int freq = 1;\n\t\tsize_t size = sizeof(freq);\n\n\t\tif (sysctlbyname(\"dev.cpu.0.freq\", &freq, &size, nullptr, 0) < 0) {\n\t\t\treturn \"\";\n\t\t}\n\t\treturn std::to_string(freq / 1000.0 ).substr(0, 3); // seems to be in MHz\n\t}\n\n\tauto get_core_mapping() -> std::unordered_map<int, int> {\n\t\tstd::unordered_map<int, int> core_map;\n\t\tif (cpu_temp_only) return core_map;\n\n\t\tfor (long i = 0; i < Shared::coreCount; i++) {\n\t\t\tcore_map[i] = i;\n\t\t}\n\n\t\t//? If core mapping from cpuinfo was incomplete try to guess remainder, if missing completely, map 0-0 1-1 2-2 etc.\n\t\tif (cmp_less(core_map.size(), Shared::coreCount)) {\n\t\t\tif (Shared::coreCount % 2 == 0 and (long) core_map.size() == Shared::coreCount / 2) {\n\t\t\t\tfor (int i = 0, n = 0; i < Shared::coreCount / 2; i++) {\n\t\t\t\t\tif (std::cmp_greater_equal(n, core_sensors.size())) n = 0;\n\t\t\t\t\tcore_map[Shared::coreCount / 2 + i] = n++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcore_map.clear();\n\t\t\t\tfor (int i = 0, n = 0; i < Shared::coreCount; i++) {\n\t\t\t\t\tif (std::cmp_greater_equal(n, core_sensors.size())) n = 0;\n\t\t\t\t\tcore_map[i] = n++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//? Apply user set custom mapping if any\n\t\tconst auto &custom_map = Config::getS(\"cpu_core_map\");\n\t\tif (not custom_map.empty()) {\n\t\t\ttry {\n\t\t\t\tfor (const auto &split : ssplit(custom_map)) {\n\t\t\t\t\tconst auto vals = ssplit(split, ':');\n\t\t\t\t\tif (vals.size() != 2) continue;\n\t\t\t\t\tint change_id = std::stoi(vals.at(0));\n\t\t\t\t\tint new_id = std::stoi(vals.at(1));\n\t\t\t\t\tif (not core_map.contains(change_id) or cmp_greater(new_id, core_sensors.size())) continue;\n\t\t\t\t\tcore_map.at(change_id) = new_id;\n\t\t\t\t}\n\t\t\t} catch (...) {\n\t\t\t}\n\t\t}\n\n\t\treturn core_map;\n\t}\n\n\tauto get_battery() -> tuple<int, float, long, string> {\n\t\tif (not has_battery) return {0, 0, 0, \"\"};\n\n\t\tlong seconds = -1;\n\t\tfloat watts = -1;\n\t\tuint32_t percent = -1;\n\t\tsize_t size = sizeof(percent);\n\t\tstring status = \"discharging\";\n\t\tif (sysctlbyname(\"hw.acpi.battery.life\", &percent, &size, nullptr, 0) < 0) {\n\t\t\thas_battery = false;\n\t\t} else {\n\t\t\thas_battery = true;\n\t\t\tsize_t size = sizeof(seconds);\n\t\t\tif (sysctlbyname(\"hw.acpi.battery.time\", &seconds, &size, nullptr, 0) < 0) {\n\t\t\t\tseconds = 0;\n\t\t\t}\n\t\t\tsize = sizeof(watts);\n\t\t\tif (sysctlbyname(\"hw.acpi.battery.rate\", &watts, &size, nullptr, 0) < 0) {\n\t\t\t\twatts = -1;\n\t\t\t}\n\t\t\tint state;\n\t\t\tsize = sizeof(state);\n\t\t\tif (sysctlbyname(\"hw.acpi.battery.state\", &state, &size, nullptr, 0) < 0) {\n\t\t\t\tstatus = \"unknown\";\n\t\t\t} else {\n\t\t\t\tif (state == 2) {\n\t\t\t\t\tstatus = \"charging\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (percent == 100) {\n\t\t\t\tstatus = \"full\";\n\t\t\t}\n\t\t}\n\n\t\treturn {percent, watts, seconds, status};\n\t}\n\n\tauto collect(bool no_update) -> cpu_info & {\n\t\tif (Runner::stopping or (no_update and not current_cpu.cpu_percent.at(\"total\").empty()))\n\t\t\treturn current_cpu;\n\t\tauto &cpu = current_cpu;\n\n\t\tif (getloadavg(cpu.load_avg.data(), cpu.load_avg.size()) < 0) {\n\t\t\tLogger::error(\"failed to get load averages\");\n\t\t}\n\n\t\tvector<array<long, CPUSTATES>> cpu_time(Shared::coreCount);\n\t\tsize_t size = sizeof(long) * CPUSTATES * Shared::coreCount;\n\t\tif (sysctlbyname(\"kern.cp_times\", &cpu_time[0], &size, nullptr, 0) == -1) {\n\t\t\tLogger::error(\"failed to get CPU times\");\n\t\t}\n\t\tlong long global_totals = 0;\n\t\tlong long global_idles = 0;\n\t\tvector<long long> times_summed = {0, 0, 0, 0};\n\n\t\tfor (long i = 0; i < Shared::coreCount; i++) {\n\t\t\tvector<long long> times;\n\t\t\t//? 0=user, 1=nice, 2=system, 3=idle\n\t\t\tfor (int x = 0; const unsigned int c_state : {CP_USER, CP_NICE, CP_SYS, CP_IDLE}) {\n\t\t\t\tauto val = cpu_time[i][c_state];\n\t\t\t\ttimes.push_back(val);\n\t\t\t\ttimes_summed.at(x++) += val;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\t//? All values\n\t\t\t\tconst long long totals = std::accumulate(times.begin(), times.end(), 0ll);\n\n\t\t\t\t//? Idle time\n\t\t\t\tconst long long idles = times.at(3);\n\n\t\t\t\tglobal_totals += totals;\n\t\t\t\tglobal_idles += idles;\n\n\t\t\t\t//? Calculate cpu total for each core\n\t\t\t\tif (i > Shared::coreCount) break;\n\t\t\t\tconst long long calc_totals = max(0ll, totals - core_old_totals.at(i));\n\t\t\t\tconst long long calc_idles = max(0ll, idles - core_old_idles.at(i));\n\t\t\t\tcore_old_totals.at(i) = totals;\n\t\t\t\tcore_old_idles.at(i) = idles;\n\n\t\t\t\tcpu.core_percent.at(i).push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));\n\n\t\t\t\t//? Reduce size if there are more values than needed for graph\n\t\t\t\tif (cpu.core_percent.at(i).size() > 40) cpu.core_percent.at(i).pop_front();\n\n\t\t\t} catch (const std::exception &e) {\n\t\t\t\tLogger::error(\"Cpu::collect() : {}\", e.what());\n\t\t\t\tthrow std::runtime_error(fmt::format(\"collect() : {}\", e.what()));\n\t\t\t}\n\n\t\t}\n\n\t\tconst long long calc_totals = max(1ll, global_totals - cpu_old.at(\"totals\"));\n\t\tconst long long calc_idles = max(1ll, global_idles - cpu_old.at(\"idles\"));\n\n\t\t//? Populate cpu.cpu_percent with all fields from syscall\n\t\tfor (int ii = 0; const auto &val : times_summed) {\n\t\t\tcpu.cpu_percent.at(time_names.at(ii)).push_back(clamp((long long)round((double)(val - cpu_old.at(time_names.at(ii))) * 100 / calc_totals), 0ll, 100ll));\n\t\t\tcpu_old.at(time_names.at(ii)) = val;\n\n\t\t\t//? Reduce size if there are more values than needed for graph\n\t\t\twhile (cmp_greater(cpu.cpu_percent.at(time_names.at(ii)).size(), width * 2)) cpu.cpu_percent.at(time_names.at(ii)).pop_front();\n\n\t\t\tii++;\n\t\t}\n\n\t\tcpu_old.at(\"totals\") = global_totals;\n\t\tcpu_old.at(\"idles\") = global_idles;\n\n\t\t//? Total usage of cpu\n\t\tcpu.cpu_percent.at(\"total\").push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));\n\n\t\t//? Reduce size if there are more values than needed for graph\n\t\twhile (cmp_greater(cpu.cpu_percent.at(\"total\").size(), width * 2)) cpu.cpu_percent.at(\"total\").pop_front();\n\n\t\tif (Config::getB(\"show_cpu_freq\")) {\n\t\t\tauto hz = get_cpuHz();\n\t\t\tif (hz != \"\") {\n\t\t\t\tcpuHz = hz;\n\t\t\t}\n\t\t}\n\n\t\tif (Config::getB(\"check_temp\") and got_sensors)\n\t\t\tupdate_sensors();\n\n\t\tif (Config::getB(\"show_battery\") and has_battery)\n\t\t\tcurrent_bat = get_battery();\n\n\t\treturn cpu;\n\t}\n}  // namespace Cpu\n\nnamespace Mem {\n\tbool has_swap = false;\n\tvector<string> fstab;\n\tfs::file_time_type fstab_time;\n\tint disk_ios = 0;\n\tvector<string> last_found;\n\n\tmem_info current_mem{};\n\n\tuint64_t get_totalMem() {\n\t\treturn Shared::totalMem;\n\t}\n\n\tvoid assign_values(struct disk_info& disk, int64_t readBytes, int64_t writeBytes) {\n\t\tdisk_ios++;\n\t\tif (disk.io_read.empty()) {\n\t\t\tdisk.io_read.push_back(0);\n\t\t} else {\n\t\t\tdisk.io_read.push_back(max((int64_t)0, (readBytes - disk.old_io.at(0))));\n\t\t}\n\t\tdisk.old_io.at(0) = readBytes;\n\t\twhile (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front();\n\n\t\tif (disk.io_write.empty()) {\n\t\t\tdisk.io_write.push_back(0);\n\t\t} else {\n\t\t\tdisk.io_write.push_back(max((int64_t)0, (writeBytes - disk.old_io.at(1))));\n\t\t}\n\t\tdisk.old_io.at(1) = writeBytes;\n\t\twhile (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front();\n\n\t\t// no io times - need to push something anyway or we'll get an ABORT\n\t\tif (disk.io_activity.empty())\n\t\t\tdisk.io_activity.push_back(0);\n\t\telse\n\t\t\tdisk.io_activity.push_back(clamp((long)round((double)(disk.io_write.back() + disk.io_read.back()) / (1 << 20)), 0l, 100l));\n\t\twhile (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();\n\t}\n\n\tclass PipeWrapper {\n\t\tpublic:\n\t\t\tPipeWrapper(const char *file, const char *mode) {fd = popen(file, mode);}\n\t\t\tvirtual ~PipeWrapper() {if (fd) pclose(fd);}\n\t\t\tauto operator()() -> FILE* { return fd;};\n\t\tprivate:\n\t\t\tFILE *fd;\n\t};\n\n\t// find all zpools in the system. Do this only at startup.\n\tvoid get_zpools() {\n\t\tstd::regex toReplace(\"\\\\.\");\n\t\tPipeWrapper poolPipe = PipeWrapper(\"zpool list -H -o name\", \"r\");\n\n\t\twhile (not std::feof(poolPipe())) {\n\t\t\tchar poolName[512];\n\t\t\tsize_t len = 512;\n\t\t\tif (fgets(poolName, len, poolPipe())) {\n\t\t\t\tpoolName[strcspn(poolName, \"\\n\")] = 0;\n\t\t\t\tLogger::debug(\"zpool found: {}\", poolName);\n\t\t\t\tMem::zpools.push_back(std::regex_replace(poolName, toReplace, \"%25\"));\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid collect_disk(std::unordered_map<string, disk_info> &disks, std::unordered_map<string, string> &mapping) {\n\t\t// this bit is for 'regular' mounts\n\t\tstatic struct statinfo cur;\n\t\tlong double etime = 0;\n\t\tuint64_t total_bytes_read;\n\t\tuint64_t total_bytes_write;\n\n\t\tstatic std::unique_ptr<struct devinfo, decltype(std::free)*> curDevInfo (reinterpret_cast<struct devinfo*>(std::calloc(1, sizeof(struct devinfo))), std::free);\n\t\tcur.dinfo = curDevInfo.get();\n\n\t\tif (devstat_getdevs(nullptr, &cur) != -1) {\n\t\t\tfor (int i = 0; i < cur.dinfo->numdevs; i++) {\n\t\t\t\tauto d = cur.dinfo->devices[i];\n\t\t\t\tstring devStatName = \"/dev/\" + string(d.device_name) + std::to_string(d.unit_number);\n\t\t\t\tfor (auto& [ignored, disk] : disks) { // find matching mountpoints - could be multiple as d.device_name is only ada (and d.unit_number is the device number), while the disk.dev is like /dev/ada0s1\n\t\t\t\t\tif (disk.dev.string().rfind(devStatName, 0) == 0 and mapping.contains(disk.dev)) {\n\t\t\t\t\t\tdevstat_compute_statistics(&d, nullptr, etime, DSM_TOTAL_BYTES_READ, &total_bytes_read, DSM_TOTAL_BYTES_WRITE, &total_bytes_write, DSM_NONE);\n\t\t\t\t\t\tassign_values(disk, total_bytes_read, total_bytes_write);\n\t\t\t\t\t\tstring mountpoint = mapping.at(disk.dev);\n\t\t\t\t\t\tLogger::debug(\"dev {} -> {} read={} write={}\", devStatName, mountpoint, total_bytes_read, total_bytes_write);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\t// this code is for ZFS mounts\n\t\tfor (const auto &poolName : Mem::zpools) {\n\t\t\tchar sysCtl[1024];\n\t\t\tsnprintf(sysCtl, sizeof(sysCtl), \"sysctl kstat.zfs.%s.dataset | grep -E \\'dataset_name|nread|nwritten\\'\", poolName.c_str());\n\t\t\tPipeWrapper f = PipeWrapper(sysCtl, \"r\");\n\t\t\tif (f()) {\n\t\t\t\tchar buf[512];\n\t\t\t\tsize_t len = 512;\n\t\t\t\tuint64_t nread = 0, nwritten = 0;\n\t\t\t\twhile (not std::feof(f())) {\n\t\t\t\t\tif (fgets(buf, len, f())) {\n\t\t\t\t\t\tchar *name = std::strtok(buf, \": \\n\");\n\t\t\t\t\t\tchar *value = std::strtok(nullptr, \": \\n\");\n\t\t\t\t\t\tif (string(name).find(\"dataset_name\") != string::npos) {\n\t\t\t\t\t\t\t// create entry if datasetname matches with anything in mapping\n\t\t\t\t\t\t\t// relies on the fact that the dataset name is last value in the list\n\t\t\t\t\t\t\t// alternatively you could parse the objset-0x... when this changes, you have a new entry\n\t\t\t\t\t\t\tstring datasetname = string(value);// this is the zfs volume, like 'zroot/usr/home' -> this maps onto the device we get back from getmntinfo(3)\n\t\t\t\t\t\t\tif (mapping.contains(datasetname)) {\n\t\t\t\t\t\t\t\tstring mountpoint = mapping.at(datasetname);\n\t\t\t\t\t\t\t\tif (disks.contains(mountpoint)) {\n\t\t\t\t\t\t\t\t\tauto& disk = disks.at(mountpoint);\n\t\t\t\t\t\t\t\t\tassign_values(disk, nread, nwritten);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (string(name).find(\"nread\") != string::npos) {\n\t\t\t\t\t\t\tnread = atoll(value);\n\t\t\t\t\t\t} else if (string(name).find(\"nwritten\") != string::npos) {\n\t\t\t\t\t\t\tnwritten = atoll(value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tauto collect(bool no_update) -> mem_info & {\n\t\tif (Runner::stopping or (no_update and not current_mem.percent.at(\"used\").empty()))\n\t\t\treturn current_mem;\n\n\t\tauto show_swap = Config::getB(\"show_swap\");\n\t\tauto show_disks = Config::getB(\"show_disks\");\n\t\tauto swap_disk = Config::getB(\"swap_disk\");\n\t\tauto &mem = current_mem;\n\t\tstatic bool snapped = (getenv(\"BTOP_SNAPPED\") != nullptr);\n\n\t\tint mib[4];\n\t\tu_int memActive, memWire, cachedMem, freeMem;\n\t\tsize_t len;\n\n   \t\tlen = 4; sysctlnametomib(\"vm.stats.vm.v_active_count\", mib, &len);\n\t\tlen = sizeof(memActive);\n\t\tsysctl(mib, 4, &(memActive), &len, nullptr, 0);\n\t\tmemActive *= Shared::pageSize;\n\n\t\tlen = 4; sysctlnametomib(\"vm.stats.vm.v_wire_count\", mib, &len);\n\t\tlen = sizeof(memWire);\n\t\tsysctl(mib, 4, &(memWire), &len, nullptr, 0);\n\t\tmemWire *= Shared::pageSize;\n\n\t\tmem.stats.at(\"used\") = memWire + memActive;\n\t\tmem.stats.at(\"available\") = Shared::totalMem - memActive - memWire;\n\n\t\tlen = sizeof(cachedMem);\n   \t\tlen = 4; sysctlnametomib(\"vm.stats.vm.v_cache_count\", mib, &len);\n   \t\tsysctl(mib, 4, &(cachedMem), &len, nullptr, 0);\n   \t\tcachedMem *= Shared::pageSize;\n   \t\tmem.stats.at(\"cached\") = cachedMem;\n\n\t\tlen = sizeof(freeMem);\n   \t\tlen = 4; sysctlnametomib(\"vm.stats.vm.v_free_count\", mib, &len);\n   \t\tsysctl(mib, 4, &(freeMem), &len, nullptr, 0);\n   \t\tfreeMem *= Shared::pageSize;\n   \t\tmem.stats.at(\"free\") = freeMem;\n\n\t\tif (show_swap) {\n\t\t\tchar buf[_POSIX2_LINE_MAX];\n\t\t\tShared::KvmPtr kd {kvm_openfiles(nullptr, _PATH_DEVNULL, nullptr, O_RDONLY, buf)}; \n   \t\t\tstruct kvm_swap swap[16];\n   \t\t\tint nswap = kvm_getswapinfo(kd.get(), swap, 16, 0);\n\t\t\tint totalSwap = 0, usedSwap = 0;\n\t\t\tfor (int i = 0; i < nswap; i++) {\n\t\t\t\ttotalSwap += swap[i].ksw_total;\n\t\t\t\tusedSwap += swap[i].ksw_used;\n\t\t\t}\n\t\t\tmem.stats.at(\"swap_total\") = totalSwap * Shared::pageSize;\n\t\t\tmem.stats.at(\"swap_used\") = usedSwap * Shared::pageSize;\n\t\t}\n\n\t\tif (show_swap and mem.stats.at(\"swap_total\") > 0) {\n\t\t\tfor (const auto &name : swap_names) {\n\t\t\t\tmem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / mem.stats.at(\"swap_total\")));\n\t\t\t\twhile (cmp_greater(mem.percent.at(name).size(), width * 2))\n\t\t\t\t\tmem.percent.at(name).pop_front();\n\t\t\t}\n\t\t\thas_swap = true;\n\t\t} else\n\t\t\thas_swap = false;\n\t\t//? Calculate percentages\n\t\tfor (const auto &name : mem_names) {\n\t\t\tmem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / Shared::totalMem));\n\t\t\twhile (cmp_greater(mem.percent.at(name).size(), width * 2))\n\t\t\t\tmem.percent.at(name).pop_front();\n\t\t}\n\n\t\tif (show_disks) {\n\t\t\tstd::unordered_map<string, string> mapping;  // keep mapping from device -> mountpoint, since IOKit doesn't give us the mountpoint\n\t\t\tdouble uptime = system_uptime();\n\t\t\tauto &disks_filter = Config::getS(\"disks_filter\");\n\t\t\tbool filter_exclude = false;\n\t\t\t// auto only_physical = Config::getB(\"only_physical\");\n\t\t\tauto &disks = mem.disks;\n\t\t\tvector<string> filter;\n\t\t\tif (not disks_filter.empty()) {\n\t\t\t\tfilter = ssplit(disks_filter);\n\t\t\t\tif (filter.at(0).starts_with(\"exclude=\")) {\n\t\t\t\t\tfilter_exclude = true;\n\t\t\t\t\tfilter.at(0) = filter.at(0).substr(8);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstruct statfs *stfs;\n\t\t\tint count = getmntinfo(&stfs, MNT_WAIT);\n\t\t\tvector<string> found;\n\t\t\tfound.reserve(last_found.size());\n\t\t\tfor (int i = 0; i < count; i++) {\n\t\t\t\tauto fstype = string(stfs[i].f_fstypename);\n\t\t\t\tif (fstype == \"autofs\" || fstype == \"devfs\" || fstype == \"linprocfs\" || fstype == \"procfs\" || fstype == \"tmpfs\" || fstype == \"linsysfs\" ||\n\t\t\t\t\tfstype == \"fdesckfs\") {\n\t\t\t\t\t// in memory filesystems -> not useful to show\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tstd::error_code ec;\n\t\t\t\tstring mountpoint = stfs[i].f_mntonname;\n\t\t\t\tstring dev = stfs[i].f_mntfromname;\n\t\t\t\tmapping[dev] = mountpoint;\n\n\t\t\t\t//? Match filter if not empty\n\t\t\t\tif (not filter.empty()) {\n\t\t\t\t\tbool match = v_contains(filter, mountpoint);\n\t\t\t\t\tif ((filter_exclude and match) or (not filter_exclude and not match))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfound.push_back(mountpoint);\n\t\t\t\tif (not disks.contains(mountpoint)) {\n\t\t\t\t\tdisks[mountpoint] = disk_info{fs::canonical(dev, ec), fs::path(mountpoint).filename()};\n\n\t\t\t\t\tif (disks.at(mountpoint).dev.empty())\n\t\t\t\t\t\tdisks.at(mountpoint).dev = dev;\n\n\t\t\t\t\tif (disks.at(mountpoint).name.empty())\n\t\t\t\t\t\tdisks.at(mountpoint).name = (mountpoint == \"/\" ? \"root\" : mountpoint);\n\t\t\t\t}\n\n\n\t\t\t\tif (not v_contains(last_found, mountpoint))\n\t\t\t\t\tredraw = true;\n\n\t\t\t\tdisks.at(mountpoint).free = stfs[i].f_bfree;\n\t\t\t\tdisks.at(mountpoint).total = stfs[i].f_iosize;\n\t\t\t}\n\n\t\t\t//? Remove disks no longer mounted or filtered out\n\t\t\tif (swap_disk and has_swap) found.push_back(\"swap\");\n\t\t\tfor (auto it = disks.begin(); it != disks.end();) {\n\t\t\t\tif (not v_contains(found, it->first))\n\t\t\t\t\tit = disks.erase(it);\n\t\t\t\telse\n\t\t\t\t\tit++;\n\t\t\t}\n\t\t\tif (found.size() != last_found.size()) redraw = true;\n\t\t\tlast_found = std::move(found);\n\n\t\t\t//? Get disk/partition stats\n\t\t\tfor (auto &[mountpoint, disk] : disks) {\n\t\t\t\tif (std::error_code ec; not fs::exists(mountpoint, ec))\n\t\t\t\t\tcontinue;\n\t\t\t\tstruct statvfs vfs;\n\t\t\t\tif (statvfs(mountpoint.c_str(), &vfs) < 0) {\n\t\t\t\t\tLogger::warning(\"Failed to get disk/partition stats with statvfs() for: {}\", mountpoint);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tdisk.total = vfs.f_blocks * vfs.f_frsize;\n\t\t\t\tdisk.free = vfs.f_bfree * vfs.f_frsize;\n\t\t\t\tdisk.used = disk.total - disk.free;\n\t\t\t\tif (disk.total != 0) {\n\t\t\t\t\tdisk.used_percent = round((double)disk.used * 100 / disk.total);\n\t\t\t\t\tdisk.free_percent = 100 - disk.used_percent;\n\t\t\t\t} else {\n\t\t\t\t\tdisk.used_percent = 0;\n\t\t\t\t\tdisk.free_percent = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Setup disks order in UI and add swap if enabled\n\t\t\tmem.disks_order.clear();\n\t\t\tif (snapped and disks.contains(\"/mnt\"))\n\t\t\t\tmem.disks_order.push_back(\"/mnt\");\n\t\t\telse if (disks.contains(\"/\"))\n\t\t\t\tmem.disks_order.push_back(\"/\");\n\t\t\tif (swap_disk and has_swap) {\n\t\t\t\tmem.disks_order.push_back(\"swap\");\n\t\t\t\tif (not disks.contains(\"swap\"))\n\t\t\t\t\tdisks[\"swap\"] = {\"\", \"swap\"};\n\t\t\t\tdisks.at(\"swap\").total = mem.stats.at(\"swap_total\");\n\t\t\t\tdisks.at(\"swap\").used = mem.stats.at(\"swap_used\");\n\t\t\t\tdisks.at(\"swap\").free = mem.stats.at(\"swap_free\");\n\t\t\t\tdisks.at(\"swap\").used_percent = mem.percent.at(\"swap_used\").back();\n\t\t\t\tdisks.at(\"swap\").free_percent = mem.percent.at(\"swap_free\").back();\n\t\t\t}\n\t\t\tfor (const auto &name : last_found)\n\t\t\t\tif (not is_in(name, \"/\", \"swap\", \"/dev\"))\n\t\t\t\t\tmem.disks_order.push_back(name);\n\n\t\t\tdisk_ios = 0;\n\t\t\tcollect_disk(disks, mapping);\n\n\t\t\told_uptime = uptime;\n\t\t}\n\t\treturn mem;\n\t}\n\n}  // namespace Mem\n\nnamespace Net {\n\tstd::unordered_map<string, net_info> current_net;\n\tnet_info empty_net = {};\n\tvector<string> interfaces;\n\tstring selected_iface;\n\tint errors = 0;\n\tstd::unordered_map<string, uint64_t> graph_max = {{\"download\", {}}, {\"upload\", {}}};\n\tstd::unordered_map<string, array<int, 2>> max_count = {{\"download\", {}}, {\"upload\", {}}};\n\tbool rescale = true;\n\tuint64_t timestamp = 0;\n\n\tauto collect(bool no_update) -> net_info & {\n\t\tauto &net = current_net;\n\t\tauto &config_iface = Config::getS(\"net_iface\");\n\t\tauto net_sync = Config::getB(\"net_sync\");\n\t\tauto net_auto = Config::getB(\"net_auto\");\n\t\tauto new_timestamp = time_ms();\n\n\t\tif (not no_update and errors < 3) {\n\t\t\t//? Get interface list using getifaddrs() wrapper\n\t\t\tIfAddrsPtr if_addrs {};\n\t\t\tif (if_addrs.get_status() != 0) {\n\t\t\t\terrors++;\n\t\t\t\tLogger::error(\"Net::collect() -> getifaddrs() failed with id {}\", if_addrs.get_status());\n\t\t\t\tredraw = true;\n\t\t\t\treturn empty_net;\n\t\t\t}\n\t\t\tint family = 0;\n\t\t\tstatic_assert(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN); // 46 >= 16, compile-time assurance.\n\t\t\tenum { IPBUFFER_MAXSIZE = INET6_ADDRSTRLEN }; // manually using the known biggest value, guarded by the above static_assert\n\t\t\tchar ip[IPBUFFER_MAXSIZE];\n\t\t\tinterfaces.clear();\n\t\t\tstring ipv4, ipv6;\n\n\t\t\t//? Iteration over all items in getifaddrs() list\n\t\t\tfor (auto *ifa = if_addrs.get(); ifa != nullptr; ifa = ifa->ifa_next) {\n\t\t\t\tif (ifa->ifa_addr == nullptr) continue;\n\t\t\t\tfamily = ifa->ifa_addr->sa_family;\n\t\t\t\tconst auto &iface = ifa->ifa_name;\n\t\t\t\t//? Update available interfaces vector and get status of interface\n\t\t\t\tif (not v_contains(interfaces, iface)) {\n\t\t\t\t\tinterfaces.push_back(iface);\n\t\t\t\t\tnet[iface].connected = (ifa->ifa_flags & IFF_RUNNING);\n\n\t\t\t\t\t// An interface can have more than one IP of the same family associated with it,\n\t\t\t\t\t// but we pick only the first one to show in the NET box.\n\t\t\t\t\t// Note: Interfaces without any IPv4 and IPv6 set are still valid and monitorable!\n\t\t\t\t\tnet[iface].ipv4.clear();\n\t\t\t\t\tnet[iface].ipv6.clear();\n\t\t\t\t}\n\t\t\t\t//? Get IPv4 address\n\t\t\t\tif (family == AF_INET) {\n\t\t\t\t\tif (net[iface].ipv4.empty()) {\n\t\t\t\t\t\tif (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr)->sin_addr), ip, IPBUFFER_MAXSIZE)) {\n\n\t\t\t\t\t\t\tnet[iface].ipv4 = ip;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tint errsv = errno;\n\t\t\t\t\t\t\tLogger::error(\"Net::collect() -> Failed to convert IPv4 to string for iface {}, errno: {}\", iface, strerror(errsv));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? Get IPv6 address\n\t\t\t\telse if (family == AF_INET6) {\n\t\t\t\t\tif (net[iface].ipv6.empty()) {\n\t\t\t\t\t\tif (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr)->sin6_addr), ip, IPBUFFER_MAXSIZE)) {\n\t\t\t\t\t\t\tnet[iface].ipv6 = ip;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tint errsv = errno;\n\t\t\t\t\t\t\tLogger::error(\"Net::collect() -> Failed to convert IPv6 to string for iface {}, errno: {}\", iface, strerror(errsv));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}  //else, ignoring family==AF_LINK (see man 3 getifaddrs)\n\t\t\t}\n\n\t\t\tstd::unordered_map<string, std::tuple<uint64_t, uint64_t>> ifstats;\n\t\t\tint mib[] = {CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, 0};\n\t\t\tsize_t len;\n\t\t\tif (sysctl(mib, 6, nullptr, &len, nullptr, 0) < 0) {\n\t\t\t\tLogger::error(\"failed getting network interfaces\");\n\t\t\t} else {\n\t\t\t\tstd::unique_ptr<char[]> buf(new char[len]);\n\t\t\t\tif (sysctl(mib, 6, buf.get(), &len, nullptr, 0) < 0) {\n\t\t\t\t\tLogger::error(\"failed getting network interfaces\");\n\t\t\t\t} else {\n\t\t\t\t\tchar *lim = buf.get() + len;\n\t\t\t\t\tchar *next = nullptr;\n\t\t\t\t\tfor (next = buf.get(); next < lim;) {\n\t\t\t\t\t\tstruct if_msghdr *ifm = (struct if_msghdr *)next;\n\t\t\t\t\t\tnext += ifm->ifm_msglen;\n\t\t\t\t\t\tstruct if_data ifm_data = ifm->ifm_data;\n\t\t\t\t\t\tif (ifm->ifm_addrs & RTA_IFP) {\n\t\t\t\t\t\t\tstruct sockaddr_dl *sdl = (struct sockaddr_dl *)(ifm + 1);\n\t\t\t\t\t\t\tchar iface[32];\n\t\t\t\t\t\t\tstrncpy(iface, sdl->sdl_data, sdl->sdl_nlen);\n\t\t\t\t\t\t\tiface[sdl->sdl_nlen] = 0;\n\t\t\t\t\t\t\tifstats[iface] = std::tuple(ifm_data.ifi_ibytes, ifm_data.ifi_obytes);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Get total received and transmitted bytes + device address if no ip was found\n\t\t\tfor (const auto &iface : interfaces) {\n\t\t\t\tfor (const string dir : {\"download\", \"upload\"}) {\n\t\t\t\t\tauto &saved_stat = net.at(iface).stat.at(dir);\n\t\t\t\t\tauto &bandwidth = net.at(iface).bandwidth.at(dir);\n\t\t\t\t\tuint64_t val = dir == \"download\" ? std::get<0>(ifstats[iface]) : std::get<1>(ifstats[iface]);\n\n\t\t\t\t\t//? Update speed, total and top values\n\t\t\t\t\tif (val < saved_stat.last) {\n\t\t\t\t\t\tsaved_stat.rollover += saved_stat.last;\n\t\t\t\t\t\tsaved_stat.last = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (cmp_greater((unsigned long long)saved_stat.rollover + (unsigned long long)val, numeric_limits<uint64_t>::max())) {\n\t\t\t\t\t\tsaved_stat.rollover = 0;\n\t\t\t\t\t\tsaved_stat.last = 0;\n\t\t\t\t\t}\n\t\t\t\t\tsaved_stat.speed = round((double)(val - saved_stat.last) / ((double)(new_timestamp - timestamp) / 1000));\n\t\t\t\t\tif (saved_stat.speed > saved_stat.top) saved_stat.top = saved_stat.speed;\n\t\t\t\t\tif (saved_stat.offset > val + saved_stat.rollover) saved_stat.offset = 0;\n\t\t\t\t\tsaved_stat.total = (val + saved_stat.rollover) - saved_stat.offset;\n\t\t\t\t\tsaved_stat.last = val;\n\n\t\t\t\t\t//? Add values to graph\n\t\t\t\t\tbandwidth.push_back(saved_stat.speed);\n\t\t\t\t\twhile (cmp_greater(bandwidth.size(), width * 2)) bandwidth.pop_front();\n\n\t\t\t\t\t//? Set counters for auto scaling\n\t\t\t\t\tif (net_auto and selected_iface == iface) {\n\t\t\t\t\t\tif (saved_stat.speed > graph_max[dir]) {\n\t\t\t\t\t\t\t++max_count[dir][0];\n\t\t\t\t\t\t\tif (max_count[dir][1] > 0) --max_count[dir][1];\n\t\t\t\t\t\t} else if (graph_max[dir] > 10 << 10 and saved_stat.speed < graph_max[dir] / 10) {\n\t\t\t\t\t\t\t++max_count[dir][1];\n\t\t\t\t\t\t\tif (max_count[dir][0] > 0) --max_count[dir][0];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Clean up net map if needed\n\t\t\tif (net.size() > interfaces.size()) {\n\t\t\t\tfor (auto it = net.begin(); it != net.end();) {\n\t\t\t\t\tif (not v_contains(interfaces, it->first))\n\t\t\t\t\t\tit = net.erase(it);\n\t\t\t\t\telse\n\t\t\t\t\t\tit++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttimestamp = new_timestamp;\n\t\t}\n\t\t//? Return empty net_info struct if no interfaces was found\n\t\tif (net.empty())\n\t\t\treturn empty_net;\n\n\t\t//? Find an interface to display if selected isn't set or valid\n\t\tif (selected_iface.empty() or not v_contains(interfaces, selected_iface)) {\n\t\t\tmax_count[\"download\"][0] = max_count[\"download\"][1] = max_count[\"upload\"][0] = max_count[\"upload\"][1] = 0;\n\t\t\tredraw = true;\n\t\t\tif (net_auto) rescale = true;\n\t\t\tif (not config_iface.empty() and v_contains(interfaces, config_iface))\n\t\t\t\tselected_iface = config_iface;\n\t\t\telse {\n\t\t\t\t//? Sort interfaces by total upload + download bytes\n\t\t\t\tauto sorted_interfaces = interfaces;\n\t\t\t\trng::sort(sorted_interfaces, [&](const auto &a, const auto &b) {\n\t\t\t\t\treturn cmp_greater(net.at(a).stat[\"download\"].total + net.at(a).stat[\"upload\"].total,\n\t\t\t\t\t\t\t\t\t   net.at(b).stat[\"download\"].total + net.at(b).stat[\"upload\"].total);\n\t\t\t\t});\n\t\t\t\tselected_iface.clear();\n\t\t\t\t//? Try to set to a connected interface\n\t\t\t\tfor (const auto &iface : sorted_interfaces) {\n\t\t\t\t\tif (net.at(iface).connected) selected_iface = iface;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t//? If no interface is connected set to first available\n\t\t\t\tif (selected_iface.empty() and not sorted_interfaces.empty())\n\t\t\t\t\tselected_iface = sorted_interfaces.at(0);\n\t\t\t\telse if (sorted_interfaces.empty())\n\t\t\t\t\treturn empty_net;\n\t\t\t}\n\t\t}\n\n\t\t//? Calculate max scale for graphs if needed\n\t\tif (net_auto) {\n\t\t\tbool sync = false;\n\t\t\tfor (const auto &dir : {\"download\", \"upload\"}) {\n\t\t\t\tfor (const auto &sel : {0, 1}) {\n\t\t\t\t\tif (rescale or max_count[dir][sel] >= 5) {\n\t\t\t\t\t\tconst long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: net[selected_iface].stat[dir].speed);\n\t\t\t\t\t\tgraph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10);\n\t\t\t\t\t\tmax_count[dir][0] = max_count[dir][1] = 0;\n\t\t\t\t\t\tredraw = true;\n\t\t\t\t\t\tif (net_sync) sync = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? Sync download/upload graphs if enabled\n\t\t\t\tif (sync) {\n\t\t\t\t\tconst auto other = (string(dir) == \"upload\" ? \"download\" : \"upload\");\n\t\t\t\t\tgraph_max[other] = graph_max[dir];\n\t\t\t\t\tmax_count[other][0] = max_count[other][1] = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trescale = false;\n\t\treturn net.at(selected_iface);\n\t}\n}  // namespace Net\n\nnamespace Proc {\n\n\tvector<proc_info> current_procs;\n\tstd::unordered_map<string, string> uid_user;\n\tstring current_sort;\n\tstring current_filter;\n\tbool current_rev = false;\n\tbool is_tree_mode;\n\n\tfs::file_time_type passwd_time;\n\n\tuint64_t cputimes;\n\tint collapse = -1, expand = -1, toggle_children = -1;\n\tuint64_t old_cputimes = 0;\n\tatomic<int> numpids = 0;\n\tint filter_found = 0;\n\n\tdetail_container detailed;\n\tstatic std::unordered_set<size_t> dead_procs;\n\n\tstring get_status(char s) {\n\t\tif (s & SRUN) return \"Running\";\n\t\tif (s & SSLEEP) return \"Sleeping\";\n\t\tif (s & SIDL) return \"Idle\";\n\t\tif (s & SSTOP) return \"Stopped\";\n\t\tif (s & SZOMB) return \"Zombie\";\n\t\treturn \"Unknown\";\n\t}\n\n\t//* Get detailed info for selected process\n\tvoid _collect_details(const size_t pid, vector<proc_info> &procs) {\n\t\tif (pid != detailed.last_pid) {\n\t\t\tdetailed = {};\n\t\t\tdetailed.last_pid = pid;\n\t\t\tdetailed.skip_smaps = not Config::getB(\"proc_info_smaps\");\n\t\t}\n\n\t\t//? Copy proc_info for process from proc vector\n\t\tauto p_info = rng::find(procs, pid, &proc_info::pid);\n\t\tdetailed.entry = *p_info;\n\n\t\t//? Update cpu percent deque for process cpu graph\n\t\tif (not Config::getB(\"proc_per_core\")) detailed.entry.cpu_p *= Shared::coreCount;\n\t\tdetailed.cpu_percent.push_back(clamp((long long)round(detailed.entry.cpu_p), 0ll, 100ll));\n\t\twhile (cmp_greater(detailed.cpu_percent.size(), width)) detailed.cpu_percent.pop_front();\n\n\t\t//? Process runtime : current time - start time (both in unix time - seconds since epoch)\n\t\tstruct timeval currentTime;\n\t\tgettimeofday(&currentTime, nullptr);\n\t\t// only interested in second granularity, so ignoring tc_usec\n\t\tif (detailed.entry.state != 'X') detailed.elapsed = sec_to_dhms(currentTime.tv_sec - detailed.entry.cpu_s); \n\t\telse detailed.elapsed = sec_to_dhms(detailed.entry.death_time);\n\t\tif (detailed.elapsed.size() > 8) detailed.elapsed.resize(detailed.elapsed.size() - 3);\n\n\t\t//? Get parent process name\n\t\tif (detailed.parent.empty()) {\n\t\t\tauto p_entry = rng::find(procs, detailed.entry.ppid, &proc_info::pid);\n\t\t\tif (p_entry != procs.end()) detailed.parent = p_entry->name;\n\t\t}\n\n\t\t//? Expand process status from single char to explanative string\n\t\tdetailed.status = get_status(detailed.entry.state);\n\n\t\tdetailed.mem_bytes.push_back(detailed.entry.mem);\n\t\tdetailed.memory = floating_humanizer(detailed.entry.mem);\n\n\t\tif (detailed.first_mem == -1 or detailed.first_mem < detailed.mem_bytes.back() / 2 or detailed.first_mem > detailed.mem_bytes.back() * 4) {\n\t\t\tdetailed.first_mem = min((uint64_t)detailed.mem_bytes.back() * 2, Mem::get_totalMem());\n\t\t\tredraw = true;\n\t\t}\n\n\t\twhile (cmp_greater(detailed.mem_bytes.size(), width)) detailed.mem_bytes.pop_front();\n\n\t\t// rusage_info_current rusage;\n\t\t// if (proc_pid_rusage(pid, RUSAGE_INFO_CURRENT, (void **)&rusage) == 0) {\n\t\t// \t// this fails for processes we don't own - same as in Linux\n\t\t// \tdetailed.io_read = floating_humanizer(rusage.ri_diskio_bytesread);\n\t\t// \tdetailed.io_write = floating_humanizer(rusage.ri_diskio_byteswritten);\n\t\t// }\n\t}\n\n\t//* Collects and sorts process information from /proc\n\tauto collect(bool no_update) -> vector<proc_info> & {\n\t\tconst auto &sorting = Config::getS(\"proc_sorting\");\n\t\tauto reverse = Config::getB(\"proc_reversed\");\n\t\tconst auto &filter = Config::getS(\"proc_filter\");\n\t\tauto per_core = Config::getB(\"proc_per_core\");\n\t\tauto tree = Config::getB(\"proc_tree\");\n\t\tauto show_detailed = Config::getB(\"show_detailed\");\n\t\tconst auto pause_proc_list = Config::getB(\"pause_proc_list\");\n\t\tconst size_t detailed_pid = Config::getI(\"detailed_pid\");\n\t\tbool should_filter = current_filter != filter;\n\t\tif (should_filter) current_filter = filter;\n\t\tbool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter);\n\t\tbool tree_mode_change = tree != is_tree_mode;\n\t\tif (sorted_change) {\n\t\t\tcurrent_sort = sorting;\n\t\t\tcurrent_rev = reverse;\n\t\t}\n\t\tif (tree_mode_change) is_tree_mode = tree;\n\n\t\tconst int cmult = (per_core) ? Shared::coreCount : 1;\n\t\tbool got_detailed = false;\n\n\t\tstatic vector<size_t> found;\n\n\t\tvector<array<long, CPUSTATES>> cpu_time(Shared::coreCount);\n\t\tsize_t size = sizeof(long) * CPUSTATES * Shared::coreCount;\n\t\tif (sysctlbyname(\"kern.cp_times\", &cpu_time[0], &size, nullptr, 0) == -1) {\n\t\t\tLogger::error(\"failed to get CPU times\");\n\t\t}\n\t\tcputimes = 0;\n\t\tfor (const auto core : cpu_time) {\n\t\t\tfor (const unsigned int c_state : {CP_USER, CP_NICE, CP_SYS, CP_IDLE}) {\n\t\t\t\tcputimes += core[c_state];\n\t\t\t}\n\t\t}\n\n\t\t//* Use pids from last update if only changing filter, sorting or tree options\n\t\tif (no_update and not current_procs.empty()) {\n\t\t\tif (show_detailed and detailed_pid != detailed.last_pid) _collect_details(detailed_pid, current_procs);\n\t\t} else {\n\t\t\t//* ---------------------------------------------Collection start----------------------------------------------\n\n\t\t\tshould_filter = true;\n\t\t\tfound.clear();\n\t\t\tstruct timeval currentTime;\n\t\t\tgettimeofday(&currentTime, nullptr);\n\t\t\tconst double timeNow = currentTime.tv_sec + (currentTime.tv_usec / 1'000'000);\n\n\t\t\tint count = 0;\n\t\t\tchar buf[_POSIX2_LINE_MAX];\n\t\t\tShared::KvmPtr kd {kvm_openfiles(nullptr, _PATH_DEVNULL, nullptr, O_RDONLY, buf)};\n   \t\t\tconst struct kinfo_proc* kprocs = kvm_getprocs(kd.get(), KERN_PROC_PROC, 0, &count);\n\n   \t\t\tfor (int i = 0; i < count; i++) {\n\t  \t\t\tconst struct kinfo_proc* kproc = &kprocs[i];\n\t\t\t\tconst size_t pid = (size_t)kproc->ki_pid;\n\t\t\t\tif (pid < 1) continue;\n\t\t\t\tfound.push_back(pid);\n\n\t\t\t\t//? Check if pid already exists in current_procs\n\t\t\t\tbool no_cache = false;\n\t\t\t\tauto find_old = rng::find(current_procs, pid, &proc_info::pid);\n\t\t\t\t//? Only add new processes if not paused\n\t\t\t\tif (find_old == current_procs.end()) {\n\t\t\t\t\tif (not pause_proc_list) {\n\t\t\t\t\t\tcurrent_procs.push_back({pid});\n\t\t\t\t\t\tfind_old = current_procs.end() - 1;\n\t\t\t\t\t\tno_cache = true;\n\t\t\t\t\t}\n\t\t\t\t\telse continue;\n\t\t\t\t}\n\t\t\t\telse if (dead_procs.contains(pid)) continue;\n\n\t\t\t\tauto &new_proc = *find_old;\n\n\t\t\t\t//? Get program name, command, username, parent pid, nice and status\n\t\t\t\tif (no_cache) {\n\t\t\t\t\tif (string(kproc->ki_comm) == \"idle\"s) {\n\t\t\t\t\t\tcurrent_procs.pop_back();\n\t\t\t\t\t\tfound.pop_back();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tnew_proc.name = kproc->ki_comm;\n\t\t\t\t\tchar** argv = kvm_getargv(kd.get(), kproc, 0);\n\t\t\t\t\tif (argv) {\n\t\t\t\t\t\tfor (int i = 0; argv[i] and cmp_less(new_proc.cmd.size(), 1000); i++) {\n\t\t\t\t\t\t\tnew_proc.cmd += argv[i] + \" \"s;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (not new_proc.cmd.empty()) new_proc.cmd.pop_back();\n\t\t\t\t\t}\n\t\t\t\t\tif (new_proc.cmd.empty()) new_proc.cmd = new_proc.name;\n\t\t\t\t\tif (new_proc.cmd.size() > 1000) {\n\t\t\t\t\t\tnew_proc.cmd.resize(1000);\n\t\t\t\t\t\tnew_proc.cmd.shrink_to_fit();\n\t\t\t\t\t}\n\t\t\t\t\tnew_proc.ppid = kproc->ki_ppid;\n\t\t\t\t\tnew_proc.cpu_s = round(kproc->ki_start.tv_sec);\n\t\t\t\t\tstruct passwd *pwd = getpwuid(kproc->ki_uid);\n\t\t\t\t\tif (pwd)\n\t\t\t\t\t\tnew_proc.user = pwd->pw_name;\n\t\t\t\t}\n\t\t\t\tnew_proc.p_nice = kproc->ki_nice;\n\t\t\t\tnew_proc.state = kproc->ki_stat;\n\n\t\t\t\tint cpu_t = 0;\n\t\t\t\tcpu_t \t= kproc->ki_rusage.ru_utime.tv_sec * 1'000'000 + kproc->ki_rusage.ru_utime.tv_usec\n\t\t\t\t\t\t+ kproc->ki_rusage.ru_stime.tv_sec * 1'000'000 + kproc->ki_rusage.ru_stime.tv_usec;\n\n\t\t\t\tnew_proc.mem = kproc->ki_rssize * Shared::pageSize;\n\t\t\t\tnew_proc.threads = kproc->ki_numthreads;\n\n\t\t\t\t//? Process cpu usage since last update\n\t\t\t\tnew_proc.cpu_p = clamp((100.0 * kproc->ki_pctcpu / Shared::kfscale) * cmult, 0.0, 100.0 * Shared::coreCount);\n\n\t\t\t\t//? Process cumulative cpu usage since process start\n\t\t\t\tnew_proc.cpu_c = (double)(cpu_t * Shared::clkTck / 1'000'000) / max(1.0, timeNow - new_proc.cpu_s);\n\n\t\t\t\t//? Update cached value with latest cpu times\n\t\t\t\tnew_proc.cpu_t = cpu_t;\n\n\t\t\t\tif (show_detailed and not got_detailed and new_proc.pid == detailed_pid) {\n\t\t\t\t\tgot_detailed = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Clear dead processes from current_procs if not paused\n\t\t\tif (not pause_proc_list) {\n\t\t\t\tauto eraser = rng::remove_if(current_procs, [&](const auto& element) { return not v_contains(found, element.pid); });\n\t\t\t\tcurrent_procs.erase(eraser.begin(), eraser.end());\n\t\t\t\tif (!dead_procs.empty()) dead_procs.clear();\n\t\t\t}\n\t\t\t//? Set correct state of dead processes if paused\n\t\t\telse {\n\t\t\t\tconst bool keep_dead_proc_usage = Config::getB(\"keep_dead_proc_usage\");\n\t\t\t\tfor (auto& r : current_procs) {\n\t\t\t\t\tif (rng::find(found, r.pid) == found.end()) {\n\t\t\t\t\t\tif (r.state != 'X') {\n\t\t\t\t\t\t\tstruct timeval currentTime;\n\t\t\t\t\t\t\tgettimeofday(&currentTime, nullptr);\n\t\t\t\t\t\t\tr.death_time = currentTime.tv_sec - r.cpu_s;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tr.state = 'X';\n\t\t\t\t\t\tdead_procs.emplace(r.pid);\n\t\t\t\t\t\t//? Reset cpu usage for dead processes if paused and option is set\n\t\t\t\t\t\tif (!keep_dead_proc_usage) {\n\t\t\t\t\t\t\tr.cpu_p = 0.0;\n\t\t\t\t\t\t\tr.mem = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Update the details info box for process if active\n\t\t\tif (show_detailed and got_detailed) {\n\t\t\t\t_collect_details(detailed_pid, current_procs);\n\t\t\t} else if (show_detailed and not got_detailed and detailed.status != \"Dead\") {\n\t\t\t\tdetailed.status = \"Dead\";\n\t\t\t\tredraw = true;\n\t\t\t}\n\n\t\t\told_cputimes = cputimes;\n\n\t\t}\n\n\t\t//* ---------------------------------------------Collection done-----------------------------------------------\n\n\t\t//* Match filter if defined\n\t\tif (should_filter) {\n\t\t\tfilter_found = 0;\n\t\t\tfor (auto& p : current_procs) {\n\t\t\t\tif (not tree and not filter.empty()) {\n\t\t\t\t\tif (!matches_filter(p, filter)) {\n\t\t\t\t\t\tp.filtered = true;\n\t\t\t\t\t\tfilter_found++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tp.filtered = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tp.filtered = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//* Sort processes\n\t\tif ((sorted_change or tree_mode_change) or (not no_update and not pause_proc_list)) {\n\t\t\tproc_sorter(current_procs, sorting, reverse, tree);\n\t\t}\n\n\t\t//* Generate tree view if enabled\n\t\tif (tree and (not no_update or should_filter or sorted_change)) {\n\t\t\tbool locate_selection = false;\n\n\t\t\tif (toggle_children != -1) {\n\t\t\t\tauto collapser = rng::find(current_procs, toggle_children, &proc_info::pid);\n\t\t\t\tif (collapser != current_procs.end()){\n\t\t\t\t\tfor (auto& p : current_procs) {\n\t\t\t\t\t\tif (p.ppid == collapser->pid) {\n\t\t\t\t\t\t\tauto child = rng::find(current_procs, p.pid, &proc_info::pid);\n\t\t\t\t\t\t\tif (child != current_procs.end()){\n\t\t\t\t\t\t\t\tchild->collapsed = not child->collapsed;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (Config::ints.at(\"proc_selected\") > 0) locate_selection = true;\n\t\t\t\t}\n\t\t\t\ttoggle_children = -1;\n\t\t\t}\n\t\t\t\n\t\t\tif (auto find_pid = (collapse != -1 ? collapse : expand); find_pid != -1) {\n\t\t\t\tauto collapser = rng::find(current_procs, find_pid, &proc_info::pid);\n\t\t\t\tif (collapser != current_procs.end()) {\n\t\t\t\t\tif (collapse == expand) {\n\t\t\t\t\t\tcollapser->collapsed = not collapser->collapsed;\n\t\t\t\t\t}\n\t\t\t\t\telse if (collapse > -1) {\n\t\t\t\t\t\tcollapser->collapsed = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (expand > -1) {\n\t\t\t\t\t\tcollapser->collapsed = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (Config::ints.at(\"proc_selected\") > 0) locate_selection = true;\n\t\t\t\t}\n\t\t\t\tcollapse = expand = -1;\n\t\t\t}\n\t\t\tif (should_filter or not filter.empty()) filter_found = 0;\n\n\t\t\tvector<tree_proc> tree_procs;\n\t\t\ttree_procs.reserve(current_procs.size());\n\n\t\t\tif (!pause_proc_list) {\n\t\t\t\tfor (auto& p : current_procs) {\n\t\t\t\t\tif (not v_contains(found, p.ppid)) p.ppid = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Stable sort to retain selected sorting among processes with the same parent\n\t\t\trng::stable_sort(current_procs, rng::less{}, & proc_info::ppid);\n\n\t\t\t//? Start recursive iteration over processes with the lowest shared parent pids\n\t\t\tfor (auto& p : rng::equal_range(current_procs, current_procs.at(0).ppid, rng::less{}, &proc_info::ppid)) {\n\t\t\t\t_tree_gen(p, current_procs, tree_procs, 0, false, filter, false, no_update, should_filter);\n\t\t\t}\n\n\t\t\t//? Recursive sort over tree structure to account for collapsed processes in the tree\n\t\t\tint index = 0;\n\t\t\ttree_sort(tree_procs, sorting, reverse, (pause_proc_list and not (sorted_change or tree_mode_change)), index, current_procs.size());\n\n\t\t\t//? Recursive construction of ASCII tree prefixes.\n\t\t\tfor (auto t = tree_procs.begin(); t != tree_procs.end(); ++t) {\n\t\t\t\t_collect_prefixes(*t, t == tree_procs.end() - 1);\n\t\t\t}\n\n\t\t\t//? Final sort based on tree index\n\t\t\trng::stable_sort(current_procs, rng::less {}, &proc_info::tree_index);\n\n\t\t\t//? Move current selection/view to the selected process when collapsing/expanding in the tree\n\t\t\tif (locate_selection) {\n\t\t\t\tint loc = rng::find(current_procs, Proc::selected_pid, &proc_info::pid)->tree_index;\n\t\t\t\tif (Config::ints.at(\"proc_start\") >= loc or Config::ints.at(\"proc_start\") <= loc - Proc::select_max)\n\t\t\t\t\tConfig::ints.at(\"proc_start\") = max(0, loc - 1);\n\t\t\t\tConfig::ints.at(\"proc_selected\") = loc - Config::ints.at(\"proc_start\") + 1;\n\t\t\t}\n\t\t}\n\n\t\tnumpids = (int)current_procs.size() - filter_found;\n\t\treturn current_procs;\n\t}\n}  // namespace Proc\n\nnamespace Tools {\n\tdouble system_uptime() {\n\t\tstruct timeval ts, currTime;\n\t\tstd::size_t len = sizeof(ts);\n\t\tint mib[2] = {CTL_KERN, KERN_BOOTTIME};\n\t\tif (sysctl(mib, 2, &ts, &len, nullptr, 0) != -1) {\n\t\t\tgettimeofday(&currTime, nullptr);\n\t\t\treturn currTime.tv_sec - ts.tv_sec;\n\t\t}\n\t\treturn 0.0;\n\t}\n}  // namespace Tools\n"
  },
  {
    "path": "src/linux/btop_collect.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include <algorithm>\n#include <charconv>\n#include <cmath>\n#include <cstdlib>\n#include <filesystem>\n#include <fstream>\n#include <future>\n#include <iterator>\n#include <numeric>\n#include <optional>\n#include <ranges>\n#include <string_view>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n\n#include <arpa/inet.h> // for inet_ntop()\n#include <dlfcn.h>\n#include <ifaddrs.h>\n#include <net/if.h>\n#include <netdb.h>\n#include <sys/statvfs.h>\n#include <unistd.h>\n\n#include <fmt/format.h>\n#include <fmt/std.h>\n\n#if defined(RSMI_STATIC)\n\t#include <rocm_smi/rocm_smi.h>\n#endif\n\n#if !(defined(STATIC_BUILD) && defined(__GLIBC__))\n\t#include <pwd.h>\n#endif\n\n#include \"../btop_config.hpp\"\n#include \"../btop_log.hpp\"\n#include \"../btop_shared.hpp\"\n#include \"../btop_tools.hpp\"\n\n#if defined(GPU_SUPPORT)\n\t// Redefining C++ keywords fortunately has a warning in clang, however it's unavoidable here\n\t// since the C library uses \"class\" as a struct member and keywords are not allowed to be used\n\t// as identifiers in C++.\n\t#if defined(__clang__)\n\t\t#pragma clang diagnostic push\n\t\t#pragma clang diagnostic ignored \"-Wkeyword-macro\"\n\t#endif // __clang__\n\n\t#define class class_\nextern \"C\" {\n\t#include \"intel_gpu_top/intel_gpu_top.h\"\n}\n\t#undef class\n\n\t#if defined(__clang__)\n\t\t#pragma clang diagnostic pop\n\t#endif // __clang__\n#endif\n\nusing std::abs;\nusing std::clamp;\nusing std::cmp_greater;\nusing std::cmp_less;\nusing std::ifstream;\nusing std::max;\nusing std::min;\nusing std::numeric_limits;\nusing std::round;\nusing std::streamsize;\nusing std::vector;\nusing std::future;\nusing std::async;\nusing std::pair;\n\n\nnamespace fs = std::filesystem;\nnamespace rng = std::ranges;\n\nusing namespace Tools;\nusing namespace std::literals; // for operator\"\"s\nusing namespace std::chrono_literals;\n//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------\n\nnamespace\n{\n\nlong long get_monotonicTimeUSec()\n{\n\tstruct timespec time;\n\tclock_gettime(CLOCK_MONOTONIC, &time);\n\treturn time.tv_sec * 1000000 + time.tv_nsec / 1000;\n}\n\n}\n\nnamespace Cpu {\n\tvector<long long> core_old_totals;\n\tvector<long long> core_old_idles;\n\tvector<fs::path> core_freq;\n\tvector<string> available_fields = {\"Auto\", \"total\"};\n\tvector<string> available_sensors = {\"Auto\"};\n\tcpu_info current_cpu;\n\tbool got_sensors{};\n\tbool cpu_temp_only{};\n\tbool supports_watts = true;\n\n\t//* Populate found_sensors map\n\tbool get_sensors();\n\n\t//* Get current cpu clock speed\n\tstring get_cpuHz();\n\n\t//* Search /proc/cpuinfo for a cpu name\n\tstring get_cpuName();\n\n\tstruct Sensor {\n\t\tfs::path path;\n\t\tint64_t temp{};\n\t\tint64_t crit{};\n\t};\n\n\tstd::unordered_map<string, Sensor> found_sensors;\n\tstring cpu_sensor;\n\tvector<string> core_sensors;\n\tstd::unordered_map<int, int> core_mapping;\n}\n\n#if defined(GPU_SUPPORT)\n\nnamespace Gpu {\n\tvector<gpu_info> gpus;\n\t//? NVIDIA data collection\n\tnamespace Nvml {\n\t\t//? NVML defines, structs & typedefs\n\t\t#define NVML_DEVICE_NAME_BUFFER_SIZE        64\n\t\t#define NVML_SUCCESS                         0\n\t\t#define NVML_TEMPERATURE_THRESHOLD_SHUTDOWN  0\n\t\t#define NVML_CLOCK_GRAPHICS                  0\n\t\t#define NVML_CLOCK_MEM                       2\n\t\t#define NVML_TEMPERATURE_GPU                 0\n\t\t#define NVML_PCIE_UTIL_TX_BYTES              0\n\t\t#define NVML_PCIE_UTIL_RX_BYTES              1\n\n\t\ttypedef void* nvmlDevice_t; // we won't be accessing any of the underlying struct's properties, so this is fine\n\t\ttypedef int nvmlReturn_t, // enums are basically ints\n\t\t\t\t\tnvmlTemperatureThresholds_t,\n\t\t\t\t\tnvmlClockType_t,\n\t\t\t\t\tnvmlPstates_t,\n\t\t\t\t\tnvmlTemperatureSensors_t,\n\t\t\t\t\tnvmlPcieUtilCounter_t;\n\n\t\tstruct nvmlUtilization_t {unsigned int gpu, memory;};\n\t\tstruct nvmlMemory_t {unsigned long long total, free, used;};\n\n\t\t//? Function pointers\n\t\tconst char* (*nvmlErrorString)(nvmlReturn_t);\n\t\tnvmlReturn_t (*nvmlInit)();\n\t\tnvmlReturn_t (*nvmlShutdown)();\n\t\tnvmlReturn_t (*nvmlDeviceGetCount)(unsigned int*);\n\t\tnvmlReturn_t (*nvmlDeviceGetHandleByIndex)(unsigned int, nvmlDevice_t*);\n\t\tnvmlReturn_t (*nvmlDeviceGetName)(nvmlDevice_t, char*, unsigned int);\n\t\tnvmlReturn_t (*nvmlDeviceGetPowerManagementLimit)(nvmlDevice_t, unsigned int*);\n\t\tnvmlReturn_t (*nvmlDeviceGetTemperatureThreshold)(nvmlDevice_t, nvmlTemperatureThresholds_t, unsigned int*);\n\t\tnvmlReturn_t (*nvmlDeviceGetUtilizationRates)(nvmlDevice_t, nvmlUtilization_t*);\n\t\tnvmlReturn_t (*nvmlDeviceGetClockInfo)(nvmlDevice_t, nvmlClockType_t, unsigned int*);\n\t\tnvmlReturn_t (*nvmlDeviceGetPowerUsage)(nvmlDevice_t, unsigned int*);\n\t\tnvmlReturn_t (*nvmlDeviceGetPowerState)(nvmlDevice_t, nvmlPstates_t*);\n\t\tnvmlReturn_t (*nvmlDeviceGetTemperature)(nvmlDevice_t, nvmlTemperatureSensors_t, unsigned int*);\n\t\tnvmlReturn_t (*nvmlDeviceGetMemoryInfo)(nvmlDevice_t, nvmlMemory_t*);\n\t\tnvmlReturn_t (*nvmlDeviceGetPcieThroughput)(nvmlDevice_t, nvmlPcieUtilCounter_t, unsigned int*);\n\t\tnvmlReturn_t (*nvmlDeviceGetEncoderUtilization)(nvmlDevice_t, unsigned int*, unsigned int*);\n\t\tnvmlReturn_t (*nvmlDeviceGetDecoderUtilization)(nvmlDevice_t, unsigned int*, unsigned int*);\n\n\t\t//? Data\n\t\tvoid* nvml_dl_handle;\n\t\tbool initialized = false;\n\t\tbool init();\n\t\tbool shutdown();\n\t\ttemplate <bool is_init> bool collect(gpu_info* gpus_slice);\n\t\tvector<nvmlDevice_t> devices;\n\t\tunsigned int device_count = 0;\n\t}\n\n\t//? AMD data collection\n\tnamespace Rsmi {\n\n\t//? RSMI defines, structs & typedefs\n\t#define RSMI_DEVICE_NAME_BUFFER_SIZE 128\n\n\t#if !defined(RSMI_STATIC)\n\t\t#define RSMI_MAX_NUM_FREQUENCIES_V5  32\n\t\t#define RSMI_MAX_NUM_FREQUENCIES_V6  33\n\t\t#define RSMI_STATUS_SUCCESS           0\n\t\t#define RSMI_MEM_TYPE_VRAM            0\n\t\t#define RSMI_TEMP_CURRENT             0\n\t\t#define RSMI_TEMP_TYPE_EDGE           0\n\t\t#define RSMI_CLK_TYPE_MEM             4\n\t\t#define RSMI_CLK_TYPE_SYS             0\n\t\t#define RSMI_TEMP_MAX                 1\n\n\t\ttypedef int rsmi_status_t,\n\t\t\t\t\trsmi_temperature_metric_t,\n\t\t\t\t\trsmi_clk_type_t,\n\t\t\t\t\trsmi_memory_type_t;\n\n\t\tstruct rsmi_version_t {uint32_t major,  minor,  patch; const char* build;};\n\t\tstruct rsmi_frequencies_t_v5 {uint32_t num_supported, current; uint64_t frequency[RSMI_MAX_NUM_FREQUENCIES_V5];};\n\t\tstruct rsmi_frequencies_t_v6 {bool has_deep_sleep; uint32_t num_supported, current; uint64_t frequency[RSMI_MAX_NUM_FREQUENCIES_V6];};\n\n\t\t//? Function pointers\n\t\trsmi_status_t (*rsmi_init)(uint64_t);\n\t\trsmi_status_t (*rsmi_shut_down)();\n\t\trsmi_status_t (*rsmi_version_get)(rsmi_version_t*);\n\t\trsmi_status_t (*rsmi_num_monitor_devices)(uint32_t*);\n\t\trsmi_status_t (*rsmi_dev_name_get)(uint32_t, char*, size_t);\n\t\trsmi_status_t (*rsmi_dev_power_cap_get)(uint32_t, uint32_t, uint64_t*);\n\t\trsmi_status_t (*rsmi_dev_temp_metric_get)(uint32_t, uint32_t, rsmi_temperature_metric_t, int64_t*);\n\t\trsmi_status_t (*rsmi_dev_busy_percent_get)(uint32_t, uint32_t*);\n\t\trsmi_status_t (*rsmi_dev_memory_busy_percent_get)(uint32_t, uint32_t*);\n\t\trsmi_status_t (*rsmi_dev_gpu_clk_freq_get_v5)(uint32_t, rsmi_clk_type_t, rsmi_frequencies_t_v5*);\n\t\trsmi_status_t (*rsmi_dev_gpu_clk_freq_get_v6)(uint32_t, rsmi_clk_type_t, rsmi_frequencies_t_v6*);\n\t\trsmi_status_t (*rsmi_dev_power_ave_get)(uint32_t, uint32_t, uint64_t*);\n\t\trsmi_status_t (*rsmi_dev_memory_total_get)(uint32_t, rsmi_memory_type_t, uint64_t*);\n\t\trsmi_status_t (*rsmi_dev_memory_usage_get)(uint32_t, rsmi_memory_type_t, uint64_t*);\n\t\trsmi_status_t (*rsmi_dev_pci_throughput_get)(uint32_t, uint64_t*, uint64_t*, uint64_t*);\n\n\t\tuint32_t version_major = 0;\n\n\t\t//? Data\n\t\tvoid* rsmi_dl_handle;\n\t#endif\n\t\tbool initialized = false;\n\t\tbool init();\n\t\tbool shutdown();\n\t\ttemplate <bool is_init> bool collect(gpu_info* gpus_slice);\n\t\tuint32_t device_count = 0;\n\t}\n\n\n\t//? Intel data collection\n\tnamespace Intel {\n\t\tconst char* device = \"i915\";\n\t\tstruct engines *engines = nullptr;\n\n\t\tbool initialized = false;\n\t\tbool init();\n\t\tbool shutdown();\n\t\ttemplate <bool is_init> bool collect(gpu_info* gpus_slice);\n\t\tuint32_t device_count = 0;\n\t}\n}\n\n#endif // GPU_SUPPORT\n\nnamespace Mem {\n\tdouble old_uptime;\n}\n\nnamespace Shared {\n\n\tfs::path procPath, passwd_path;\n\tlong pageSize, clkTck, coreCount;\n\n\tvoid init() {\n\n\t\t//? Shared global variables init\n\t\tprocPath = (fs::is_directory(fs::path(\"/proc\")) and access(\"/proc\", R_OK) != -1) ? \"/proc\" : \"\";\n\t\tif (procPath.empty())\n\t\t\tthrow std::runtime_error(\"Proc filesystem not found or no permission to read from it!\");\n\n\t\tpasswd_path = (fs::is_regular_file(fs::path(\"/etc/passwd\")) and access(\"/etc/passwd\", R_OK) != -1) ? \"/etc/passwd\" : \"\";\n\t\tif (passwd_path.empty())\n\t\t\tLogger::warning(\"Could not read /etc/passwd, will show UID instead of username.\");\n\n\t\tcoreCount = sysconf(_SC_NPROCESSORS_ONLN);\n\t\tif (coreCount < 1) {\n\t\t\tcoreCount = sysconf(_SC_NPROCESSORS_CONF);\n\t\t\tif (coreCount < 1) {\n\t\t\t\tcoreCount = 1;\n\t\t\t\tLogger::warning(\"Could not determine number of cores, defaulting to 1.\");\n\t\t\t}\n\t\t}\n\n\t\tpageSize = sysconf(_SC_PAGE_SIZE);\n\t\tif (pageSize <= 0) {\n\t\t\tpageSize = 4096;\n\t\t\tLogger::warning(\"Could not get system page size. Defaulting to 4096, processes memory usage might be incorrect.\");\n\t\t}\n\n\t\tclkTck = sysconf(_SC_CLK_TCK);\n\t\tif (clkTck <= 0) {\n\t\t\tclkTck = 100;\n\t\t\tLogger::warning(\"Could not get system clock ticks per second. Defaulting to 100, processes cpu usage might be incorrect.\");\n\t\t}\n\n\t\t//? Init for namespace Cpu\n\t\tCpu::current_cpu.core_percent.insert(Cpu::current_cpu.core_percent.begin(), Shared::coreCount, {});\n\t\tCpu::current_cpu.temp.insert(Cpu::current_cpu.temp.begin(), Shared::coreCount + 1, {});\n\t\tCpu::core_old_totals.insert(Cpu::core_old_totals.begin(), Shared::coreCount, 0);\n\t\tCpu::core_old_idles.insert(Cpu::core_old_idles.begin(), Shared::coreCount, 0);\n\n\t\tfor (int i = 0; i < Shared::coreCount; ++i) {\n\t\t\tCpu::core_freq.push_back(\"/sys/devices/system/cpu/cpufreq/policy\" + to_string(i) + \"/scaling_cur_freq\");\n\t\t\tif (not fs::exists(Cpu::core_freq.back()) or access(Cpu::core_freq.back().c_str(), R_OK) == -1) {\n\t\t\t\tCpu::core_freq.pop_back();\n\t\t\t}\n\t\t}\n\n\t\tCpu::collect();\n\t\tif (Runner::coreNum_reset) Runner::coreNum_reset = false;\n\t\tfor (auto& [field, vec] : Cpu::current_cpu.cpu_percent) {\n\t\t\tif (not vec.empty() and not v_contains(Cpu::available_fields, field)) Cpu::available_fields.push_back(field);\n\t\t}\n\t\tCpu::cpuName = Cpu::get_cpuName();\n\t\tCpu::got_sensors = Cpu::get_sensors();\n\t\tfor (const auto& [sensor, ignored] : Cpu::found_sensors) {\n\t\t\tCpu::available_sensors.push_back(sensor);\n\t\t}\n\t\tCpu::core_mapping = Cpu::get_core_mapping();\n\n\t\tCpu::container_engine = detect_container();\n\n\t\t//? Init for namespace Gpu\n\t#ifdef GPU_SUPPORT\n\t\tauto shown_gpus = Config::getS(\"shown_gpus\");\n\t\tif (shown_gpus.contains(\"nvidia\")) {\n\t\t    Gpu::Nvml::init();\n\t\t}\n\n\t\tif (shown_gpus.contains(\"amd\")) {\n\t\t\tGpu::Rsmi::init();\n\t\t}\n\n\t\tif (shown_gpus.contains(\"intel\")) {\n\t\t\tGpu::Intel::init();\n\t\t}\n\n\t\tif (not Gpu::gpu_names.empty()) {\n\t\t\tfor (auto const& [key, _] : Gpu::gpus[0].gpu_percent)\n\t\t\t\tCpu::available_fields.push_back(key);\n\t\t\tfor (auto const& [key, _] : Gpu::shared_gpu_percent)\n\t\t\t\tCpu::available_fields.push_back(key);\n\n\t\t\tusing namespace Gpu;\n\t\t\tcount = gpus.size();\n\t\t\tgpu_b_height_offsets.resize(gpus.size());\n\t\t\tfor (size_t i = 0; i < gpu_b_height_offsets.size(); ++i)\n\t\t\t\tgpu_b_height_offsets[i] = gpus[i].supported_functions.gpu_utilization\n\t\t\t\t\t   + gpus[i].supported_functions.pwr_usage\n\t\t\t\t\t   + (gpus[i].supported_functions.encoder_utilization or gpus[i].supported_functions.decoder_utilization)\n\t\t\t\t\t   + (gpus[i].supported_functions.mem_total or gpus[i].supported_functions.mem_used)\n\t\t\t\t\t\t* (1 + 2*(gpus[i].supported_functions.mem_total and gpus[i].supported_functions.mem_used) + 2*gpus[i].supported_functions.mem_utilization);\n\t\t}\n\t#endif\n\n\t\t//? Init for namespace Mem\n\t\tMem::old_uptime = system_uptime();\n\t\tMem::collect();\n\n\t\tLogger::debug(\"Shared::init() : Initialized.\");\n\t}\n}\n\nnamespace Cpu {\n\tstring cpuName;\n\tstring cpuHz;\n\tbool has_battery = true;\n\ttuple<int, float, long, string> current_bat;\n\n\tconst array time_names {\n\t\t\"user\"s, \"nice\"s, \"system\"s, \"idle\"s, \"iowait\"s,\n\t\t\"irq\"s, \"softirq\"s, \"steal\"s, \"guest\"s, \"guest_nice\"s\n\t};\n\n\tstd::unordered_map<string, long long> cpu_old = {\n\t\t\t{\"totals\", 0},\n\t\t\t{\"idles\", 0},\n\t\t\t{\"user\", 0},\n\t\t\t{\"nice\", 0},\n\t\t\t{\"system\", 0},\n\t\t\t{\"idle\", 0},\n\t\t\t{\"iowait\", 0},\n\t\t\t{\"irq\", 0},\n\t\t\t{\"softirq\", 0},\n\t\t\t{\"steal\", 0},\n\t\t\t{\"guest\", 0},\n\t\t\t{\"guest_nice\", 0}\n\t};\n\n\tstring get_cpuName() {\n\t\tstring name;\n\t\tifstream cpuinfo(Shared::procPath / \"cpuinfo\");\n\t\tif (cpuinfo.good()) {\n\t\t\tfor (string instr; getline(cpuinfo, instr, ':') and not instr.starts_with(\"model name\");)\n\t\t\t\tcpuinfo.ignore(SSmax, '\\n');\n\t\t\tif (cpuinfo.bad()) return name;\n\t\t\telse if (not cpuinfo.eof()) {\n\t\t\t\tcpuinfo.ignore(1);\n\t\t\t\tgetline(cpuinfo, name);\n\t\t\t}\n\t\t\telse if (fs::exists(\"/sys/devices\")) {\n\t\t\t\tfor (const auto& d : fs::directory_iterator(\"/sys/devices\")) {\n\t\t\t\t\tif (string(d.path().filename()).starts_with(\"arm\")) {\n\t\t\t\t\t\tname = d.path().filename();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (not name.empty()) {\n\t\t\t\t\tauto name_vec = ssplit(name, '_');\n\t\t\t\t\tif (name_vec.size() < 2) return capitalize(name);\n\t\t\t\t\telse return capitalize(name_vec.at(1)) + (name_vec.size() > 2 ? ' ' + capitalize(name_vec.at(2)) : \"\");\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tname = trim_name(name);\n\t\t}\n\n\t\treturn name;\n\t}\n\n\tbool get_sensors() {\n\t\tbool got_cpu = false, got_coretemp = false;\n\t\tvector<fs::path> search_paths;\n\t\ttry {\n\t\t\t//? Setup up paths to search for sensors\n\t\t\tif (fs::exists(fs::path(\"/sys/class/hwmon\")) and access(\"/sys/class/hwmon\", R_OK) != -1) {\n\t\t\t\tfor (const auto& dir : fs::directory_iterator(fs::path(\"/sys/class/hwmon\"))) {\n\t\t\t\t\tfs::path add_path = fs::canonical(dir.path());\n\t\t\t\t\tif (v_contains(search_paths, add_path) or v_contains(search_paths, add_path / \"device\")) continue;\n\n\t\t\t\t\tif (std::string_view { add_path.c_str() }.contains(\"coretemp\"))\n\t\t\t\t\t\tgot_coretemp = true;\n\n\t\t\t\t\tfor (const auto & file : fs::directory_iterator(add_path)) {\n\t\t\t\t\t\tif (file.path().filename() == \"device\") {\n\t\t\t\t\t\t\tfor (const auto & dev_file : fs::directory_iterator(file.path())) {\n\t\t\t\t\t\t\t\tstring dev_filename = dev_file.path().filename();\n\t\t\t\t\t\t\t\tif (dev_filename.starts_with(\"temp\") and dev_filename.ends_with(\"_input\")) {\n\t\t\t\t\t\t\t\t\tsearch_paths.push_back(file.path());\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tstring filename = file.path().filename();\n\t\t\t\t\t\tif (filename.starts_with(\"temp\") and filename.ends_with(\"_input\")) {\n\t\t\t\t\t\t\tsearch_paths.push_back(add_path);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (not got_coretemp and fs::exists(fs::path(\"/sys/devices/platform/coretemp.0/hwmon\"))) {\n\t\t\t\tfor (auto& d : fs::directory_iterator(fs::path(\"/sys/devices/platform/coretemp.0/hwmon\"))) {\n\t\t\t\t\tfs::path add_path = fs::canonical(d.path());\n\n\t\t\t\t\tfor (const auto & file : fs::directory_iterator(add_path)) {\n\t\t\t\t\t\tstring filename = file.path().filename();\n\t\t\t\t\t\tif (filename.starts_with(\"temp\") and filename.ends_with(\"_input\") and not v_contains(search_paths, add_path)) {\n\t\t\t\t\t\t\t\tsearch_paths.push_back(add_path);\n\t\t\t\t\t\t\t\tgot_coretemp = true;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//? Scan any found directories for temperature sensors\n\t\t\tif (not search_paths.empty()) {\n\t\t\t\tfor (const auto& path : search_paths) {\n\t\t\t\t\tconst string pname = readfile(path / \"name\", path.filename());\n\t\t\t\t\tfor (const auto & file : fs::directory_iterator(path)) {\n\t\t\t\t\t\tconst string file_suffix = \"input\";\n\t\t\t\t\t\tconst int file_id = atoi(file.path().filename().c_str() + 4); // skip \"temp\" prefix\n\t\t\t\t\t\tstring file_path = file.path();\n\n\t\t\t\t\t\tif (!file_path.contains(file_suffix) or file_path.contains(\"nvme\")) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst string basepath = file_path.erase(file_path.find(file_suffix), file_suffix.length());\n\t\t\t\t\t\tconst string label = readfile(fs::path(basepath + \"label\"), \"temp\" + to_string(file_id));\n\t\t\t\t\t\tconst string sensor_name = pname + \"/\" + label;\n\t\t\t\t\t\tconst int64_t temp = stol(readfile(fs::path(basepath + \"input\"), \"0\")) / 1000;\n\t\t\t\t\t\tconst int64_t crit = stol(readfile(fs::path(basepath + \"crit\"), \"95000\")) / 1000;\n\n\t\t\t\t\t\tfound_sensors[sensor_name] = Sensor { fs::path(basepath + \"input\"), temp, crit };\n\n\t\t\t\t\t\tif (not got_cpu and (label.starts_with(\"Package id\") or label.starts_with(\"Tdie\") or label.starts_with(\"SoC Temperature\"))) {\n\t\t\t\t\t\t\tgot_cpu = true;\n\t\t\t\t\t\t\tcpu_sensor = sensor_name;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (label.starts_with(\"Core\") or label.starts_with(\"Tccd\")) {\n\t\t\t\t\t\t\tgot_coretemp = true;\n\t\t\t\t\t\t\tif (not v_contains(core_sensors, sensor_name)) core_sensors.push_back(sensor_name);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//? If no good candidate for cpu temp has been found scan /sys/class/thermal\n\t\t\tif (not got_cpu and fs::exists(fs::path(\"/sys/class/thermal\"))) {\n\t\t\t\tconst string rootpath = fs::path(\"/sys/class/thermal/thermal_zone\");\n\t\t\t\tfor (int i = 0; fs::exists(fs::path(rootpath + to_string(i))); i++) {\n\t\t\t\t\tconst fs::path basepath = rootpath + to_string(i);\n\t\t\t\t\tif (not fs::exists(basepath / \"temp\")) continue;\n\t\t\t\t\tconst string label = readfile(basepath / \"type\", \"temp\" + to_string(i));\n\t\t\t\t\tconst string sensor_name = \"thermal\" + to_string(i) + \"/\" + label;\n\t\t\t\t\tconst int64_t temp = stol(readfile(basepath / \"temp\", \"0\")) / 1000;\n\n\t\t\t\t\tint64_t high = 0;\n\t\t\t\t\tint64_t crit = 0;\n\t\t\t\t\tfor (int ii = 0; fs::exists(basepath / fmt::format(\"trip_point_{}_temp\", ii)); ii++) {\n\t\t\t\t\t\tconst string trip_type = readfile(basepath / fmt::format(\"trip_point_{}_type\", ii));\n\t\t\t\t\t\tif (not is_in(trip_type, \"high\", \"critical\")) continue;\n\t\t\t\t\t\tauto& val = (trip_type == \"high\" ? high : crit);\n\t\t\t\t\t\tval = stol(readfile(basepath / fmt::format(\"trip_point_{}_temp\", ii), \"0\")) / 1000;\n\t\t\t\t\t}\n\t\t\t\t\tif (high < 1) high = 80;\n\t\t\t\t\tif (crit < 1) crit = 95;\n\n\t\t\t\t\tfound_sensors[sensor_name] = Sensor { basepath / \"temp\", temp, crit };\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tcatch (...) {}\n\n\t\tif (not got_coretemp or core_sensors.empty()) {\n\t\t\tcpu_temp_only = true;\n\t\t}\n\t\telse {\n\t\t\trng::sort(core_sensors, rng::less{});\n\t\t\trng::stable_sort(core_sensors, [](const auto& a, const auto& b){\n\t\t\t\treturn a.size() < b.size();\n\t\t\t});\n\t\t}\n\n\t\tif (cpu_sensor.empty() and not found_sensors.empty()) {\n\t\t\tfor (const auto& [name, sensor] : found_sensors) {\n\t\t\t\tif (str_to_lower(name).contains(\"cpu\") or str_to_lower(name).contains(\"k10temp\")) {\n\t\t\t\t\tcpu_sensor = name;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (cpu_sensor.empty()) {\n\t\t\t\tcpu_sensor = found_sensors.begin()->first;\n\t\t\t\tLogger::warning(\"No good candidate for cpu sensor found, using random from all found sensors.\");\n\t\t\t}\n\t\t}\n\n\t\treturn not found_sensors.empty();\n\t}\n\n\tstatic void update_sensors() {\n\t\tif (cpu_sensor.empty()) return;\n\n\t\tconst auto& cpu_sensor = (not Config::getS(\"cpu_sensor\").empty() and found_sensors.contains(Config::getS(\"cpu_sensor\")) ? Config::getS(\"cpu_sensor\") : Cpu::cpu_sensor);\n\n\t\tfound_sensors.at(cpu_sensor).temp = stol(readfile(found_sensors.at(cpu_sensor).path, \"0\")) / 1000;\n\t\tcurrent_cpu.temp.at(0).push_back(found_sensors.at(cpu_sensor).temp);\n\t\tcurrent_cpu.temp_max = found_sensors.at(cpu_sensor).crit;\n\t\tif (current_cpu.temp.at(0).size() > 20) current_cpu.temp.at(0).pop_front();\n\n\t\tif (Config::getB(\"show_coretemp\") and not cpu_temp_only) {\n\t\t\tfor (vector<string_view> done; const auto& sensor : core_sensors) {\n\t\t\t\tif (v_contains(done, sensor)) continue;\n\t\t\t\tfound_sensors.at(sensor).temp = stol(readfile(found_sensors.at(sensor).path, \"0\")) / 1000;\n\t\t\t\tdone.push_back(sensor);\n\t\t\t}\n\t\t\tfor (const auto& [core, temp] : core_mapping) {\n\t\t\t\tif (cmp_less(core + 1, current_cpu.temp.size()) and cmp_less(temp, core_sensors.size())) {\n\t\t\t\t\tcurrent_cpu.temp.at(core + 1).push_back(found_sensors.at(core_sensors.at(temp)).temp);\n\t\t\t\t\tif (current_cpu.temp.at(core + 1).size() > 20) current_cpu.temp.at(core + 1).pop_front();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstatic string normalize_frequency(double hz) {\n\t\tstring str;\n\t\tif (hz > 999999) {\n\t\t\tstr = fmt::format(\"{:.1f}\", hz / 1'000'000);\n\t\t\tstr.resize(3);\n\t\t\tif (str.back() == '.') str.pop_back();\n\t\t\tstr += \" THz\";\n\t\t}\n\t\telse if (hz > 999) {\n\t\t\tstr = fmt::format(\"{:.1f}\", hz / 1'000);\n\t\t\tstr.resize(3);\n\t\t\tif (str.back() == '.') str.pop_back();\n\t\t\tstr += \" GHz\";\n\t\t}\n\t\telse {\n\t\t\tstr = fmt::format(\"{:.0f} MHz\", hz);\n\t\t}\n\t\treturn str;\n\t}\n\n\tstring get_cpuHz() {\n\t\tstatic int failed{};\n\n\t\tif (failed > 4)\n\t\t\treturn \"\"s;\n\n\t\tstring cpuhz;\n\n\t\tconst auto &freq_mode = Config::getS(\"freq_mode\");\n\n\t\ttry {\n\t\t\tdouble hz = 0.0;\n\t\t\t// Read frequencies from all CPU cores\n\t\t\tvector<double> frequencies;\n\t\t\tfor (auto it = Cpu::core_freq.begin(); it != Cpu::core_freq.end(); ) {\n    \t\t\tif (it->empty()) {\n        \t\t\tit = Cpu::core_freq.erase(it);\n        \t\t\tcontinue;\n    \t\t\t}\n\n    \t\t\tdouble core_hz = stod(readfile(*it, \"0.0\")) / 1000;\n    \t\t\tif (core_hz <= 0.0 and ++failed >= 2) {\n        \t\t\tit = Cpu::core_freq.erase(it);\n    \t\t\t} else {\n        \t\t\tfrequencies.push_back(core_hz);\n        \t\t\tif (freq_mode == \"first\") break;\n        \t\t\t++it;\n    \t\t\t}\n \t\t\t}\n\n\t\t\tif (not frequencies.empty()) {\n\t\t\t\tif (freq_mode == \"first\") {\n\t\t\t\t\thz = frequencies.front();\n\t\t\t\t}\n\t\t\t\tif (freq_mode == \"average\") {\n\t\t\t\t\thz = std::accumulate(frequencies.begin(), frequencies.end(), 0.0) / static_cast<double>(frequencies.size());\n\t\t\t\t}\n\t\t\t\telse if (freq_mode == \"highest\") {\n\t\t\t\t\thz = *std::max_element(frequencies.begin(), frequencies.end());\n\t\t\t\t}\n\t\t\t\telse if (freq_mode == \"lowest\") {\n\t\t\t\t\thz = *std::min_element(frequencies.begin(), frequencies.end());\n\t\t\t\t}\n\t\t\t\telse if (freq_mode == \"range\") {\n\t\t\t\t\tauto [min_hz,max_hz] = std::minmax_element(frequencies.begin(), frequencies.end());\n\n\t\t\t\t\t// Format as range\n\t\t\t\t\tstring min_str, max_str;\n\t\t\t\t\tmin_str = normalize_frequency(*min_hz);\n\t\t\t\t\tmax_str = normalize_frequency(*max_hz);\n\n\t\t\t\t\treturn min_str + \" - \" + max_str;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//? If freq from /sys failed or is missing try to use /proc/cpuinfo\n\t\t\tif (hz <= 0.0) {\n\t\t\t\tifstream cpufreq(Shared::procPath / \"cpuinfo\");\n\t\t\t\tif (cpufreq.good()) {\n\t\t\t\t\twhile (cpufreq.ignore(SSmax, '\\n')) {\n\t\t\t\t\t\t// peek is caps sensitive so it was skipping 'CPU MHz'. This aims to fix it.\n\t\t\t\t\t\tif (cpufreq.peek() == 'c' || cpufreq.peek() == 'C') {\n\t\t\t\t\t\t\tcpufreq.ignore(SSmax, ' ');\n\t\t\t\t\t\t\tif (cpufreq.peek() == 'M') {\n\t\t\t\t\t\t\t\tcpufreq.ignore(SSmax, ':');\n\t\t\t\t\t\t\t\tcpufreq.ignore(1);\n\t\t\t\t\t\t\t\tcpufreq >> hz;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (hz <= 1 or hz >= 999999999)\n\t\t\t\tthrow std::runtime_error(\"Failed to read /sys/devices/system/cpu/cpufreq/policy and /proc/cpuinfo.\");\n\n\t\t\tcpuhz = normalize_frequency(hz);\n\n\t\t}\n\t\tcatch (const std::exception& e) {\n\t\t\tif (++failed < 5)\n\t\t\t\treturn \"\"s;\n\t\t\telse {\n\t\t\t\tLogger::warning(\"get_cpuHZ() : {}\", e.what());\n\t\t\t\treturn \"\"s;\n\t\t\t}\n\t\t}\n\n\t\treturn cpuhz;\n\t}\n\n\tauto get_core_mapping() -> std::unordered_map<int, int> {\n\t\tstd::unordered_map<int, int> core_map;\n\t\tif (cpu_temp_only) return core_map;\n\n\t\t//? Try to get core mapping from /proc/cpuinfo\n\t\tifstream cpuinfo(Shared::procPath / \"cpuinfo\");\n\t\tif (cpuinfo.good()) {\n\t\t\tint cpu{};\n\t\t\tint core{};\n\t\t\tint n{};\n\t\t\tfor (string instr; cpuinfo >> instr;) {\n\t\t\t\tif (instr == \"processor\") {\n\t\t\t\t\tcpuinfo.ignore(SSmax, ':');\n\t\t\t\t\tcpuinfo >> cpu;\n\t\t\t\t}\n\t\t\t\telse if (instr.starts_with(\"core\")) {\n\t\t\t\t\tcpuinfo.ignore(SSmax, ':');\n\t\t\t\t\tcpuinfo >> core;\n\t\t\t\t\tif (std::cmp_greater_equal(core, core_sensors.size())) {\n\t\t\t\t\t\tif (std::cmp_greater_equal(n, core_sensors.size())) n = 0;\n\t\t\t\t\t\tcore_map[cpu] = n++;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tcore_map[cpu] = core;\n\t\t\t\t}\n\t\t\t\tcpuinfo.ignore(SSmax, '\\n');\n\t\t\t}\n\t\t}\n\n\t\t//? If core mapping from cpuinfo was incomplete try to guess remainder, if missing completely, map 0-0 1-1 2-2 etc.\n\t\tif (cmp_less(core_map.size(), Shared::coreCount)) {\n\t\t\tif (Shared::coreCount % 2 == 0 and (long)core_map.size() == Shared::coreCount / 2) {\n\t\t\t\tfor (int i = 0, n = 0; i < Shared::coreCount / 2; i++) {\n\t\t\t\t\tif (std::cmp_greater_equal(n, core_sensors.size())) n = 0;\n\t\t\t\t\tcore_map[Shared::coreCount / 2 + i] = n++;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcore_map.clear();\n\t\t\t\tfor (int i = 0, n = 0; i < Shared::coreCount; i++) {\n\t\t\t\t\tif (std::cmp_greater_equal(n, core_sensors.size())) n = 0;\n\t\t\t\t\tcore_map[i] = n++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//? Apply user set custom mapping if any\n\t\tconst auto& custom_map = Config::getS(\"cpu_core_map\");\n\t\tif (not custom_map.empty()) {\n\t\t\ttry {\n\t\t\t\tfor (const auto& split : ssplit(custom_map)) {\n\t\t\t\t\tconst auto vals = ssplit(split, ':');\n\t\t\t\t\tif (vals.size() != 2) continue;\n\t\t\t\t\tint change_id = std::stoi(vals.at(0));\n\t\t\t\t\tint new_id = std::stoi(vals.at(1));\n\t\t\t\t\tif (not core_map.contains(change_id) or cmp_greater(new_id, core_sensors.size())) continue;\n\t\t\t\t\tcore_map.at(change_id) = new_id;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (...) {}\n\t\t}\n\n\t\treturn core_map;\n\t}\n\n\tstruct battery {\n\t\tfs::path base_dir, energy_now, charge_now, energy_full, charge_full, power_now, current_now, voltage_now, status, online;\n\t\tstring device_type;\n\t\tbool use_energy_or_charge = true;\n\t\tbool use_power = true;\n\t};\n\n\tauto get_battery() -> tuple<int, float, long, string> {\n\t\tif (not has_battery) return {0, 0, 0, \"\"};\n\t\tstatic string auto_sel;\n\t\tstatic std::unordered_map<string, battery> batteries;\n\n\t\t//? Get paths to needed files and check for valid values on first run\n\t\tif (batteries.empty() and has_battery) {\n\t\t\ttry {\n\t\t\t\tif (fs::exists(\"/sys/class/power_supply\")) {\n\t\t\t\t\tfor (const auto& d : fs::directory_iterator(\"/sys/class/power_supply\")) {\n\t\t\t\t\t\t//? Only consider online power supplies of type Battery or UPS\n\t\t\t\t\t\t//? see kernel docs for details on the file structure and contents\n\t\t\t\t\t\t//? https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-power\n\t\t\t\t\t\tbattery new_bat;\n\t\t\t\t\t\tfs::path bat_dir;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tif (not d.is_directory()\n\t\t\t\t\t\t\t\tor not fs::exists(d.path() / \"type\")\n\t\t\t\t\t\t\t\tor not fs::exists(d.path() / \"present\")\n\t\t\t\t\t\t\t\tor stoi(readfile(d.path() / \"present\")) != 1)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tstring dev_type = readfile(d.path() / \"type\");\n\t\t\t\t\t\t\tif (is_in(dev_type, \"Battery\", \"UPS\")) {\n\t\t\t\t\t\t\t\tbat_dir = d.path();\n\t\t\t\t\t\t\t\tnew_bat.base_dir = d.path();\n\t\t\t\t\t\t\t\tnew_bat.device_type = dev_type;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (...) {\n\t\t\t\t\t\t\t//? skip power supplies not conforming to the kernel standard\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (fs::exists(bat_dir / \"energy_now\")) new_bat.energy_now = bat_dir / \"energy_now\";\n\t\t\t\t\t\telse if (fs::exists(bat_dir / \"charge_now\")) new_bat.charge_now = bat_dir / \"charge_now\";\n\t\t\t\t\t\telse new_bat.use_energy_or_charge = false;\n\n\t\t\t\t\t\tif (fs::exists(bat_dir / \"energy_full\")) new_bat.energy_full = bat_dir / \"energy_full\";\n\t\t\t\t\t\telse if (fs::exists(bat_dir / \"charge_full\")) new_bat.charge_full = bat_dir / \"charge_full\";\n\t\t\t\t\t\telse new_bat.use_energy_or_charge = false;\n\n\t\t\t\t\t\tif (not new_bat.use_energy_or_charge and not fs::exists(bat_dir / \"capacity\")) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (fs::exists(bat_dir / \"power_now\")) {\n\t\t\t\t\t\t\tnew_bat.power_now = bat_dir / \"power_now\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if ((fs::exists(bat_dir / \"current_now\")) and (fs::exists(bat_dir / \"voltage_now\"))) {\n\t\t\t\t\t\t\t new_bat.current_now = bat_dir / \"current_now\";\n\t\t\t\t\t\t\t new_bat.voltage_now = bat_dir / \"voltage_now\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tnew_bat.use_power = false;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (fs::exists(bat_dir / \"AC0/online\")) new_bat.online = bat_dir / \"AC0/online\";\n\t\t\t\t\t\telse if (fs::exists(bat_dir / \"AC/online\")) new_bat.online = bat_dir / \"AC/online\";\n\n\t\t\t\t\t\tbatteries[bat_dir.filename()] = new_bat;\n\t\t\t\t\t\tConfig::available_batteries.push_back(bat_dir.filename());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (...) {\n\t\t\t\tbatteries.clear();\n\t\t\t}\n\t\t\tif (batteries.empty()) {\n\t\t\t\thas_battery = false;\n\t\t\t\treturn {0, 0, 0, \"\"};\n\t\t\t}\n\t\t}\n\n\t\tauto& battery_sel = Config::getS(\"selected_battery\");\n\n\t\tif (auto_sel.empty()) {\n\t\t\tfor (auto& [name, bat] : batteries) {\n\t\t\t\tif (bat.device_type == \"Battery\") {\n\t\t\t\t\tauto_sel = name;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (auto_sel.empty()) auto_sel = batteries.begin()->first;\n\t\t}\n\n\t\tauto& b = (battery_sel != \"Auto\" and batteries.contains(battery_sel) ? batteries.at(battery_sel) : batteries.at(auto_sel));\n\n\t\tint percent = -1;\n\t\tlong seconds = -1;\n\t\tfloat watts = -1;\n\n\t\t//? Try to get battery percentage\n\t\tif (percent < 0) {\n\t\t\ttry {\n\t\t\t\tpercent = stoi(readfile(b.base_dir / \"capacity\", \"-1\"));\n\t\t\t}\n\t\t\tcatch (const std::invalid_argument&) { }\n\t\t\tcatch (const std::out_of_range&) { }\n\t\t}\n\t\tif (b.use_energy_or_charge and percent < 0) {\n\t\t\ttry {\n\t\t\t\tpercent = round(100.0 * stod(readfile(b.energy_now, \"-1\")) / stod(readfile(b.energy_full, \"1\")));\n\t\t\t}\n\t\t\tcatch (const std::invalid_argument&) { }\n\t\t\tcatch (const std::out_of_range&) { }\n\t\t}\n\t\tif (b.use_energy_or_charge and percent < 0) {\n\t\t\ttry {\n\t\t\t\tpercent = round(100.0 * stod(readfile(b.charge_now, \"-1\")) / stod(readfile(b.charge_full, \"1\")));\n\t\t\t}\n\t\t\tcatch (const std::invalid_argument&) { }\n\t\t\tcatch (const std::out_of_range&) { }\n\t\t}\n\t\tif (percent < 0) {\n\t\t\thas_battery = false;\n\t\t\treturn {0, 0, 0, \"\"};\n\t\t}\n\n\t\t//? Get charging/discharging status\n\t\tstring status = str_to_lower(readfile(b.base_dir / \"status\", \"unknown\"));\n\t\tif (status == \"unknown\" and not b.online.empty()) {\n\t\t\tconst auto online = readfile(b.online, \"0\");\n\t\t\tif (online == \"1\" and percent < 100) status = \"charging\";\n\t\t\telse if (online == \"1\") status = \"full\";\n\t\t\telse status = \"discharging\";\n\t\t}\n\n\t\t//? Get seconds to empty\n\t\tif (not is_in(status, \"charging\", \"full\")) {\n\t\t\tif (b.use_energy_or_charge ) {\n\t\t\t\tif (not b.power_now.empty()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tseconds = abs(round(stod(readfile(b.energy_now, \"0\")) / stod(readfile(b.power_now, \"1\")) * 3600));\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::invalid_argument&) { }\n\t\t\t\t\tcatch (const std::out_of_range&) { }\n\t\t\t\t}\n\t\t\t\telse if (not b.current_now.empty()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tseconds = abs(round(stod(readfile(b.charge_now, \"0\")) / stod(readfile(b.current_now, \"1\")) * 3600));\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::invalid_argument&) { }\n\t\t\t\t\tcatch (const std::out_of_range&) { }\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (seconds < 0 and fs::exists(b.base_dir / \"time_to_empty\")) {\n\t\t\t\ttry {\n\t\t\t\t\tseconds = stoll(readfile(b.base_dir / \"time_to_empty\", \"0\")) * 60;\n\t\t\t\t}\n\t\t\t\tcatch (const std::invalid_argument&) { }\n\t\t\t\tcatch (const std::out_of_range&) { }\n\t\t\t}\n\t\t}\n\t\t//? Or get seconds to full\n\t\telse if(is_in(status, \"charging\")) {\n\t\t\tif (b.use_energy_or_charge ) {\n\t\t\t\tif (not b.power_now.empty()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tseconds = (round(stod(readfile(b.energy_full , \"0\")) - round(stod(readfile(b.energy_now, \"0\"))))\n\t\t\t\t\t\t\t\t\t/ abs(stod(readfile(b.power_now, \"1\"))) * 3600);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::invalid_argument&) { }\n\t\t\t\t\tcatch (const std::out_of_range&) { }\n\t\t\t\t}\n\t\t\t\telse if (not b.current_now.empty()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tseconds = (round(stod(readfile(b.charge_full , \"0\")) - stod(readfile(b.charge_now, \"0\")))\n\t\t\t\t\t\t\t\t\t/ std::abs(stod(readfile(b.current_now, \"1\"))) * 3600);\n\t\t\t\t\t}\n\t\t\t\t\tcatch (const std::invalid_argument&) { }\n\t\t\t\t\tcatch (const std::out_of_range&) { }\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//? Get power draw\n\t\tif (b.use_power) {\n\t\t\tif (not b.power_now.empty()) {\n\t\t\t\ttry {\n\t\t\t\t\twatts = stof(readfile(b.power_now, \"-1\")) / 1000000.0F;\n\t\t\t\t}\n\t\t\t\tcatch (const std::invalid_argument&) { }\n\t\t\t\tcatch (const std::out_of_range&) { }\n\t\t\t}\n\t\t\telse if (not b.voltage_now.empty() and not b.current_now.empty()) {\n\t\t\t\ttry {\n\t\t\t\t\twatts = stof(readfile(b.current_now, \"-1\")) / 1000000.0F * stof(readfile(b.voltage_now, \"1\")) / 1000000.0F;\n\t\t\t\t}\n\t\t\t\tcatch (const std::invalid_argument&) { }\n\t\t\t\tcatch (const std::out_of_range&) { }\n\t\t\t}\n\n\t\t}\n\n\t\treturn {percent, watts, seconds, status};\n\t}\n\n\tlong long get_cpuConsumptionUJoules()\n\t{\n\t\tlong long consumption = -1;\n\t\tconst auto rapl_power_usage_path = \"/sys/class/powercap/intel-rapl:0/energy_uj\";\n\t\tstd::ifstream file(rapl_power_usage_path);\n\t\tif(file.good())\n\t\t{\n\t\t\tfile >> consumption;\n\t\t}\n\t\treturn consumption;\n\t}\n\n\tfloat get_cpuConsumptionWatts()\n\t{\n\t\tstatic long long previous_usage = 0;\n\t\tstatic long long previous_timestamp = 0;\n\n\t\tif (previous_usage == 0)\n\t\t{\n\t\t\tprevious_usage = get_cpuConsumptionUJoules();\n\t\t\tprevious_timestamp = get_monotonicTimeUSec();\n\t\t\tsupports_watts = (previous_usage > 0);\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (!supports_watts)\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\n\t\tauto current_timestamp = get_monotonicTimeUSec();\n\t\tauto current_usage = get_cpuConsumptionUJoules();\n\n\t\tauto watts = (float)(current_usage - previous_usage) / (float)(current_timestamp - previous_timestamp);\n\n\t\tprevious_timestamp = current_timestamp;\n\t\tprevious_usage = current_usage;\n\n\t\treturn watts;\n\t}\n\n    static constexpr auto to_int(std::string_view view) {\n        std::uint32_t value {};\n        std::from_chars(view.data(), view.data() + view.size(), value);\n        return value;\n    }\n\n    static constexpr auto detect_active_cpus() {\n        auto stream = std::ifstream { \"/sys/fs/cgroup/cpuset.cpus.effective\" };\n        auto buf = std::string { std::istreambuf_iterator<char> { stream }, {} };\n\n        if (buf.empty()) {\n            return std::views::iota(0, Shared::coreCount) | std::ranges::to<std::vector<std::int32_t>>();\n        }\n\n        return buf | std::views::split(',') | std::views::transform([](auto&& range) -> auto {\n                   auto view = std::string_view { range };\n                   auto dash = view.find('-');\n\n                   if (dash == std::string_view::npos) {\n                       // Single CPU, return iota of single element\n                       auto value = to_int(view);\n                       return std::views::iota(value, value + 1);\n                   }\n\n                   auto start = to_int(view.substr(0, dash));\n                   auto end = to_int(view.substr(dash + 1));\n                   return std::views::iota(start, end + 1);\n               }) |\n               std::views::join | std::ranges::to<std::vector<std::int32_t>>();\n    }\n\n\tauto collect(bool no_update) -> cpu_info& {\n\t\tif (Runner::stopping or (no_update and not current_cpu.cpu_percent.at(\"total\").empty())) return current_cpu;\n\t\tauto& cpu = current_cpu;\n\n\t\tif (Config::getB(\"show_cpu_freq\"))\n\t\t\tcpuHz = get_cpuHz();\n\n\t\tif (getloadavg(cpu.load_avg.data(), cpu.load_avg.size()) < 0) {\n\t\t\tLogger::error(\"failed to get load averages\");\n\t\t}\n\n\t\tifstream cread;\n\n\t\ttry {\n\t\t\t//? Get cpu total times for all cores from /proc/stat\n\t\t\tstring cpu_name;\n\t\t\tcread.open(Shared::procPath / \"stat\");\n\t\t\tint i = 0;\n\t\t\tint target = Shared::coreCount;\n\t\t\tfor (; i <= target or (cread.good() and cread.peek() == 'c'); i++) {\n\t\t\t\t//? Make sure to add zero value for missing core values if at end of file\n\t\t\t\tif ((not cread.good() or cread.peek() != 'c') and i <= target) {\n\t\t\t\t\tif (i == 0) throw std::runtime_error(\"Failed to parse /proc/stat\");\n\t\t\t\t\telse {\n\t\t\t\t\t\t//? Fix container sizes if new cores are detected\n\t\t\t\t\t\twhile (cmp_less(cpu.core_percent.size(), i)) {\n\t\t\t\t\t\t\tcore_old_totals.push_back(0);\n\t\t\t\t\t\t\tcore_old_idles.push_back(0);\n\t\t\t\t\t\t\tcpu.core_percent.emplace_back();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcpu.core_percent.at(i-1).push_back(0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (i == 0) cread.ignore(SSmax, ' ');\n\t\t\t\t\telse {\n\t\t\t\t\t\tcread >> cpu_name;\n\t\t\t\t\t\tint cpuNum = std::stoi(cpu_name.substr(3));\n\t\t\t\t\t\tif (cpuNum >= target - 1) target = cpuNum + (cread.peek() == 'c' ? 2 : 1);\n\n\t\t\t\t\t\t//? Add zero value for core if core number is missing from /proc/stat\n\t\t\t\t\t\twhile (i - 1 < cpuNum) {\n\t\t\t\t\t\t\t//? Fix container sizes if new cores are detected\n\t\t\t\t\t\t\twhile (cmp_less(cpu.core_percent.size(), i)) {\n\t\t\t\t\t\t\t\tcore_old_totals.push_back(0);\n\t\t\t\t\t\t\t\tcore_old_idles.push_back(0);\n\t\t\t\t\t\t\t\tcpu.core_percent.emplace_back();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcpu.core_percent[i-1].push_back(0);\n\t\t\t\t\t\t\tif (cpu.core_percent.at(i-1).size() > 40) cpu.core_percent.at(i-1).pop_front();\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t//? Expected on kernel 2.6.3> : 0=user, 1=nice, 2=system, 3=idle, 4=iowait, 5=irq, 6=softirq, 7=steal, 8=guest, 9=guest_nice\n\t\t\t\t\tvector<long long> times;\n\t\t\t\t\tlong long total_sum = 0;\n\n\t\t\t\t\tfor (uint64_t val; cread >> val; total_sum += val) {\n\t\t\t\t\t\ttimes.push_back(val);\n\t\t\t\t\t}\n\t\t\t\t\tcread.clear();\n\t\t\t\t\tif (times.size() < 4) throw std::runtime_error(\"Malformed /proc/stat\");\n\n\t\t\t\t\t//? Subtract fields 8-9 and any future unknown fields\n\t\t\t\t\tconst long long totals = max(0ll, total_sum - (times.size() > 8 ? std::accumulate(times.begin() + 8, times.end(), 0ll) : 0));\n\n\t\t\t\t\t//? Add iowait field if present\n\t\t\t\t\tconst long long idles = max(0ll, times.at(3) + (times.size() > 4 ? times.at(4) : 0));\n\n\t\t\t\t\t//? Calculate values for totals from first line of stat\n\t\t\t\t\tif (i == 0) {\n\t\t\t\t\t\tconst long long calc_totals = max(1ll, totals - cpu_old.at(\"totals\"));\n\t\t\t\t\t\tconst long long calc_idles = max(0ll, idles - cpu_old.at(\"idles\"));\n\t\t\t\t\t\tcpu_old.at(\"totals\") = totals;\n\t\t\t\t\t\tcpu_old.at(\"idles\") = idles;\n\n\t\t\t\t\t\t//? Total usage of cpu\n\t\t\t\t\t\tcpu.cpu_percent.at(\"total\").push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));\n\n\t\t\t\t\t\t//? Reduce size if there are more values than needed for graph\n\t\t\t\t\t\twhile (cmp_greater(cpu.cpu_percent.at(\"total\").size(), width * 2)) cpu.cpu_percent.at(\"total\").pop_front();\n\n\t\t\t\t\t\t//? Populate cpu.cpu_percent with all fields from stat\n\t\t\t\t\t\tfor (int ii = 0; const auto& val : times) {\n\t\t\t\t\t\t\tcpu.cpu_percent.at(time_names.at(ii)).push_back(clamp((long long)round((double)(val - cpu_old.at(time_names.at(ii))) * 100 / calc_totals), 0ll, 100ll));\n\t\t\t\t\t\t\tcpu_old.at(time_names.at(ii)) = val;\n\n\t\t\t\t\t\t\t//? Reduce size if there are more values than needed for graph\n\t\t\t\t\t\t\twhile (cmp_greater(cpu.cpu_percent.at(time_names.at(ii)).size(), width * 2)) cpu.cpu_percent.at(time_names.at(ii)).pop_front();\n\n\t\t\t\t\t\t\tif (++ii == 10) break;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\t//? Calculate cpu total for each core\n\t\t\t\t\telse {\n\t\t\t\t\t\t//? Fix container sizes if new cores are detected\n\t\t\t\t\t\twhile (cmp_less(cpu.core_percent.size(), i)) {\n\t\t\t\t\t\t\tcore_old_totals.push_back(0);\n\t\t\t\t\t\t\tcore_old_idles.push_back(0);\n\t\t\t\t\t\t\tcpu.core_percent.emplace_back();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst long long calc_totals = max(1ll, totals - core_old_totals.at(i-1));\n\t\t\t\t\t\tconst long long calc_idles = max(0ll, idles - core_old_idles.at(i-1));\n\t\t\t\t\t\tcore_old_totals.at(i-1) = totals;\n\t\t\t\t\t\tcore_old_idles.at(i-1) = idles;\n\n\t\t\t\t\t\tcpu.core_percent.at(i-1).push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//? Reduce size if there are more values than needed for graph\n\t\t\t\tif (cpu.core_percent.at(i-1).size() > 40) cpu.core_percent.at(i-1).pop_front();\n\t\t\t}\n\n\t\t\t//? Notify main thread to redraw screen if we found more cores than previously detected\n\t\t\tif (cmp_greater(cpu.core_percent.size(), Shared::coreCount)) {\n\t\t\t\tLogger::debug(\"Changing CPU max corecount from {} to {}.\", Shared::coreCount, cpu.core_percent.size());\n\t\t\t\tRunner::coreNum_reset = true;\n\t\t\t\tShared::coreCount = cpu.core_percent.size();\n\t\t\t\twhile (cmp_less(current_cpu.temp.size(), cpu.core_percent.size() + 1)) current_cpu.temp.push_back({0});\n\t\t\t}\n\n\t\t}\n\t\tcatch (const std::exception& e) {\n\t\t\tLogger::debug(\"Cpu::collect() : {}\", e.what());\n\t\t\tif (cread.bad()) throw std::runtime_error(\"Failed to read /proc/stat\");\n\t\t\telse throw std::runtime_error(fmt::format(\"Cpu::collect() : {}\", e.what()));\n\t\t}\n\n\t\tif (Config::getB(\"check_temp\") and got_sensors)\n\t\t\tupdate_sensors();\n\n\t\tif (Config::getB(\"show_battery\") and has_battery)\n\t\t\tcurrent_bat = get_battery();\n\n\t\tif (Config::getB(\"show_cpu_watts\") and supports_watts)\n\t\t\tcurrent_cpu.usage_watts = get_cpuConsumptionWatts();\n\n\t\tcpu.active_cpus = std::make_optional(detect_active_cpus());\n\n\t\treturn cpu;\n\t}\n}\n\n#ifdef GPU_SUPPORT\nnamespace Gpu {\n    //? NVIDIA\n    namespace Nvml {\n\t\tbool init() {\n\t\t\tif (initialized) return false;\n\n\t\t\t//? Dynamic loading & linking\n\t\t\t//? Try possible library names for libnvidia-ml.so\n\t\t\tconst array libNvAlts = {\n\t\t\t\t\"libnvidia-ml.so\",\n\t\t\t\t\"libnvidia-ml.so.1\",\n\t\t\t};\n\n\t\t\tfor (const auto& l : libNvAlts) {\n\t\t\t\tnvml_dl_handle = dlopen(l, RTLD_LAZY);\n\t\t\t\tif (nvml_dl_handle != nullptr) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n \t\t\tif (!nvml_dl_handle) {\n\t\t\t\tLogger::info(\"Failed to load libnvidia-ml.so, NVIDIA GPUs will not be detected: {}\", dlerror());\n \t\t\t\treturn false;\n \t\t\t}\n\n\t\t\tauto load_nvml_sym = [&](const char sym_name[]) {\n\t\t\t\tauto sym = dlsym(nvml_dl_handle, sym_name);\n\t\t\t\tauto err = dlerror();\n\t\t\t\tif (err != nullptr) {\n\t\t\t\t\tLogger::error(\"NVML: Couldn't find function {}: {}\", sym_name, err);\n\t\t\t\t\treturn (void*)nullptr;\n\t\t\t\t} else return sym;\n\t\t\t};\n\n            #define LOAD_SYM(NAME)  if ((NAME = (decltype(NAME))load_nvml_sym(#NAME)) == nullptr) return false\n\n\t\t    LOAD_SYM(nvmlErrorString);\n\t\t    LOAD_SYM(nvmlInit);\n\t\t    LOAD_SYM(nvmlShutdown);\n\t\t    LOAD_SYM(nvmlDeviceGetCount);\n\t\t    LOAD_SYM(nvmlDeviceGetHandleByIndex);\n\t\t    LOAD_SYM(nvmlDeviceGetName);\n\t\t    LOAD_SYM(nvmlDeviceGetPowerManagementLimit);\n\t\t    LOAD_SYM(nvmlDeviceGetTemperatureThreshold);\n\t\t    LOAD_SYM(nvmlDeviceGetUtilizationRates);\n\t\t    LOAD_SYM(nvmlDeviceGetClockInfo);\n\t\t    LOAD_SYM(nvmlDeviceGetPowerUsage);\n\t\t    LOAD_SYM(nvmlDeviceGetPowerState);\n\t\t    LOAD_SYM(nvmlDeviceGetTemperature);\n\t\t    LOAD_SYM(nvmlDeviceGetMemoryInfo);\n\t\t    LOAD_SYM(nvmlDeviceGetPcieThroughput);\n\t\t\tLOAD_SYM(nvmlDeviceGetEncoderUtilization);\n\t\t\tLOAD_SYM(nvmlDeviceGetDecoderUtilization);\n\n            #undef LOAD_SYM\n\n\t\t\t//? Function calls\n\t\t\tnvmlReturn_t result = nvmlInit();\n    \t\tif (result != NVML_SUCCESS) {\n    \t\t\tLogger::debug(\"Failed to initialize NVML, NVIDIA GPUs will not be detected: {}\", nvmlErrorString(result));\n    \t\t\treturn false;\n    \t\t}\n\n\t\t\t//? Device count\n\t\t\tresult = nvmlDeviceGetCount(&device_count);\n    \t\tif (result != NVML_SUCCESS) {\n    \t\t\tLogger::warning(\"NVML: Failed to get device count: {}\", nvmlErrorString(result));\n    \t\t\treturn false;\n    \t\t}\n\n\t\t\tif (device_count > 0) {\n\t\t\t\tdevices.resize(device_count);\n\t\t\t\tgpus.resize(device_count);\n\t\t\t\tgpu_names.resize(device_count);\n\n\t\t\t\tinitialized = true;\n\n\t\t\t\t//? Check supported functions & get maximums\n\t\t\t\tNvml::collect<1>(gpus.data());\n\n\t\t\t\treturn true;\n\t\t\t} else {initialized = true; shutdown(); return false;}\n\t\t}\n\n\t\tbool shutdown() {\n\t\t\tif (!initialized) return false;\n\t\t\tnvmlReturn_t result = nvmlShutdown();\n\t\t\tif (NVML_SUCCESS == result) {\n\t\t\t\tinitialized = false;\n\t\t\t\tdlclose(nvml_dl_handle);\n\t\t\t} else Logger::warning(\"Failed to shutdown NVML: {}\", nvmlErrorString(result));\n\n\t\t\treturn !initialized;\n\t\t}\n\n\t\ttemplate <bool is_init> // collect<1> is called in Nvml::init(), and populates gpus.supported_functions\n\t\tbool collect(gpu_info* gpus_slice) { // raw pointer to vector data, size == device_count\n\t\t\tif (!initialized) return false;\n\n\t\t\tnvmlReturn_t result;\n\t\t\tstd::thread pcie_tx_thread, pcie_rx_thread;\n\t\t\t// DebugTimer nvTotalTimer(\"Nvidia Total\");\n\t\t\tfor (unsigned int i = 0; i < device_count; ++i) {\n\t\t\t\tif constexpr(is_init) {\n\t\t\t\t\t//? Device Handle\n    \t\t\t\tresult = nvmlDeviceGetHandleByIndex(i, devices.data() + i);\n        \t\t\tif (result != NVML_SUCCESS) {\n    \t\t\t\t\tLogger::warning(\"NVML: Failed to get device handle: {}\", nvmlErrorString(result));\n\t\t\t\t\t\tgpus[i].supported_functions = {false, false, false, false, false, false, false, false, false, false};\n    \t\t\t\t\tcontinue;\n        \t\t\t}\n\n\t\t\t\t\t//? Device name\n\t\t\t\t\tchar name[NVML_DEVICE_NAME_BUFFER_SIZE];\n    \t\t\t\tresult = nvmlDeviceGetName(devices[i], name, NVML_DEVICE_NAME_BUFFER_SIZE);\n        \t\t\tif (result != NVML_SUCCESS)\n    \t\t\t\t\tLogger::warning(\"NVML: Failed to get device name: {}\", nvmlErrorString(result));\n        \t\t\telse {\n        \t\t\t\tgpu_names[i] = string(name);\n        \t\t\t\tfor (const auto& brand : {\"NVIDIA\", \"Nvidia\", \"(R)\", \"(TM)\"}) {\n\t\t\t\t\t\t\tgpu_names[i] = s_replace(gpu_names[i], brand, \"\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tgpu_names[i] = trim(gpu_names[i]);\n        \t\t\t}\n\n    \t\t\t\t//? Power usage\n    \t\t\t\tunsigned int max_power;\n    \t\t\t\tresult = nvmlDeviceGetPowerManagementLimit(devices[i], &max_power);\n    \t\t\t\tif (result != NVML_SUCCESS)\n\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get maximum GPU power draw, defaulting to 225W: {}\", nvmlErrorString(result));\n\t\t\t\t\telse {\n\t\t\t\t\t\tgpus[i].pwr_max_usage = max_power; // RSMI reports power in microWatts\n\t\t\t\t\t\tgpu_pwr_total_max += max_power;\n\t\t\t\t\t}\n\n\t\t\t\t\t//? Get temp_max\n\t\t\t\t\tunsigned int temp_max;\n    \t\t\t\tresult = nvmlDeviceGetTemperatureThreshold(devices[i], NVML_TEMPERATURE_THRESHOLD_SHUTDOWN, &temp_max);\n        \t\t\tif (result != NVML_SUCCESS)\n    \t\t\t\t\tLogger::warning(\"NVML: Failed to get maximum GPU temperature, defaulting to 110°C: {}\", nvmlErrorString(result));\n    \t\t\t\telse gpus[i].temp_max = (long long)temp_max;\n\t\t\t\t}\n\n\t\t\t\t//? PCIe link speeds, the data collection takes >=20ms each call so they run on separate threads\n\t\t\t\tif (gpus_slice[i].supported_functions.pcie_txrx and (Config::getB(\"nvml_measure_pcie_speeds\") or is_init)) {\n\t\t\t\t\tpcie_tx_thread = std::thread([gpus_slice, i]() {\n\t\t\t\t\t\tunsigned int tx;\n\t\t\t\t\t\tnvmlReturn_t result = nvmlDeviceGetPcieThroughput(devices[i], NVML_PCIE_UTIL_TX_BYTES, &tx);\n    \t\t\t\t\tif (result != NVML_SUCCESS) {\n\t\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get PCIe TX throughput: {}\", nvmlErrorString(result));\n\t\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.pcie_txrx = false;\n\t\t\t\t\t\t} else gpus_slice[i].pcie_tx = (long long)tx;\n\t\t\t\t\t});\n\n\t\t\t\t\tpcie_rx_thread = std::thread([gpus_slice, i]() {\n\t\t\t\t\t\tunsigned int rx;\n\t\t\t\t\t\tnvmlReturn_t result = nvmlDeviceGetPcieThroughput(devices[i], NVML_PCIE_UTIL_RX_BYTES, &rx);\n    \t\t\t\t\tif (result != NVML_SUCCESS) {\n\t\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get PCIe RX throughput: {}\", nvmlErrorString(result));\n\t\t\t\t\t\t} else gpus_slice[i].pcie_rx = (long long)rx;\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tgpus_slice[i].pcie_tx = -1;\n\t\t\t\t\tgpus_slice[i].pcie_rx = -1;\n\t\t\t\t}\n\n\t\t\t\t// DebugTimer nvTimer(\"Nv utilization\");\n\t\t\t\t//? GPU & memory utilization\n\t\t\t\tif (gpus_slice[i].supported_functions.gpu_utilization) {\n\t\t\t\t\tnvmlUtilization_t utilization;\n\t\t\t\t\tresult = nvmlDeviceGetUtilizationRates(devices[i], &utilization);\n    \t\t\t\tif (result != NVML_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get GPU utilization: {}\", nvmlErrorString(result));\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.gpu_utilization = false;\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.mem_utilization = false;\n    \t\t\t\t} else {\n\t\t\t\t\t\tgpus_slice[i].gpu_percent.at(\"gpu-totals\").push_back((long long)utilization.gpu);\n\t\t\t\t\t\tgpus_slice[i].mem_utilization_percent.push_back((long long)utilization.memory);\n    \t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// nvTimer.stop_rename_reset(\"Nv clock\");\n\t\t\t\t//? Clock speeds\n\t\t\t\tif (gpus_slice[i].supported_functions.gpu_clock) {\n\t\t\t\t\tunsigned int gpu_clock;\n\t\t\t\t\tresult = nvmlDeviceGetClockInfo(devices[i], NVML_CLOCK_GRAPHICS, &gpu_clock);\n    \t\t\t\tif (result != NVML_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get GPU clock speed: {}\", nvmlErrorString(result));\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false;\n\t\t\t\t\t} else gpus_slice[i].gpu_clock_speed = (long long)gpu_clock;\n\t\t\t\t}\n\n\t\t\t\tif (gpus_slice[i].supported_functions.mem_clock) {\n\t\t\t\t\tunsigned int mem_clock;\n\t\t\t\t\tresult = nvmlDeviceGetClockInfo(devices[i], NVML_CLOCK_MEM, &mem_clock);\n    \t\t\t\tif (result != NVML_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get VRAM clock speed: {}\", nvmlErrorString(result));\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false;\n\t\t\t\t\t} else gpus_slice[i].mem_clock_speed = (long long)mem_clock;\n\t\t\t\t}\n\n\t\t\t\t// nvTimer.stop_rename_reset(\"Nv power\");\n    \t\t\t//? Power usage & state\n\t\t\t\tif (gpus_slice[i].supported_functions.pwr_usage) {\n    \t\t\t\tunsigned int power;\n    \t\t\t\tresult = nvmlDeviceGetPowerUsage(devices[i], &power);\n    \t\t\t\tif (result != NVML_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get GPU power usage: {}\", nvmlErrorString(result));\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.pwr_usage = false;\n    \t\t\t\t} else {\n    \t\t\t\t\tgpus_slice[i].pwr_usage = (long long)power;\n\t\t\t\t\t\tif (gpus_slice[i].pwr_usage > gpus_slice[i].pwr_max_usage)\n\t\t\t\t\t\t\t\tgpus_slice[i].pwr_max_usage = gpus_slice[i].pwr_usage;\n    \t\t\t\t\tgpus_slice[i].gpu_percent.at(\"gpu-pwr-totals\").push_back(clamp((long long)round((double)gpus_slice[i].pwr_usage * 100.0 / (double)gpus_slice[i].pwr_max_usage), 0ll, 100ll));\n    \t\t\t\t}\n    \t\t\t}\n\n\t\t\t\tif (gpus_slice[i].supported_functions.pwr_state) {\n\t\t\t\t\tnvmlPstates_t pState;\n    \t\t\t\tresult = nvmlDeviceGetPowerState(devices[i], &pState);\n    \t\t\t\tif (result != NVML_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get GPU power state: {}\", nvmlErrorString(result));\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.pwr_state = false;\n    \t\t\t\t} else gpus_slice[i].pwr_state = static_cast<int>(pState);\n    \t\t\t}\n\n\t\t\t\t// nvTimer.stop_rename_reset(\"Nv temp\");\n    \t\t\t//? GPU temperature\n\t\t\t\tif (gpus_slice[i].supported_functions.temp_info) {\n    \t\t\t\tif (Config::getB(\"check_temp\")) {\n\t\t\t\t\t\tunsigned int temp;\n\t\t\t\t\t\tnvmlReturn_t result = nvmlDeviceGetTemperature(devices[i], NVML_TEMPERATURE_GPU, &temp);\n    \t\t\t\t\tif (result != NVML_SUCCESS) {\n\t\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get GPU temperature: {}\", nvmlErrorString(result));\n\t\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.temp_info = false;\n    \t\t\t\t\t} else gpus_slice[i].temp.push_back((long long)temp);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// nvTimer.stop_rename_reset(\"Nv mem\");\n\t\t\t\t//? Memory info\n\t\t\t\tif (gpus_slice[i].supported_functions.mem_total) {\n\t\t\t\t\tnvmlMemory_t memory;\n\t\t\t\t\tresult = nvmlDeviceGetMemoryInfo(devices[i], &memory);\n    \t\t\t\tif (result != NVML_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get VRAM info: {}\", nvmlErrorString(result));\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.mem_total = false;\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.mem_used = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgpus_slice[i].mem_total = memory.total;\n\t\t\t\t\t\tgpus_slice[i].mem_used = memory.used;\n\t\t\t\t\t\t//gpu.mem_free = memory.free;\n\n\t\t\t\t\t\tauto used_percent = (long long)round((double)memory.used * 100.0 / (double)memory.total);\n\t\t\t\t\t\tgpus_slice[i].gpu_percent.at(\"gpu-vram-totals\").push_back(used_percent);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// nvTimer.stop_rename_reset(\"Nv enc\");\n\t\t\t\t//? Encoder info\n\t\t\t\tif (gpus_slice[i].supported_functions.encoder_utilization) {\n\t\t\t\t\tunsigned int utilization;\n\t\t\t\t\tunsigned int samplingPeriodUs;\n\t\t\t\t\tresult = nvmlDeviceGetEncoderUtilization(devices[i], &utilization, &samplingPeriodUs);\n\t\t\t\t\tif (result != NVML_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get encoder utilization: {}\", nvmlErrorString(result));\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.encoder_utilization = false;\n\t\t\t\t\t} else gpus_slice[i].encoder_utilization = (long long)utilization;\n\t\t\t\t}\n\n\t\t\t\t// nvTimer.stop_rename_reset(\"Nv dec\");\n\t\t\t\t//? Decoder info\n\t\t\t\tif (gpus_slice[i].supported_functions.decoder_utilization) {\n\t\t\t\t\tunsigned int utilization;\n\t\t\t\t\tunsigned int samplingPeriodUs;\n\t\t\t\t\tresult = nvmlDeviceGetDecoderUtilization(devices[i], &utilization, &samplingPeriodUs);\n\t\t\t\t\tif (result != NVML_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get decoder utilization: {}\", nvmlErrorString(result));\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.decoder_utilization = false;\n\t\t\t\t\t} else gpus_slice[i].decoder_utilization = (long long)utilization;\n\t\t\t\t}\n\n    \t\t\t//? TODO: Processes using GPU\n    \t\t\t\t/*unsigned int proc_info_len;\n    \t\t\t\tnvmlProcessInfo_t* proc_info = 0;\n    \t\t\t\tresult = nvmlDeviceGetComputeRunningProcesses_v3(device, &proc_info_len, proc_info);\n    \t\t\t\tif (result != NVML_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"NVML: Failed to get compute processes: {}\", nvmlErrorString(result));\n    \t\t\t\t} else {\n    \t\t\t\t\tfor (unsigned int i = 0; i < proc_info_len; ++i)\n    \t\t\t\t\t\tgpus_slice[i].graphics_processes.push_back({proc_info[i].pid, proc_info[i].usedGpuMemory});\n    \t\t\t\t}*/\n\n\t\t\t\t// nvTimer.stop_rename_reset(\"Nv pcie thread join\");\n\t\t\t\t//? Join PCIE TX/RX threads\n\t\t\t\tif constexpr(is_init) { // there doesn't seem to be a better way to do this, but this should be fine considering it's just 2 lines\n\t\t\t\t\tpcie_tx_thread.join();\n\t\t\t\t\tpcie_rx_thread.join();\n\t\t\t\t} else if (gpus_slice[i].supported_functions.pcie_txrx and Config::getB(\"nvml_measure_pcie_speeds\")) {\n\t\t\t\t\tpcie_tx_thread.join();\n\t\t\t\t\tpcie_rx_thread.join();\n\t\t\t\t}\n    \t\t}\n\n\t\t\treturn true;\n\t\t}\n    }\n\n\t//? AMD\n\tnamespace Rsmi {\n\t\tbool init() {\n\t\t\tif (initialized) return false;\n\n\t\t\t//? Dynamic loading & linking\n\t\t#if !defined(RSMI_STATIC)\n\n\t\t\t//? Try possible library paths and names for librocm_smi64.so\n\t\t\tconst array libRocAlts = {\n\t\t\t\t\"/opt/rocm/lib/librocm_smi64.so\",\n\t\t\t\t\"librocm_smi64.so\",\n\t\t\t\t\"librocm_smi64.so.5\", // fedora\n\t\t\t\t\"librocm_smi64.so.1.0\", // debian\n\t\t\t\t\"librocm_smi64.so.6\"\n\t\t\t};\n\n\t\t\tfor (const auto& l : libRocAlts) {\n\t\t\t\trsmi_dl_handle = dlopen(l, RTLD_LAZY);\n\t\t\t\tif (rsmi_dl_handle != nullptr) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n \t\t\t}\n\n\t\t\tif (!rsmi_dl_handle) {\n\t\t\t\tLogger::info(\"Failed to load librocm_smi64.so, AMD GPUs will not be detected: {}\", dlerror());\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tauto load_rsmi_sym = [&](const char sym_name[]) {\n\t\t\t\tauto sym = dlsym(rsmi_dl_handle, sym_name);\n\t\t\t\tauto err = dlerror();\n\t\t\t\tif (err != nullptr) {\n\t\t\t\t\tLogger::error(\"ROCm SMI: Couldn't find function {}: {}\", sym_name, err);\n\t\t\t\t\treturn (void*)nullptr;\n\t\t\t\t} else return sym;\n\t\t\t};\n\n            #define LOAD_SYM(NAME)  if ((NAME = (decltype(NAME))load_rsmi_sym(#NAME)) == nullptr) return false\n\n\t\t    LOAD_SYM(rsmi_init);\n\t\t    LOAD_SYM(rsmi_shut_down);\n\t\t\tLOAD_SYM(rsmi_version_get);\n\t\t    LOAD_SYM(rsmi_num_monitor_devices);\n\t\t    LOAD_SYM(rsmi_dev_name_get);\n\t\t    LOAD_SYM(rsmi_dev_power_cap_get);\n\t\t    LOAD_SYM(rsmi_dev_temp_metric_get);\n\t\t    LOAD_SYM(rsmi_dev_busy_percent_get);\n\t\t    LOAD_SYM(rsmi_dev_memory_busy_percent_get);\n\t\t    LOAD_SYM(rsmi_dev_power_ave_get);\n\t\t    LOAD_SYM(rsmi_dev_memory_total_get);\n\t\t    LOAD_SYM(rsmi_dev_memory_usage_get);\n\t\t    LOAD_SYM(rsmi_dev_pci_throughput_get);\n\n            #undef LOAD_SYM\n        #endif\n\n\t\t\t//? Function calls\n\t\t\trsmi_status_t result = rsmi_init(0);\n\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\tLogger::debug(\"Failed to initialize ROCm SMI, AMD GPUs will not be detected\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t#if !defined(RSMI_STATIC)\n\t\t\t//? Check version\n\t\t\trsmi_version_t version;\n\t\t\tresult = rsmi_version_get(&version);\n\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get version\");\n\t\t\t\treturn false;\n\t\t\t} else if (version.major == 5) {\n\t\t\t\tif ((rsmi_dev_gpu_clk_freq_get_v5 = (decltype(rsmi_dev_gpu_clk_freq_get_v5))load_rsmi_sym(\"rsmi_dev_gpu_clk_freq_get\")) == nullptr)\n\t\t\t\t\treturn false;\n\t\t\t// In the release tarballs of rocm 6.0.0 and 6.0.2 the version queried with rsmi_version_get is 7.0.0.0\n\t\t\t// In rocm 7.2 the version is 1.0.0.0\n\t\t\t} else if (version.major == 1 || version.major == 6 || version.major == 7) {\n\t\t\t\tif ((rsmi_dev_gpu_clk_freq_get_v6 = (decltype(rsmi_dev_gpu_clk_freq_get_v6))load_rsmi_sym(\"rsmi_dev_gpu_clk_freq_get\")) == nullptr)\n\t\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\tLogger::warning(\"ROCm SMI: Dynamic loading only supported for version 5 and 6\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tversion_major = version.major;\n\t\t#endif\n\n\t\t\t//? Device count\n\t\t\tresult = rsmi_num_monitor_devices(&device_count);\n\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\tLogger::warning(\"ROCm SMI: Failed to fetch number of devices\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (device_count > 0) {\n\t\t\t\tgpus.resize(gpus.size() + device_count);\n\t\t\t\tgpu_names.resize(gpus.size() + device_count);\n\n\t\t\t\tinitialized = true;\n\n\t\t\t\t//? Check supported functions & get maximums\n\t\t\t\tRsmi::collect<1>(gpus.data() + Nvml::device_count);\n\n\t\t\t\treturn true;\n\t\t\t} else {initialized = true; shutdown(); return false;}\n\t\t}\n\n\t\tbool shutdown() {\n\t\t\tif (!initialized) return false;\n    \t\tif (rsmi_shut_down() == RSMI_STATUS_SUCCESS) {\n\t\t\t\tinitialized = false;\n\t\t\t#if !defined(RSMI_STATIC)\n\t\t\t\tdlclose(rsmi_dl_handle);\n\t\t\t#endif\n\t\t\t} else Logger::warning(\"Failed to shutdown ROCm SMI\");\n\n\t\t\treturn true;\n\t\t}\n\n\t\ttemplate <bool is_init>\n\t\tbool collect(gpu_info* gpus_slice) { // raw pointer to vector data, size == device_count, offset by Nvml::device_count elements\n\t\t\tif (!initialized) return false;\n\t\t\trsmi_status_t result;\n\n\t\t\tfor (uint32_t i = 0; i < device_count; ++i) {\n\t\t\t\tif constexpr(is_init) {\n\t\t\t\t\t//? Device name\n\t\t\t\t\tchar name[RSMI_DEVICE_NAME_BUFFER_SIZE];\n    \t\t\t\tresult = rsmi_dev_name_get(i, name, RSMI_DEVICE_NAME_BUFFER_SIZE);\n        \t\t\tif (result != RSMI_STATUS_SUCCESS)\n    \t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get device name\");\n        \t\t\telse gpu_names[Nvml::device_count + i] = string(name);\n\n    \t\t\t\t//? Power usage\n    \t\t\t\tuint64_t max_power;\n    \t\t\t\tresult = rsmi_dev_power_cap_get(i, 0, &max_power);\n    \t\t\t\tif (result != RSMI_STATUS_SUCCESS)\n\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get maximum GPU power draw, defaulting to 225W\");\n\t\t\t\t\telse {\n\t\t\t\t\t\tgpus_slice[i].pwr_max_usage = (long long)(max_power/1000); // RSMI reports power in microWatts\n\t\t\t\t\t\tgpu_pwr_total_max += gpus_slice[i].pwr_max_usage;\n\t\t\t\t\t}\n\n\t\t\t\t\t//? Get temp_max\n\t\t\t\t\tint64_t temp_max;\n    \t\t\t\tresult = rsmi_dev_temp_metric_get(i, RSMI_TEMP_TYPE_EDGE, RSMI_TEMP_MAX, &temp_max);\n        \t\t\tif (result != RSMI_STATUS_SUCCESS)\n    \t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get maximum GPU temperature, defaulting to 110°C\");\n    \t\t\t\telse gpus_slice[i].temp_max = (long long)temp_max;\n\n\t\t\t\t\t//? Disable encoder and decoder utilisation on AMD\n\t\t\t\t\tgpus_slice[i].supported_functions.encoder_utilization = false;\n\t\t\t\t\tgpus_slice[i].supported_functions.decoder_utilization = false;\n    \t\t\t}\n\n\t\t\t\t//? GPU utilization\n\t\t\t\tif (gpus_slice[i].supported_functions.gpu_utilization) {\n\t\t\t\t\tuint32_t utilization;\n\t\t\t\t\tresult = rsmi_dev_busy_percent_get(i, &utilization);\n    \t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get GPU utilization\");\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.gpu_utilization = false;\n    \t\t\t\t} else gpus_slice[i].gpu_percent.at(\"gpu-totals\").push_back((long long)utilization);\n\t\t\t\t}\n\n\t\t\t\t//? Memory utilization\n\t\t\t\tif (gpus_slice[i].supported_functions.mem_utilization) {\n\t\t\t\t\tuint32_t utilization;\n\t\t\t\t\tresult = rsmi_dev_memory_busy_percent_get(i, &utilization);\n    \t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get VRAM utilization\");\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.mem_utilization = false;\n    \t\t\t\t} else gpus_slice[i].mem_utilization_percent.push_back((long long)utilization);\n\t\t\t\t}\n\t\t\t#if !defined(RSMI_STATIC)\n\t\t\t\t//? Clock speeds\n\t\t\t\tif (gpus_slice[i].supported_functions.gpu_clock) {\n\t\t\t\t\tif (version_major == 5) {\n\t\t\t\t\t\trsmi_frequencies_t_v5 frequencies;\n\t\t\t\t\t\tresult = rsmi_dev_gpu_clk_freq_get_v5(i, RSMI_CLK_TYPE_SYS, &frequencies);\n\t\t\t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get GPU clock speed: \");\n\t\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false;\n\t\t\t\t\t\t} else gpus_slice[i].gpu_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz\n\t\t\t\t\t}\n\t\t\t\t\telse if (version_major == 6 || version_major == 7) {\n\t\t\t\t\t\trsmi_frequencies_t_v6 frequencies;\n\t\t\t\t\t\tresult = rsmi_dev_gpu_clk_freq_get_v6(i, RSMI_CLK_TYPE_SYS, &frequencies);\n\t\t\t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get GPU clock speed: \");\n\t\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false;\n\t\t\t\t\t\t} else gpus_slice[i].gpu_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (gpus_slice[i].supported_functions.mem_clock) {\n\t\t\t\t\tif (version_major == 5) {\n\t\t\t\t\t\trsmi_frequencies_t_v5 frequencies;\n\t\t\t\t\t\tresult = rsmi_dev_gpu_clk_freq_get_v5(i, RSMI_CLK_TYPE_MEM, &frequencies);\n\t\t\t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get VRAM clock speed: \");\n\t\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false;\n\t\t\t\t\t\t} else gpus_slice[i].mem_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz\n\t\t\t\t\t}\n\t\t\t\t\telse if (version_major == 6 || version_major == 7) {\n\t\t\t\t\t\trsmi_frequencies_t_v6 frequencies;\n\t\t\t\t\t\tresult = rsmi_dev_gpu_clk_freq_get_v6(i, RSMI_CLK_TYPE_MEM, &frequencies);\n\t\t\t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get VRAM clock speed: \");\n\t\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false;\n\t\t\t\t\t\t} else gpus_slice[i].mem_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t#else\n\t\t\t\t//? Clock speeds\n\t\t\t\tif (gpus_slice[i].supported_functions.gpu_clock) {\n\t\t\t\t\trsmi_frequencies_t frequencies;\n\t\t\t\t\tresult = rsmi_dev_gpu_clk_freq_get(i, RSMI_CLK_TYPE_SYS, &frequencies);\n    \t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get GPU clock speed: \");\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false;\n    \t\t\t\t} else gpus_slice[i].gpu_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz\n\t\t\t\t}\n\n\t\t\t\tif (gpus_slice[i].supported_functions.mem_clock) {\n\t\t\t\t\trsmi_frequencies_t frequencies;\n\t\t\t\t\tresult = rsmi_dev_gpu_clk_freq_get(i, RSMI_CLK_TYPE_MEM, &frequencies);\n    \t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get VRAM clock speed: \");\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false;\n    \t\t\t\t} else gpus_slice[i].mem_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz\n\t\t\t\t}\n\t\t\t#endif\n\n    \t\t\t//? Power usage & state\n\t\t\t\tif (gpus_slice[i].supported_functions.pwr_usage) {\n    \t\t\t\tuint64_t power;\n    \t\t\t\tresult = rsmi_dev_power_ave_get(i, 0, &power);\n    \t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get GPU power usage\");\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.pwr_usage = false;\n    \t\t\t\t} else {\n\t\t\t\t\t\t\tgpus_slice[i].pwr_usage = (long long)power / 1000;\n\t\t\t\t\t\t\tif (gpus_slice[i].pwr_usage > gpus_slice[i].pwr_max_usage)\n\t\t\t\t\t\t\t\tgpus_slice[i].pwr_max_usage = gpus_slice[i].pwr_usage;\n\t\t\t\t\t\t\tgpus_slice[i].gpu_percent.at(\"gpu-pwr-totals\").push_back(clamp((long long)round((double)gpus_slice[i].pwr_usage * 100.0 / (double)gpus_slice[i].pwr_max_usage), 0ll, 100ll));\n\t\t\t\t\t\t}\n\n\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.pwr_state = false;\n\t\t\t\t}\n\n    \t\t\t//? GPU temperature\n\t\t\t\tif (gpus_slice[i].supported_functions.temp_info) {\n    \t\t\t\tif (Config::getB(\"check_temp\") or is_init) {\n\t\t\t\t\t\tint64_t temp;\n    \t\t\t\t\tresult = rsmi_dev_temp_metric_get(i, RSMI_TEMP_TYPE_EDGE, RSMI_TEMP_CURRENT, &temp);\n        \t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n    \t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get GPU temperature\");\n\t\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.temp_info = false;\n    \t\t\t\t\t} else gpus_slice[i].temp.push_back((long long)temp/1000);\n    \t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//? Memory info\n\t\t\t\tif (gpus_slice[i].supported_functions.mem_total) {\n\t\t\t\t\tuint64_t total;\n\t\t\t\t\tresult = rsmi_dev_memory_total_get(i, RSMI_MEM_TYPE_VRAM, &total);\n    \t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get total VRAM\");\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.mem_total = false;\n\t\t\t\t\t} else gpus_slice[i].mem_total = total;\n\t\t\t\t}\n\n\t\t\t\tif (gpus_slice[i].supported_functions.mem_used) {\n\t\t\t\t\tuint64_t used;\n\t\t\t\t\tresult = rsmi_dev_memory_usage_get(i, RSMI_MEM_TYPE_VRAM, &used);\n    \t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get VRAM usage\");\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.mem_used = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgpus_slice[i].mem_used = used;\n\t\t\t\t\t\tif (gpus_slice[i].supported_functions.mem_total)\n\t\t\t\t\t\t\tgpus_slice[i].gpu_percent.at(\"gpu-vram-totals\").push_back((long long)round((double)used * 100.0 / (double)gpus_slice[i].mem_total));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//? PCIe link speeds\n\t\t\t\tif ((gpus_slice[i].supported_functions.pcie_txrx and Config::getB(\"rsmi_measure_pcie_speeds\")) or is_init) {\n\t\t\t\t\tuint64_t tx, rx;\n\t\t\t\t\tresult = rsmi_dev_pci_throughput_get(i, &tx, &rx, nullptr);\n    \t\t\t\tif (result != RSMI_STATUS_SUCCESS) {\n\t\t\t\t\t\tLogger::warning(\"ROCm SMI: Failed to get PCIe throughput\");\n\t\t\t\t\t\tif constexpr(is_init) gpus_slice[i].supported_functions.pcie_txrx = false;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tgpus_slice[i].pcie_tx = (long long)tx;\n\t\t\t\t\t\tgpus_slice[i].pcie_rx = (long long)rx;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tgpus_slice[i].pcie_tx = -1;\n\t\t\t\t\tgpus_slice[i].pcie_rx = -1;\n\t\t\t\t}\n    \t\t}\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tnamespace Intel {\n\t\tbool init() {\n\t\t\tif (initialized) return false;\n\n\t\t\tchar *gpu_path = find_intel_gpu_dir();\n\t\t\tif (!gpu_path) {\n\t\t\t\tLogger::debug(\"Failed to find Intel GPU sysfs path, Intel GPUs will not be detected\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tchar *gpu_device_id = get_intel_device_id(gpu_path);\n\t\t\tif (!gpu_device_id) {\n\t\t\t\tLogger::debug(\"Failed to find Intel GPU device ID, Intel GPUs will not be detected\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tchar *gpu_device_name = get_intel_device_name(gpu_device_id);\n\t\t\tif (!gpu_device_name) {\n\t\t\t\tLogger::warning(\"Failed to find Intel GPU device name in internal database\");\n\t\t\t}\n\n\t\t\tfree(gpu_device_id);\n\n\t\t\tengines = discover_engines(device);\n\t\t\tif (!engines) {\n\t\t\t\tLogger::debug(\"Failed to find Intel GPU engines, Intel GPUs will not be detected\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tint ret = pmu_init(engines);\n\t\t\tif (ret) {\n\t\t\t\tLogger::warning(\"Intel GPU: Failed to initialize PMU\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tpmu_sample(engines);\n\n\t\t\tdevice_count = 1;\n\n\t\t\tgpus.resize(gpus.size() + device_count);\n\t\t\tgpu_names.resize(gpus.size() + device_count);\n\n\t\t\tif (gpu_device_name) {\n\t\t\t\tgpu_names[Nvml::device_count + Rsmi::device_count] = string(gpu_device_name);\n\t\t\t} else {\n\t\t\t\tgpu_names[Nvml::device_count + Rsmi::device_count] = \"Intel GPU\";\n\t\t\t}\n\n\t\t\tfree(gpu_device_name);\n\n\t\t\tinitialized = true;\n\t\t\tIntel::collect<1>(gpus.data() + Nvml::device_count + Rsmi::device_count);\n\n\t\t\treturn true;\n\t\t}\n\n\t\tbool shutdown() {\n\t\t\tif (!initialized) return false;\n\t\t\tif (engines) {\n\t\t\t\tfree_engines(engines);\n\t\t\t\tengines = nullptr;\n\t\t\t}\n\t\t\tinitialized = false;\n\t\t\treturn true;\n\t\t}\n\n\t\ttemplate <bool is_init> bool collect(gpu_info* gpus_slice) {\n\t\t\tif (!initialized) return false;\n\n\t\t\tif constexpr(is_init) {\n\t\t\t\tgpus_slice->supported_functions = {\n\t\t\t\t\t.gpu_utilization = true,\n\t\t\t\t\t.mem_utilization = false,\n\t\t\t\t\t.gpu_clock = true,\n\t\t\t\t\t.mem_clock = false,\n\t\t\t\t\t.pwr_usage = true,\n\t\t\t\t\t.pwr_state = false,\n\t\t\t\t\t.temp_info = false,\n\t\t\t\t\t.mem_total = false,\n\t\t\t\t\t.mem_used = false,\n\t\t\t\t\t.pcie_txrx = false,\n\t\t\t\t\t.encoder_utilization = false,\n\t\t\t\t\t.decoder_utilization = false\n\t\t\t\t};\n\n\t\t\t\tgpus_slice->pwr_max_usage = 10'000; //? 10W\n\t\t\t}\n\n\t\t\tpmu_sample(engines);\n\t\t\tdouble t = (double)(engines->ts.cur - engines->ts.prev) / 1e9;\n\n\t\t\tdouble max_util = 0;\n\t\t\tfor (unsigned int i = 0; i < engines->num_engines; i++) {\n\t\t\t\tstruct engine *engine = &(&engines->engine)[i];\n\t\t\t\tdouble util = pmu_calc(&engine->busy.val, 1e9, t, 100);\n\t\t\t\tif (util > max_util) {\n\t\t\t\t\tmax_util = util;\n\t\t\t\t}\n\t\t\t}\n\t\t\tgpus_slice->gpu_percent.at(\"gpu-totals\").push_back((long long)round(max_util));\n\n\t\t\tdouble pwr = pmu_calc(&engines->r_gpu.val, 1, t, engines->r_gpu.scale); // in Watts\n\t\t\tgpus_slice->pwr_usage = (long long)round(pwr * 1000);\n\t\t\tif (gpus_slice->pwr_usage > gpus_slice->pwr_max_usage)\n\t\t\t\tgpus_slice->pwr_max_usage = gpus_slice->pwr_usage;\n\n\t\t\tgpus_slice->gpu_percent.at(\"gpu-pwr-totals\").push_back(clamp((long long)round((double)gpus_slice->pwr_usage * 100.0 / (double)gpus_slice->pwr_max_usage), 0ll, 100ll));\n\n\t\t\tdouble freq = pmu_calc(&engines->freq_act.val, 1, t, 1); // in MHz\n\t\t\tgpus_slice->gpu_clock_speed = (unsigned int)round(freq);\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t//? Collect data from GPU-specific libraries\n\tauto collect(bool no_update) -> vector<gpu_info>& {\n\t\tif (Runner::stopping or (no_update and not gpus.empty())) return gpus;\n\n\t\t// DebugTimer gpu_timer(\"GPU Total\");\n\n\t\t//* Collect data\n\t\tNvml::collect<0>(gpus.data()); // raw pointer to vector data, size == Nvml::device_count\n\t\tRsmi::collect<0>(gpus.data() + Nvml::device_count); // size = Rsmi::device_count\n\t\tIntel::collect<0>(gpus.data() + Nvml::device_count + Rsmi::device_count); // size = Intel::device_count\n\n\t\t//* Calculate average usage\n\t\tlong long avg = 0;\n\t\tlong long mem_usage_total = 0;\n\t\tlong long mem_total = 0;\n\t\tlong long pwr_total = 0;\n\t\tfor (auto& gpu : gpus) {\n\t\t\tif (gpu.supported_functions.gpu_utilization)\n\t\t\t\tavg += gpu.gpu_percent.at(\"gpu-totals\").back();\n\t\t\tif (gpu.supported_functions.mem_used)\n\t\t\t\tmem_usage_total += gpu.mem_used;\n\t\t\tif (gpu.supported_functions.mem_total)\n\t\t\t\tmem_total += gpu.mem_total;\n\t\t\tif (gpu.supported_functions.pwr_usage)\n\t\t\t\tmem_total += gpu.pwr_usage;\n\n\t\t\t//* Trim vectors if there are more values than needed for graphs\n\t\t\tif (width != 0) {\n\t\t\t\t//? GPU & memory utilization\n\t\t\t\twhile (cmp_greater(gpu.gpu_percent.at(\"gpu-totals\").size(), width * 2)) gpu.gpu_percent.at(\"gpu-totals\").pop_front();\n\t\t\t\twhile (cmp_greater(gpu.mem_utilization_percent.size(), width)) gpu.mem_utilization_percent.pop_front();\n\t\t\t\t//? Power usage\n\t\t\t\twhile (cmp_greater(gpu.gpu_percent.at(\"gpu-pwr-totals\").size(), width)) gpu.gpu_percent.at(\"gpu-pwr-totals\").pop_front();\n\t\t\t\t//? Temperature\n\t\t\t\twhile (cmp_greater(gpu.temp.size(), 18)) gpu.temp.pop_front();\n\t\t\t\t//? Memory usage\n\t\t\t\twhile (cmp_greater(gpu.gpu_percent.at(\"gpu-vram-totals\").size(), width/2)) gpu.gpu_percent.at(\"gpu-vram-totals\").pop_front();\n\t\t\t}\n\t\t}\n\n\t\tshared_gpu_percent.at(\"gpu-average\").push_back(avg / gpus.size());\n\t\tif (mem_total != 0)\n\t\t\tshared_gpu_percent.at(\"gpu-vram-total\").push_back(mem_usage_total / mem_total);\n\t\tif (gpu_pwr_total_max != 0)\n\t\t\tshared_gpu_percent.at(\"gpu-pwr-total\").push_back(pwr_total / gpu_pwr_total_max);\n\n\t\tif (width != 0) {\n\t\t\twhile (cmp_greater(shared_gpu_percent.at(\"gpu-average\").size(), width * 2)) shared_gpu_percent.at(\"gpu-average\").pop_front();\n\t\t\twhile (cmp_greater(shared_gpu_percent.at(\"gpu-pwr-total\").size(), width * 2)) shared_gpu_percent.at(\"gpu-pwr-total\").pop_front();\n\t\t\twhile (cmp_greater(shared_gpu_percent.at(\"gpu-vram-total\").size(), width * 2)) shared_gpu_percent.at(\"gpu-vram-total\").pop_front();\n\t\t}\n\n\t\tcount = gpus.size();\n\n\t\treturn gpus;\n\t}\n}\n#endif\n\n/// Convert ascii escapes like \\040 into chars.\nstatic auto convert_ascii_escapes(const std::string& input) -> std::string {\n    std::string out;\n    out.reserve(input.size());\n\n    for (std::size_t i = 0; i < input.size(); ++i) {\n        if (input[i] == '\\\\' &&\n\t    \t// Peek the next three characters.\n            i + 3 < input.size() &&\n            std::isdigit(input[i + 1]) &&\n            std::isdigit(input[i + 2]) &&\n            std::isdigit(input[i + 3])) {\n\n\t\t\t// Convert octal chars to decimal int.\n\t\t\t//   '0' - '0' -> 0, '4' - '0' -> 4, '0' - '0' -> 0.\n\t\t\t//   0 * 64 (0)\n\t\t\t//   + 4 * 8 (32)\n\t\t\t//   + 0\n\t\t\t//   = 32 (ascii space)\n            int value = ((input[i + 1] - '0') * 64) + ((input[i + 2] - '0') * 8) + (input[i + 3] - '0');\n            out.push_back(static_cast<char>(value));\n            // Consume the three digits.\n            i += 3;\n        } else {\n            out.push_back(input[i]);\n        }\n    }\n    return out;\n}\n\nnamespace Mem {\n\tbool has_swap{};\n\tvector<string> fstab;\n\tfs::file_time_type fstab_time;\n\tint disk_ios{};\n\tvector<string> last_found;\n\n\t//?* Find the filepath to the specified ZFS object's stat file\n\tfs::path get_zfs_stat_file(const string& device_name, size_t dataset_name_start, bool zfs_hide_datasets);\n\n\t//?* Collect total ZFS pool io stats\n\tbool zfs_collect_pool_total_stats(struct disk_info &disk);\n\n\tmem_info current_mem {};\n\n\tuint64_t get_totalMem() {\n\t\tifstream meminfo(Shared::procPath / \"meminfo\");\n\t\tint64_t totalMem = 0;\n\t\tif (meminfo.good()) {\n\t\t\tmeminfo.ignore(SSmax, ':');\n\t\t\tmeminfo >> totalMem;\n\t\t\ttotalMem <<= 10;\n\t\t}\n\t\tif (not meminfo.good() or totalMem == 0)\n\t\t\tthrow std::runtime_error(\"Could not get total memory size from /proc/meminfo\");\n\n\t\treturn totalMem;\n\t}\n\n\tauto collect(bool no_update) -> mem_info& {\n\t\tif (Runner::stopping or (no_update and not current_mem.percent.at(\"used\").empty())) return current_mem;\n\t\tauto show_swap = Config::getB(\"show_swap\");\n\t\tauto swap_disk = Config::getB(\"swap_disk\");\n\t\tauto show_disks = Config::getB(\"show_disks\");\n\t\tauto zfs_arc_cached = Config::getB(\"zfs_arc_cached\");\n\t\tauto totalMem = get_totalMem();\n\t\tauto& mem = current_mem;\n\n\t\tmem.stats.at(\"swap_total\") = 0;\n\n\t\t//? Read ZFS ARC info from /proc/spl/kstat/zfs/arcstats\n\t\tuint64_t arc_size = 0, arc_min_size = 0;\n\t\tif (zfs_arc_cached) {\n\t\t\tifstream arcstats(Shared::procPath / \"spl/kstat/zfs/arcstats\");\n\t\t\tif (arcstats.good()) {\n\t\t\t\tfor (string label; arcstats >> label;) {\n\t\t\t\t\tif (label == \"c_min\") {\n\t\t\t\t\t\tarcstats >> arc_min_size >> arc_min_size; // double read skips type column\n\t\t\t\t\t}\n\t\t\t\t\telse if (label == \"size\") {\n\t\t\t\t\t\tarcstats >> arc_size >> arc_size;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tarcstats.close();\n\t\t}\n\n\t\t//? Read memory info from /proc/meminfo\n\t\tifstream meminfo(Shared::procPath / \"meminfo\");\n\t\tif (meminfo.good()) {\n\t\t\tbool got_avail = false;\n\t\t\tfor (string label; meminfo.peek() != 'D' and meminfo >> label;) {\n\t\t\t\tif (label == \"MemFree:\") {\n\t\t\t\t\tmeminfo >> mem.stats.at(\"free\");\n\t\t\t\t\tmem.stats.at(\"free\") <<= 10;\n\t\t\t\t}\n\t\t\t\telse if (label == \"MemAvailable:\") {\n\t\t\t\t\tmeminfo >> mem.stats.at(\"available\");\n\t\t\t\t\tmem.stats.at(\"available\") <<= 10;\n\t\t\t\t\tgot_avail = true;\n\t\t\t\t}\n\t\t\t\telse if (label == \"Cached:\") {\n\t\t\t\t\tmeminfo >> mem.stats.at(\"cached\");\n\t\t\t\t\tmem.stats.at(\"cached\") <<= 10;\n\t\t\t\t\tif (not show_swap and not swap_disk) break;\n\t\t\t\t}\n\t\t\t\telse if (label == \"SwapTotal:\") {\n\t\t\t\t\tmeminfo >> mem.stats.at(\"swap_total\");\n\t\t\t\t\tmem.stats.at(\"swap_total\") <<= 10;\n\t\t\t\t}\n\t\t\t\telse if (label == \"SwapFree:\") {\n\t\t\t\t\tmeminfo >> mem.stats.at(\"swap_free\");\n\t\t\t\t\tmem.stats.at(\"swap_free\") <<= 10;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tmeminfo.ignore(SSmax, '\\n');\n\t\t\t}\n\t\t\tif (not got_avail) mem.stats.at(\"available\") = mem.stats.at(\"free\") + mem.stats.at(\"cached\");\n\t\t\tif (zfs_arc_cached) {\n\t\t\t\tmem.stats.at(\"cached\") += arc_size;\n\t\t\t\t// The ARC will not shrink below arc_min_size, so that memory is not available\n\t\t\t\tif (arc_size > arc_min_size)\n\t\t\t\t\tmem.stats.at(\"available\") += arc_size - arc_min_size;\n\t\t\t}\n\t\t\tmem.stats.at(\"used\") = totalMem - (mem.stats.at(\"available\") <= totalMem ? mem.stats.at(\"available\") : mem.stats.at(\"free\"));\n\n\t\t\tif (mem.stats.at(\"swap_total\") > 0) mem.stats.at(\"swap_used\") = mem.stats.at(\"swap_total\") - mem.stats.at(\"swap_free\");\n\t\t}\n\t\telse\n\t\t\tthrow std::runtime_error(\"Failed to read /proc/meminfo\");\n\n\t\tmeminfo.close();\n\n\t\t//? Calculate percentages\n\t\tfor (const auto& name : mem_names) {\n\t\t\tmem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / totalMem));\n\t\t\twhile (cmp_greater(mem.percent.at(name).size(), width * 2)) mem.percent.at(name).pop_front();\n\t\t}\n\n\t\tif (show_swap and mem.stats.at(\"swap_total\") > 0) {\n\t\t\tfor (const auto& name : swap_names) {\n\t\t\t\tmem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / mem.stats.at(\"swap_total\")));\n\t\t\t\twhile (cmp_greater(mem.percent.at(name).size(), width * 2)) mem.percent.at(name).pop_front();\n\t\t\t}\n\t\t\thas_swap = true;\n\t\t}\n\t\telse\n\t\t\thas_swap = false;\n\n\t\t//? Get disks stats\n\t\tif (show_disks) {\n\t\t\tstatic vector<string> ignore_list;\n\t\t\tdouble uptime = system_uptime();\n\t\t\tauto free_priv = Config::getB(\"disk_free_priv\");\n\t\t\ttry {\n\t\t\t\tauto& disks_filter = Config::getS(\"disks_filter\");\n\t\t\t\tbool filter_exclude = false;\n\t\t\t\tauto use_fstab = Config::getB(\"use_fstab\");\n\t\t\t\tauto only_physical = Config::getB(\"only_physical\");\n\t\t\t\tauto zfs_hide_datasets = Config::getB(\"zfs_hide_datasets\");\n\t\t\t\tauto& disks = mem.disks;\n\t\t\t\tstatic std::unordered_map<string, future<pair<disk_info, int>>> disks_stats_promises;\n\t\t\t\tifstream diskread;\n\n\t\t\t\tvector<string> filter;\n\t\t\t\tif (not disks_filter.empty()) {\n\t\t\t\t\tfilter = ssplit(disks_filter);\n\t\t\t\t\tif (filter.at(0).starts_with(\"exclude=\")) {\n\t\t\t\t\t\tfilter_exclude = true;\n\t\t\t\t\t\tfilter.at(0) = filter.at(0).substr(8);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//? Get list of \"real\" filesystems from /proc/filesystems\n\t\t\t\tvector<string> fstypes;\n\t\t\t\tif (only_physical and not use_fstab) {\n\t\t\t\t\tfstypes = {\"zfs\", \"wslfs\", \"drvfs\"};\n\t\t\t\t\tdiskread.open(Shared::procPath / \"filesystems\");\n\t\t\t\t\tif (diskread.good()) {\n\t\t\t\t\t\tfor (string fstype; diskread >> fstype;) {\n\t\t\t\t\t\t\tif (not is_in(fstype, \"nodev\", \"squashfs\", \"nullfs\"))\n\t\t\t\t\t\t\t\tfstypes.push_back(fstype);\n\t\t\t\t\t\t\tdiskread.ignore(SSmax, '\\n');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow std::runtime_error(\"Failed to read /proc/filesystems\");\n\t\t\t\t\tdiskread.close();\n\t\t\t\t}\n\n\t\t\t\t//? Get disk list to use from fstab if enabled\n\t\t\t\tif (use_fstab and fs::last_write_time(\"/etc/fstab\") != fstab_time) {\n\t\t\t\t\tfstab.clear();\n\t\t\t\t\tfstab_time = fs::last_write_time(\"/etc/fstab\");\n\t\t\t\t\tdiskread.open(\"/etc/fstab\");\n\t\t\t\t\tif (diskread.good()) {\n\t\t\t\t\t\tfor (string instr; diskread >> instr;) {\n\t\t\t\t\t\t\tif (not instr.starts_with('#')) {\n\t\t\t\t\t\t\t\tdiskread >> instr;\n\t\t\t\t\t\t\t\t#ifdef SNAPPED\n\t\t\t\t\t\t\t\t\tif (instr == \"/\") fstab.push_back(\"/mnt\");\n\t\t\t\t\t\t\t\t\telse if (not is_in(instr, \"none\", \"swap\")) fstab.push_back(instr);\n\t\t\t\t\t\t\t\t#else\n\t\t\t\t\t\t\t\t\tif (not is_in(instr, \"none\", \"swap\")) fstab.push_back(instr);\n\t\t\t\t\t\t\t\t#endif\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdiskread.ignore(SSmax, '\\n');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tthrow std::runtime_error(\"Failed to read /etc/fstab\");\n\t\t\t\t\tdiskread.close();\n\t\t\t\t}\n\n\t\t\t\t//? Get mounts from /etc/mtab or /proc/self/mounts\n\t\t\t\tdiskread.open((fs::exists(\"/etc/mtab\") ? fs::path(\"/etc/mtab\") : Shared::procPath / \"self/mounts\"));\n\t\t\t\tif (diskread.good()) {\n\t\t\t\t\tvector<string> found;\n\t\t\t\t\tfound.reserve(last_found.size());\n\t\t\t\t\tstring dev, mountpoint, fstype;\n\t\t\t\t\twhile (not diskread.eof()) {\n\t\t\t\t\t\tstd::error_code ec;\n\t\t\t\t\t\tdiskread >> dev >> mountpoint >> fstype;\n\t\t\t\t\t\tdiskread.ignore(SSmax, '\\n');\n\n\t\t\t\t\t\t// A mountpoint can ascii escape codes, which will not work with `statvfs`.\n\t\t\t\t\t\tmountpoint = convert_ascii_escapes(mountpoint);\n\n\t\t\t\t\t\tif (v_contains(ignore_list, mountpoint) or v_contains(found, mountpoint)) continue;\n\n\t\t\t\t\t\t//? Match filter if not empty\n\t\t\t\t\t\tif (not filter.empty()) {\n\t\t\t\t\t\t\tbool match = v_contains(filter, mountpoint);\n\t\t\t\t\t\t\tif ((filter_exclude and match) or (not filter_exclude and not match))\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t//? Skip ZFS datasets if zfs_hide_datasets option is enabled\n\t\t\t\t\t\tsize_t zfs_dataset_name_start = 0;\n\t\t\t\t\t\tif (fstype == \"zfs\" && (zfs_dataset_name_start = dev.find('/')) != std::string::npos && zfs_hide_datasets) continue;\n\n\t\t\t\t\t\tif ((not use_fstab and not only_physical)\n\t\t\t\t\t\tor (use_fstab and v_contains(fstab, mountpoint))\n\t\t\t\t\t\tor (not use_fstab and only_physical and v_contains(fstypes, fstype))) {\n\t\t\t\t\t\t\tfound.push_back(mountpoint);\n\t\t\t\t\t\t\tif (not v_contains(last_found, mountpoint)) redraw = true;\n\n\t\t\t\t\t\t\t//? Save mountpoint, name, fstype, dev path and path to /sys/block stat file\n\t\t\t\t\t\t\tif (not disks.contains(mountpoint)) {\n\t\t\t\t\t\t\t\tdisks[mountpoint] = disk_info{fs::canonical(dev, ec), fs::path(mountpoint).filename(), fstype};\n\t\t\t\t\t\t\t\tif (disks.at(mountpoint).dev.empty()) disks.at(mountpoint).dev = dev;\n\t\t\t\t\t\t\t\t#ifdef SNAPPED\n\t\t\t\t\t\t\t\t\tif (mountpoint == \"/mnt\") disks.at(mountpoint).name = \"root\";\n\t\t\t\t\t\t\t\t#endif\n\t\t\t\t\t\t\t\tif (disks.at(mountpoint).name.empty()) disks.at(mountpoint).name = (mountpoint == \"/\" ? \"root\" : mountpoint);\n\t\t\t\t\t\t\t\tstring devname = disks.at(mountpoint).dev.filename();\n\t\t\t\t\t\t\t\tint c = 0;\n\t\t\t\t\t\t\t\twhile (devname.size() >= 2) {\n\t\t\t\t\t\t\t\t\tconst auto stat = fmt::format(\"/sys/block/{}/stat\", devname);\n\t\t\t\t\t\t\t\t\tif (fs::exists(stat, ec) and access(stat.c_str(), R_OK) == 0) {\n\t\t\t\t\t\t\t\t\t\tconst auto mount_stat = fmt::format(\"/sys/block/{}/{}/stat\", devname, disks.at(mountpoint).dev.filename());\n\t\t\t\t\t\t\t\t\t\tif (c > 0 and fs::exists(mount_stat, ec))\n\t\t\t\t\t\t\t\t\t\t\tdisks.at(mountpoint).stat = std::move(mount_stat);\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\tdisks.at(mountpoint).stat = std::move(stat);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t//? Set ZFS stat filepath\n\t\t\t\t\t\t\t\t\t} else if (fstype == \"zfs\") {\n\t\t\t\t\t\t\t\t\t\tdisks.at(mountpoint).stat = get_zfs_stat_file(dev, zfs_dataset_name_start, zfs_hide_datasets);\n\t\t\t\t\t\t\t\t\t\tif (disks.at(mountpoint).stat.empty()) {\n\t\t\t\t\t\t\t\t\t\t\tLogger::debug(\"Failed to get ZFS stat file for device {}\", dev);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tdevname.resize(devname.size() - 1);\n\t\t\t\t\t\t\t\t\tc++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t//? If zfs_hide_datasets option was switched, refresh stat filepath\n\t\t\t\t\t\t\tif (fstype == \"zfs\" && ((zfs_hide_datasets && !is_directory(disks.at(mountpoint).stat))\n\t\t\t\t\t\t\t\t|| (!zfs_hide_datasets && is_directory(disks.at(mountpoint).stat)))) {\n\t\t\t\t\t\t\t\tdisks.at(mountpoint).stat = get_zfs_stat_file(dev, zfs_dataset_name_start, zfs_hide_datasets);\n\t\t\t\t\t\t\t\tif (disks.at(mountpoint).stat.empty()) {\n\t\t\t\t\t\t\t\t\tLogger::debug(\"Failed to get ZFS stat file for device {}\", dev);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\t//? Remove disks no longer mounted or filtered out\n\t\t\t\t\tif (swap_disk and has_swap) found.push_back(\"swap\");\n\t\t\t\t\tfor (auto it = disks.begin(); it != disks.end();) {\n\t\t\t\t\t\tif (not v_contains(found, it->first))\n\t\t\t\t\t\t\tit = disks.erase(it);\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tit++;\n\t\t\t\t\t}\n\t\t\t\t\tif (found.size() != last_found.size()) redraw = true;\n\t\t\t\t\tlast_found = std::move(found);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\tthrow std::runtime_error(\"Failed to get mounts from /etc/mtab and /proc/self/mounts\");\n\t\t\t\tdiskread.close();\n\n\t\t\t\t//? Get disk/partition stats\n\t\t\t\tfor (auto it = disks.begin(); it != disks.end(); ) {\n\t\t\t\t\tauto &[mountpoint, disk] = *it;\n\t\t\t\t\tif (v_contains(ignore_list, mountpoint) or disk.name == \"swap\") {\n\t\t\t\t\t\tit = disks.erase(it);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif(auto promises_it = disks_stats_promises.find(mountpoint); promises_it != disks_stats_promises.end()){\n\t\t\t\t\t\tauto& promise = promises_it->second;\n\t\t\t\t\t\tif(promise.valid() &&\n\t\t\t\t\t\t   promise.wait_for(0s) == std::future_status::timeout) {\n\t\t\t\t\t\t\t++it;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tauto promise_res = promises_it->second.get();\n\t\t\t\t\t\tif(promise_res.second != -1){\n\t\t\t\t\t\t\tignore_list.push_back(mountpoint);\n\t\t\t\t\t\t\tLogger::warning(\"Failed to get disk/partition stats for mount \\\"{}\\\" with statvfs error code: {}. Ignoring...\", mountpoint, promise_res.second);\n\t\t\t\t\t\t\tit = disks.erase(it);\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tauto &updated_stats = promise_res.first;\n\t\t\t\t\t\tdisk.total = updated_stats.total;\n\t\t\t\t\t\tdisk.free = updated_stats.free;\n\t\t\t\t\t\tdisk.used = updated_stats.used;\n\t\t\t\t\t\tdisk.used_percent = updated_stats.used_percent;\n\t\t\t\t\t\tdisk.free_percent = updated_stats.free_percent;\n\t\t\t\t\t}\n\t\t\t\t\tdisks_stats_promises[mountpoint] = async(std::launch::async, [mountpoint, free_priv]() -> pair<disk_info, int> {\n\t\t\t\t\t\tstruct statvfs vfs;\n\t\t\t\t\t\tdisk_info disk;\n\t\t\t\t\t\tif (statvfs(mountpoint.c_str(), &vfs) < 0) {\n\t\t\t\t\t\t\treturn pair{disk, errno};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdisk.total = vfs.f_blocks * vfs.f_frsize;\n\t\t\t\t\t\tdisk.free = (free_priv ? vfs.f_bfree : vfs.f_bavail) * vfs.f_frsize;\n\t\t\t\t\t\tdisk.used = disk.total - disk.free;\n\t\t\t\t\t\tif (disk.total != 0) {\n\t\t\t\t\t\t\tdisk.used_percent = round((double)disk.used * 100 / disk.total);\n\t\t\t\t\t\t\tdisk.free_percent = 100 - disk.used_percent;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tdisk.used_percent = 0;\n\t\t\t\t\t\t\tdisk.free_percent = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn pair{disk, -1};\n\t\t\t\t\t});\n\t\t\t\t\t++it;\n\t\t\t\t}\n\n\t\t\t\t//? Setup disks order in UI and add swap if enabled\n\t\t\t\tmem.disks_order.clear();\n\t\t\t\t#ifdef SNAPPED\n\t\t\t\t\tif (disks.contains(\"/mnt\")) mem.disks_order.push_back(\"/mnt\");\n\t\t\t\t#else\n\t\t\t\t\tif (disks.contains(\"/\")) mem.disks_order.push_back(\"/\");\n\t\t\t\t#endif\n\t\t\t\tif (swap_disk and has_swap) {\n\t\t\t\t\tmem.disks_order.push_back(\"swap\");\n\t\t\t\t\tif (not disks.contains(\"swap\")) disks[\"swap\"] = {\"\", \"swap\", \"swap\"};\n\t\t\t\t\tdisks.at(\"swap\").total = mem.stats.at(\"swap_total\");\n\t\t\t\t\tdisks.at(\"swap\").used = mem.stats.at(\"swap_used\");\n\t\t\t\t\tdisks.at(\"swap\").free = mem.stats.at(\"swap_free\");\n\t\t\t\t\tdisks.at(\"swap\").used_percent = mem.percent.at(\"swap_used\").back();\n\t\t\t\t\tdisks.at(\"swap\").free_percent = mem.percent.at(\"swap_free\").back();\n\t\t\t\t}\n\t\t\t\tfor (const auto& name : last_found)\n\t\t\t\t\t#ifdef SNAPPED\n\t\t\t\t\t\tif (not is_in(name, \"/mnt\", \"swap\")) mem.disks_order.push_back(name);\n\t\t\t\t\t#else\n\t\t\t\t\t\tif (not is_in(name, \"/\", \"swap\")) mem.disks_order.push_back(name);\n\t\t\t\t\t#endif\n\n\t\t\t\t//? Get disks IO\n\t\t\t\tint64_t sectors_read, sectors_write, io_ticks, io_ticks_temp;\n\t\t\t\tdisk_ios = 0;\n\t\t\t\tfor (auto& [ignored, disk] : disks) {\n\t\t\t\t\tif (disk.stat.empty() or access(disk.stat.c_str(), R_OK) != 0) continue;\n\t\t\t\t\tif (disk.fstype == \"zfs\" && zfs_hide_datasets && zfs_collect_pool_total_stats(disk)) {\n\t\t\t\t\t\tdisk_ios++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tdiskread.open(disk.stat);\n\t\t\t\t\tif (diskread.good()) {\n\t\t\t\t\t\tdisk_ios++;\n\t\t\t\t\t\t//? ZFS Pool Support\n\t\t\t\t\t\tif (disk.fstype == \"zfs\") {\n\t\t\t\t\t\t\t// skip first three lines\n\t\t\t\t\t\t\tfor (int i = 0; i < 3; i++) diskread.ignore(numeric_limits<streamsize>::max(), '\\n');\n\t\t\t\t\t\t\t// skip characters until '4' is reached, indicating data type 4, next value will be out target\n\t\t\t\t\t\t\tdiskread.ignore(numeric_limits<streamsize>::max(), '4');\n\t\t\t\t\t\t\tdiskread >> io_ticks;\n\n\t\t\t\t\t\t\t// skip characters until '4' is reached, indicating data type 4, next value will be out target\n\t\t\t\t\t\t\tdiskread.ignore(numeric_limits<streamsize>::max(), '4');\n\t\t\t\t\t\t\tdiskread >> sectors_write; // nbytes written\n\t\t\t\t\t\t\tif (disk.io_write.empty())\n\t\t\t\t\t\t\t\tdisk.io_write.push_back(0);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tdisk.io_write.push_back(max((int64_t)0, (sectors_write - disk.old_io.at(1))));\n\t\t\t\t\t\t\tdisk.old_io.at(1) = sectors_write;\n\t\t\t\t\t\t\twhile (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front();\n\n\t\t\t\t\t\t\t// skip characters until '4' is reached, indicating data type 4, next value will be out target\n\t\t\t\t\t\t\tdiskread.ignore(numeric_limits<streamsize>::max(), '4');\n\t\t\t\t\t\t\tdiskread >> io_ticks_temp;\n\t\t\t\t\t\t\tio_ticks += io_ticks_temp;\n\n\t\t\t\t\t\t\t// skip characters until '4' is reached, indicating data type 4, next value will be out target\n\t\t\t\t\t\t\tdiskread.ignore(numeric_limits<streamsize>::max(), '4');\n\t\t\t\t\t\t\tdiskread >> sectors_read; // nbytes read\n\t\t\t\t\t\t\tif (disk.io_read.empty())\n\t\t\t\t\t\t\t\tdisk.io_read.push_back(0);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tdisk.io_read.push_back(max((int64_t)0, (sectors_read - disk.old_io.at(0))));\n\t\t\t\t\t\t\tdisk.old_io.at(0) = sectors_read;\n\t\t\t\t\t\t\twhile (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front();\n\n\t\t\t\t\t\t\tif (disk.io_activity.empty())\n\t\t\t\t\t\t\t\tdisk.io_activity.push_back(0);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tdisk.io_activity.push_back(max((int64_t)0, (io_ticks - disk.old_io.at(2))));\n\t\t\t\t\t\t\tdisk.old_io.at(2) = io_ticks;\n\t\t\t\t\t\t\twhile (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfor (int i = 0; i < 2; i++) { diskread >> std::ws; diskread.ignore(SSmax, ' '); }\n\t\t\t\t\t\t\tdiskread >> sectors_read;\n\t\t\t\t\t\t\tif (disk.io_read.empty())\n\t\t\t\t\t\t\t\tdisk.io_read.push_back(0);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tdisk.io_read.push_back(max((int64_t)0, (sectors_read - disk.old_io.at(0)) * 512));\n\t\t\t\t\t\t\tdisk.old_io.at(0) = sectors_read;\n\t\t\t\t\t\t\twhile (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front();\n\n\t\t\t\t\t\t\tfor (int i = 0; i < 3; i++) { diskread >> std::ws; diskread.ignore(SSmax, ' '); }\n\t\t\t\t\t\t\tdiskread >> sectors_write;\n\t\t\t\t\t\t\tif (disk.io_write.empty())\n\t\t\t\t\t\t\t\tdisk.io_write.push_back(0);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tdisk.io_write.push_back(max((int64_t)0, (sectors_write - disk.old_io.at(1)) * 512));\n\t\t\t\t\t\t\tdisk.old_io.at(1) = sectors_write;\n\t\t\t\t\t\t\twhile (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front();\n\n\t\t\t\t\t\t\tfor (int i = 0; i < 2; i++) { diskread >> std::ws; diskread.ignore(SSmax, ' '); }\n\t\t\t\t\t\t\tdiskread >> io_ticks;\n\t\t\t\t\t\t\tif (uptime == old_uptime || disk.io_activity.empty())\n\t\t\t\t\t\t\t\tdisk.io_activity.push_back(0);\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tdisk.io_activity.push_back(clamp((long)round((double)(io_ticks - disk.old_io.at(2)) / (uptime - old_uptime) / 10), 0l, 100l));\n\t\t\t\t\t\t\tdisk.old_io.at(2) = io_ticks;\n\t\t\t\t\t\t\twhile (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tLogger::debug(\"Error in Mem::collect() : when opening {}\", disk.stat);\n\t\t\t\t\t}\n\t\t\t\t\tdiskread.close();\n\t\t\t\t}\n\t\t\t\told_uptime = uptime;\n\t\t\t}\n\t\t\tcatch (const std::exception& e) {\n\t\t\t\tLogger::warning(\"Error in Mem::collect() : {}\", e.what());\n\t\t\t}\n\t\t}\n\n\t\treturn mem;\n\t}\n\n\tfs::path get_zfs_stat_file(const string& device_name, size_t dataset_name_start, bool zfs_hide_datasets) {\n\t\tfs::path zfs_pool_stat_path;\n\t\tif (zfs_hide_datasets) {\n\t\t\tzfs_pool_stat_path = Shared::procPath / \"spl/kstat/zfs\" / device_name;\n\t\t\tif (access(zfs_pool_stat_path.c_str(), R_OK) == 0) {\n\t\t\t\treturn zfs_pool_stat_path;\n\t\t\t} else {\n\t\t\t\tLogger::debug(\"Can't access folder: {}\", zfs_pool_stat_path);\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t}\n\n\t\tifstream filestream;\n\t\tstring filename;\n\t\tstring name_compare;\n\n\t\tif (dataset_name_start != std::string::npos) { // device is a dataset\n\t\t\tzfs_pool_stat_path = Shared::procPath / \"spl/kstat/zfs\" / device_name.substr(0, dataset_name_start);\n\t\t} else { // device is a pool\n\t\t\tzfs_pool_stat_path = Shared::procPath / \"spl/kstat/zfs\" / device_name;\n\t\t}\n\n\t\t// looking through all files that start with 'objset' to find the one containing `device_name` object stats\n\t\ttry {\n\t\t\tfor (const auto& file: fs::directory_iterator(zfs_pool_stat_path)) {\n\t\t\t\tfilename = file.path().filename();\n\t\t\t\tif (filename.starts_with(\"objset\")) {\n\t\t\t\t\tfilestream.open(file.path());\n\t\t\t\t\tif (filestream.good()) {\n\t\t\t\t\t\t// skip first two lines\n\t\t\t\t\t\tfor (int i = 0; i < 2; i++) filestream.ignore(numeric_limits<streamsize>::max(), '\\n');\n\t\t\t\t\t\t// skip characters until '7' is reached, indicating data type 7, next value will be object name\n\t\t\t\t\t\tfilestream.ignore(numeric_limits<streamsize>::max(), '7');\n\t\t\t\t\t\tfilestream >> name_compare;\n\t\t\t\t\t\tif (name_compare == device_name) {\n\t\t\t\t\t\t\tfilestream.close();\n\t\t\t\t\t\t\tif (access(file.path().c_str(), R_OK) == 0) {\n\t\t\t\t\t\t\t\treturn file.path();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tLogger::debug(\"Can't access file: {}\", file.path());\n\t\t\t\t\t\t\t\treturn \"\";\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfilestream.close();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (fs::filesystem_error& e) {}\n\n\t\tLogger::debug(\"Could not read directory: {}\", zfs_pool_stat_path);\n\t\treturn \"\";\n\t}\n\n\tbool zfs_collect_pool_total_stats(struct disk_info &disk) {\n\t\tifstream diskread;\n\n\t\tint64_t bytes_read;\n\t\tint64_t bytes_write;\n\t\tint64_t io_ticks;\n\t\tint64_t bytes_read_total{};\n\t\tint64_t bytes_write_total{};\n\t\tint64_t io_ticks_total{};\n\t\tint64_t objects_read{};\n\n\t\t// looking through all files that start with 'objset'\n\t\tfor (const auto& file: fs::directory_iterator(disk.stat)) {\n\t\t\tif ((file.path().filename()).string().starts_with(\"objset\")) {\n\t\t\t\tdiskread.open(file.path());\n\t\t\t\tif (diskread.good()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\t// skip first three lines\n\t\t\t\t\t\tfor (int i = 0; i < 3; i++) diskread.ignore(numeric_limits<streamsize>::max(), '\\n');\n\t\t\t\t\t\t// skip characters until '4' is reached, indicating data type 4, next value will be out target\n\t\t\t\t\t\tdiskread.ignore(numeric_limits<streamsize>::max(), '4');\n\t\t\t\t\t\tdiskread >> io_ticks;\n\t\t\t\t\t\tio_ticks_total += io_ticks;\n\n\t\t\t\t\t\t// skip characters until '4' is reached, indicating data type 4, next value will be out target\n\t\t\t\t\t\tdiskread.ignore(numeric_limits<streamsize>::max(), '4');\n\t\t\t\t\t\tdiskread >> bytes_write;\n\t\t\t\t\t\tbytes_write_total += bytes_write;\n\n\t\t\t\t\t\t// skip characters until '4' is reached, indicating data type 4, next value will be out target\n\t\t\t\t\t\tdiskread.ignore(numeric_limits<streamsize>::max(), '4');\n\t\t\t\t\t\tdiskread >> io_ticks;\n\t\t\t\t\t\tio_ticks_total += io_ticks;\n\n\t\t\t\t\t\t// skip characters until '4' is reached, indicating data type 4, next value will be out target\n\t\t\t\t\t\tdiskread.ignore(numeric_limits<streamsize>::max(), '4');\n\t\t\t\t\t\tdiskread >> bytes_read;\n\t\t\t\t\t\tbytes_read_total += bytes_read;\n\t\t\t\t\t} catch (const std::exception& e) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// increment read objects counter if no errors were encountered\n\t\t\t\t\tobjects_read++;\n\t\t\t\t} else {\n\t\t\t\t\tLogger::debug(\"Could not read file: {}\", file.path());\n\t\t\t\t}\n\t\t\t\tdiskread.close();\n\t\t\t}\n\t\t}\n\n\t\t// if for some reason no objects were read\n\t\tif (objects_read == 0) return false;\n\n\t\tif (disk.io_write.empty())\n\t\t\tdisk.io_write.push_back(0);\n\t\telse\n\t\t\tdisk.io_write.push_back(max((int64_t)0, (bytes_write_total - disk.old_io.at(1))));\n\t\tdisk.old_io.at(1) = bytes_write_total;\n\t\twhile (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front();\n\n\t\tif (disk.io_read.empty())\n\t\t\tdisk.io_read.push_back(0);\n\t\telse\n\t\t\tdisk.io_read.push_back(max((int64_t)0, (bytes_read_total - disk.old_io.at(0))));\n\t\tdisk.old_io.at(0) = bytes_read_total;\n\t\twhile (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front();\n\n\t\tif (disk.io_activity.empty())\n\t\t\tdisk.io_activity.push_back(0);\n\t\telse\n\t\t\tdisk.io_activity.push_back(max((int64_t)0, (io_ticks_total - disk.old_io.at(2))));\n\t\tdisk.old_io.at(2) = io_ticks_total;\n\t\twhile (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();\n\n\t\treturn true;\n\t}\n\n}\n\nnamespace Net {\n\tstd::unordered_map<string, net_info> current_net;\n\tnet_info empty_net = {};\n\tvector<string> interfaces;\n\tstring selected_iface;\n\tint errors{};\n\tstd::unordered_map<string, uint64_t> graph_max = { {\"download\", {}}, {\"upload\", {}} };\n\tstd::unordered_map<string, array<int, 2>> max_count = { {\"download\", {}}, {\"upload\", {}} };\n\tbool rescale{true};\n\tuint64_t timestamp{};\n\n\tauto collect(bool no_update) -> net_info& {\n\t\tif (Runner::stopping) return empty_net;\n\t\tauto& net = current_net;\n\t\tauto& config_iface = Config::getS(\"net_iface\");\n\t\tauto net_sync = Config::getB(\"net_sync\");\n\t\tauto net_auto = Config::getB(\"net_auto\");\n\t\tauto new_timestamp = time_ms();\n\n\t\tif (not no_update and errors < 3) {\n\t\t\t//? Get interface list using getifaddrs() wrapper\n\t\t\tIfAddrsPtr if_addrs {};\n\t\t\tif (if_addrs.get_status() != 0) {\n\t\t\t\terrors++;\n\t\t\t\tLogger::error(\"Net::collect() -> getifaddrs() failed with id {}\", if_addrs.get_status());\n\t\t\t\tredraw = true;\n\t\t\t\treturn empty_net;\n\t\t\t}\n\t\t\tint family = 0;\n\t\t\tstatic_assert(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN); // 46 >= 16, compile-time assurance.\n\t\t\tenum { IPBUFFER_MAXSIZE = INET6_ADDRSTRLEN }; // manually using the known biggest value, guarded by the above static_assert\n\t\t\tchar ip[IPBUFFER_MAXSIZE];\n\t\t\tinterfaces.clear();\n\t\t\tstring ipv4, ipv6;\n\n\t\t\t//? Iteration over all items in getifaddrs() list\n\t\t\tfor (auto* ifa = if_addrs.get(); ifa != nullptr; ifa = ifa->ifa_next) {\n\t\t\t\tif (ifa->ifa_addr == nullptr) continue;\n\t\t\t\tfamily = ifa->ifa_addr->sa_family;\n\t\t\t\tconst auto& iface = ifa->ifa_name;\n\n\t\t\t\t//? Update available interfaces vector and get status of interface\n\t\t\t\tif (not v_contains(interfaces, iface)) {\n\t\t\t\t\tinterfaces.push_back(iface);\n\t\t\t\t\tnet[iface].connected = (ifa->ifa_flags & IFF_RUNNING);\n\n\t\t\t\t\t// An interface can have more than one IP of the same family associated with it,\n\t\t\t\t\t// but we pick only the first one to show in the NET box.\n\t\t\t\t\t// Note: Interfaces without any IPv4 and IPv6 set are still valid and monitorable!\n\t\t\t\t\tnet[iface].ipv4.clear();\n\t\t\t\t\tnet[iface].ipv6.clear();\n\t\t\t\t}\n\n\n\t\t\t\t//? Get IPv4 address\n\t\t\t\tif (family == AF_INET) {\n\t\t\t\t\tif (net[iface].ipv4.empty()) {\n\t\t\t\t\t\tif (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr)->sin_addr), ip, IPBUFFER_MAXSIZE)) {\n\t\t\t\t\t\t\tnet[iface].ipv4 = ip;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tint errsv = errno;\n\t\t\t\t\t\t\tLogger::error(\"Net::collect() -> Failed to convert IPv4 to string for iface {}, errno: {}\", iface, strerror(errsv));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? Get IPv6 address\n\t\t\t\telse if (family == AF_INET6) {\n\t\t\t\t\tif (net[iface].ipv6.empty()) {\n\t\t\t\t\t\tif (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr)->sin6_addr), ip, IPBUFFER_MAXSIZE)) {\n\t\t\t\t\t\t\tnet[iface].ipv6 = ip;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tint errsv = errno;\n\t\t\t\t\t\t\tLogger::error(\"Net::collect() -> Failed to convert IPv6 to string for iface {}, errno: {}\", iface, strerror(errsv));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} //else, ignoring family==AF_PACKET (see man 3 getifaddrs) which is the first one in the `for` loop.\n\t\t\t}\n\n\t\t\t//? Get total received and transmitted bytes + device address if no ip was found\n\t\t\tfor (const auto& iface : interfaces) {\n\t\t\t\tauto& netif = net.at(iface);\n\t\t\t\tif (netif.ipv4.empty() and netif.ipv6.empty())\n\t\t\t\t\tnetif.ipv4 = readfile(\"/sys/class/net/\" + iface + \"/address\");\n\n\t\t\t\tfor (const string dir : {\"download\", \"upload\"}) {\n\t\t\t\t\tconst fs::path sys_file = \"/sys/class/net/\" + iface + \"/statistics/\" + (dir == \"download\" ? \"rx_bytes\" : \"tx_bytes\");\n\t\t\t\t\tauto& saved_stat = netif.stat.at(dir);\n\t\t\t\t\tauto& bandwidth = netif.bandwidth.at(dir);\n\n\t\t\t\t\tuint64_t val{};\n\t\t\t\t\ttry { val = stoull(readfile(sys_file, \"0\")); }\n\t\t\t\t\tcatch (const std::invalid_argument&) {}\n\t\t\t\t\tcatch (const std::out_of_range&) {}\n\n\t\t\t\t\t//? Update speed, total and top values\n\t\t\t\t\tif (val < saved_stat.last) {\n\t\t\t\t\t\tsaved_stat.rollover += saved_stat.last;\n\t\t\t\t\t\tsaved_stat.last = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (cmp_greater((unsigned long long)saved_stat.rollover + (unsigned long long)val, numeric_limits<uint64_t>::max())) {\n\t\t\t\t\t\tsaved_stat.rollover = 0;\n\t\t\t\t\t\tsaved_stat.last = 0;\n\t\t\t\t\t}\n\t\t\t\t\tsaved_stat.speed = round((double)(val - saved_stat.last) / ((double)(new_timestamp - timestamp) / 1000));\n\t\t\t\t\tif (saved_stat.speed > saved_stat.top) saved_stat.top = saved_stat.speed;\n\t\t\t\t\tif (saved_stat.offset > val + saved_stat.rollover) saved_stat.offset = 0;\n\t\t\t\t\tsaved_stat.total = (val + saved_stat.rollover) - saved_stat.offset;\n\t\t\t\t\tsaved_stat.last = val;\n\n\t\t\t\t\t//? Add values to graph\n\t\t\t\t\tbandwidth.push_back(saved_stat.speed);\n\t\t\t\t\twhile (cmp_greater(bandwidth.size(), width * 2)) bandwidth.pop_front();\n\n\t\t\t\t\t//? Set counters for auto scaling\n\t\t\t\t\tif (net_auto and selected_iface == iface) {\n\t\t\t\t\t\tif (net_sync and saved_stat.speed < netif.stat.at(dir == \"download\" ? \"upload\" : \"download\").speed) continue;\n\t\t\t\t\t\tif (saved_stat.speed > graph_max[dir]) {\n\t\t\t\t\t\t\t++max_count[dir][0];\n\t\t\t\t\t\t\tif (max_count[dir][1] > 0) --max_count[dir][1];\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (graph_max[dir] > 10 << 10 and saved_stat.speed < graph_max[dir] / 10) {\n\t\t\t\t\t\t\t++max_count[dir][1];\n\t\t\t\t\t\t\tif (max_count[dir][0] > 0) --max_count[dir][0];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Clean up net map if needed\n\t\t\tif (net.size() > interfaces.size()) {\n\t\t\t\tfor (auto it = net.begin(); it != net.end();) {\n\t\t\t\t\tif (not v_contains(interfaces, it->first))\n\t\t\t\t\t\tit = net.erase(it);\n\t\t\t\t\telse\n\t\t\t\t\t\tit++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttimestamp = new_timestamp;\n\t\t}\n\n\t\t//? Return empty net_info struct if no interfaces was found\n\t\tif (net.empty())\n\t\t\treturn empty_net;\n\n\t\t//? Find an interface to display if selected isn't set or valid\n\t\tif (selected_iface.empty() or not v_contains(interfaces, selected_iface)) {\n\t\t\tmax_count[\"download\"][0] = max_count[\"download\"][1] = max_count[\"upload\"][0] = max_count[\"upload\"][1] = 0;\n\t\t\tredraw = true;\n\t\t\tif (net_auto) rescale = true;\n\t\t\tif (not config_iface.empty() and v_contains(interfaces, config_iface)) selected_iface = config_iface;\n\t\t\telse {\n\t\t\t\t//? Sort interfaces by total upload + download bytes\n\t\t\t\tauto sorted_interfaces = interfaces;\n\t\t\t\trng::sort(sorted_interfaces, [&](const auto& a, const auto& b){\n\t\t\t\t\treturn \tcmp_greater(net.at(a).stat[\"download\"].total + net.at(a).stat[\"upload\"].total,\n\t\t\t\t\t\t\t\t\t\tnet.at(b).stat[\"download\"].total + net.at(b).stat[\"upload\"].total);\n\t\t\t\t});\n\t\t\t\tselected_iface.clear();\n\t\t\t\t//? Try to set to a connected interface\n\t\t\t\tfor (const auto& iface : sorted_interfaces) {\n\t\t\t\t\tif (net.at(iface).connected) {\n\t\t\t\t\t\tselected_iface = iface;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? If no interface is connected set to first available\n\t\t\t\tif (selected_iface.empty() and not sorted_interfaces.empty()) selected_iface = sorted_interfaces.at(0);\n\t\t\t\telse if (sorted_interfaces.empty()) return empty_net;\n\n\t\t\t}\n\t\t}\n\n\t\t//? Calculate max scale for graphs if needed\n\t\tif (net_auto) {\n\t\t\tbool sync = false;\n\t\t\tfor (const auto& dir: {\"download\", \"upload\"}) {\n\t\t\t\tfor (const auto& sel : {0, 1}) {\n\t\t\t\t\tif (rescale or max_count[dir][sel] >= 5) {\n\t\t\t\t\t\tconst long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5\n\t\t\t\t\t\t\t? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5\n\t\t\t\t\t\t\t: net[selected_iface].stat[dir].speed);\n\t\t\t\t\t\tgraph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10);\n\t\t\t\t\t\tmax_count[dir][0] = max_count[dir][1] = 0;\n\t\t\t\t\t\tredraw = true;\n\t\t\t\t\t\tif (net_sync) sync = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? Sync download/upload graphs if enabled\n\t\t\t\tif (sync) {\n\t\t\t\t\tconst auto other = (string(dir) == \"upload\" ? \"download\" : \"upload\");\n\t\t\t\t\tgraph_max[other] = graph_max[dir];\n\t\t\t\t\tmax_count[other][0] = max_count[other][1] = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trescale = false;\n\t\treturn net.at(selected_iface);\n\t}\n}\n\nnamespace Proc {\n\n\tvector<proc_info> current_procs;\n\tstd::unordered_map<string, string> uid_user;\n\tstring current_sort;\n\tstring current_filter;\n\tbool current_rev{};\n\tbool is_tree_mode;\n\n\tfs::file_time_type passwd_time;\n\n\tuint64_t cputimes;\n\tint collapse = -1, expand = -1, toggle_children = -1;\n\tuint64_t old_cputimes{};\n\tatomic<int> numpids{};\n\tint filter_found{};\n\n\tdetail_container detailed;\n\tconstexpr size_t KTHREADD = 2;\n\tstatic std::unordered_set<size_t> kernels_procs = {KTHREADD};\n\tstatic std::unordered_set<size_t> dead_procs;\n\n\t//* Get detailed info for selected process\n\tstatic void _collect_details(const size_t pid, const uint64_t uptime, vector<proc_info>& procs) {\n\t\tfs::path pid_path = Shared::procPath / std::to_string(pid);\n\n\t\tif (pid != detailed.last_pid) {\n\t\t\tdetailed = {};\n\t\t\tdetailed.last_pid = pid;\n\t\t\tdetailed.skip_smaps = not Config::getB(\"proc_info_smaps\");\n\t\t}\n\n\t\t//? Copy proc_info for process from proc vector\n\t\tauto p_info = rng::find(procs, pid, &proc_info::pid);\n\t\tdetailed.entry = *p_info;\n\n\t\t//? Update cpu percent deque for process cpu graph\n\t\tif (not Config::getB(\"proc_per_core\")) detailed.entry.cpu_p *= Shared::coreCount;\n\t\tdetailed.cpu_percent.push_back(clamp((long long)round(detailed.entry.cpu_p), 0ll, 100ll));\n\t\twhile (cmp_greater(detailed.cpu_percent.size(), width)) detailed.cpu_percent.pop_front();\n\n\t\t//? Process runtime\n\t\tif (detailed.entry.state != 'X') detailed.elapsed = sec_to_dhms(uptime - (detailed.entry.cpu_s / Shared::clkTck));\n\t\telse detailed.elapsed = sec_to_dhms(detailed.entry.death_time);\n\t\tif (detailed.elapsed.size() > 8) detailed.elapsed.resize(detailed.elapsed.size() - 3);\n\n\t\t//? Get parent process name\n\t\tif (detailed.parent.empty()) {\n\t\t\tauto p_entry = rng::find(procs, detailed.entry.ppid, &proc_info::pid);\n\t\t\tif (p_entry != procs.end()) detailed.parent = p_entry->name;\n\t\t}\n\n\t\t//? Expand process status from single char to explanative string\n\t\tdetailed.status = (proc_states.contains(detailed.entry.state)) ? proc_states.at(detailed.entry.state) : \"Unknown\";\n\n\t\tifstream d_read;\n\t\tstring short_str;\n\n\t\t//? Try to get RSS mem from proc/[pid]/smaps\n\t\tdetailed.memory.clear();\n\t\tif (not detailed.skip_smaps and fs::exists(pid_path / \"smaps\")) {\n\t\t\td_read.open(pid_path / \"smaps\");\n\t\t\tuint64_t rss = 0;\n\t\t\ttry {\n\t\t\t\twhile (d_read.good()) {\n\t\t\t\t\td_read.ignore(SSmax, 'R');\n\t\t\t\t\tif (d_read.peek() == 's') {\n\t\t\t\t\t\td_read.ignore(SSmax, ':');\n\t\t\t\t\t\tgetline(d_read, short_str, 'k');\n\t\t\t\t\t\trss += stoull(short_str);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (rss == detailed.entry.mem >> 10)\n\t\t\t\t\tdetailed.skip_smaps = true;\n\t\t\t\telse {\n\t\t\t\t\tdetailed.mem_bytes.push_back(rss << 10);\n\t\t\t\t\tdetailed.memory = floating_humanizer(rss, false, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (const std::invalid_argument&) {}\n\t\t\tcatch (const std::out_of_range&) {}\n\t\t\td_read.close();\n\t\t}\n\t\tif (detailed.memory.empty()) {\n\t\t\tdetailed.mem_bytes.push_back(detailed.entry.mem);\n\t\t\tdetailed.memory = floating_humanizer(detailed.entry.mem);\n\t\t}\n\t\tif (detailed.first_mem == -1 or detailed.first_mem < detailed.mem_bytes.back() / 2 or detailed.first_mem > detailed.mem_bytes.back() * 4) {\n\t\t\tdetailed.first_mem = min((uint64_t)detailed.mem_bytes.back() * 2, Mem::get_totalMem());\n\t\t\tredraw = true;\n\t\t}\n\n\t\twhile (cmp_greater(detailed.mem_bytes.size(), width)) detailed.mem_bytes.pop_front();\n\n\t\t//? Get bytes read and written from proc/[pid]/io\n\t\tif (fs::exists(pid_path / \"io\")) {\n\t\t\td_read.open(pid_path / \"io\");\n\t\t\ttry {\n\t\t\t\tstring name;\n\t\t\t\twhile (d_read.good()) {\n\t\t\t\t\tgetline(d_read, name, ':');\n\t\t\t\t\tif (name.ends_with(\"read_bytes\")) {\n\t\t\t\t\t\tgetline(d_read, short_str);\n\t\t\t\t\t\tdetailed.io_read = floating_humanizer(stoull(short_str));\n\t\t\t\t\t}\n\t\t\t\t\telse if (name.ends_with(\"write_bytes\")) {\n\t\t\t\t\t\tgetline(d_read, short_str);\n\t\t\t\t\t\tdetailed.io_write = floating_humanizer(stoull(short_str));\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\td_read.ignore(SSmax, '\\n');\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (const std::invalid_argument&) {}\n\t\t\tcatch (const std::out_of_range&) {}\n\t\t\td_read.close();\n\t\t}\n\t}\n\n\t//* Collects and sorts process information from /proc\n\tauto collect(bool no_update) -> vector<proc_info>& {\n\t\tif (Runner::stopping) return current_procs;\n\t\tconst auto& sorting = Config::getS(\"proc_sorting\");\n\t\tauto reverse = Config::getB(\"proc_reversed\");\n\t\tconst auto& filter = Config::getS(\"proc_filter\");\n\t\tauto per_core = Config::getB(\"proc_per_core\");\n\t\tauto should_filter_kernel = Config::getB(\"proc_filter_kernel\");\n\t\tauto tree = Config::getB(\"proc_tree\");\n\t\tauto show_detailed = Config::getB(\"show_detailed\");\n\t\tconst auto pause_proc_list = Config::getB(\"pause_proc_list\");\n\t\tconst size_t detailed_pid = Config::getI(\"detailed_pid\");\n\t\tbool should_filter = current_filter != filter;\n\t\tif (should_filter) current_filter = filter;\n\t\tbool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter);\n\t\tbool tree_mode_change = tree != is_tree_mode;\n\t\tif (sorted_change) {\n\t\t\tcurrent_sort = sorting;\n\t\t\tcurrent_rev = reverse;\n\t\t}\n\t\tif (tree_mode_change) is_tree_mode = tree;\n\t\tifstream pread;\n\t\tstring long_string;\n\t\tstring short_str;\n\n\t\tstatic vector<size_t> found;\n\n\t\tconst double uptime = system_uptime();\n\n\t\tconst int cmult = (per_core) ? Shared::coreCount : 1;\n\t\tbool got_detailed = false;\n\n\t\tstatic size_t proc_clear_count{};\n\n\t\t//* Use pids from last update if only changing filter, sorting or tree options\n\t\tif (no_update and not current_procs.empty()) {\n\t\t\tif (show_detailed and detailed_pid != detailed.last_pid) _collect_details(detailed_pid, round(uptime), current_procs);\n\t\t}\n\t\t//* ---------------------------------------------Collection start----------------------------------------------\n\t\telse {\n\t\t\tshould_filter = true;\n\t\t\tfound.clear();\n\n\t\t\t//? First make sure kernel proc cache is cleared.\n\t\t\tif (should_filter_kernel and ++proc_clear_count >= 256) {\n\t\t\t\t//? Clearing the cache is used in the event of a pid wrap around.\n\t\t\t\t//? In that event processes that acquire old kernel pids would also be filtered out so we need to manually clean the cache every now and then.\n\t\t\t\tkernels_procs.clear();\n\t\t\t\tkernels_procs.emplace(KTHREADD);\n\t\t\t\tproc_clear_count = 0;\n\t\t\t}\n\n\t\t\tauto totalMem = Mem::get_totalMem();\n\t\t\tint totalMem_len = to_string(totalMem >> 10).size();\n\n\t\t\t//? Update uid_user map if /etc/passwd changed since last run\n\t\t\tif (not Shared::passwd_path.empty() and fs::last_write_time(Shared::passwd_path) != passwd_time) {\n\t\t\t\tstring r_uid, r_user;\n\t\t\t\tpasswd_time = fs::last_write_time(Shared::passwd_path);\n\t\t\t\tuid_user.clear();\n\t\t\t\tpread.open(Shared::passwd_path);\n\t\t\t\tif (pread.good()) {\n\t\t\t\t\twhile (pread.good()) {\n\t\t\t\t\t\tgetline(pread, r_user, ':');\n\t\t\t\t\t\tpread.ignore(SSmax, ':');\n\t\t\t\t\t\tgetline(pread, r_uid, ':');\n\t\t\t\t\t\tif (uid_user.contains(r_uid)) break;\n\t\t\t\t\t\tuid_user[r_uid] = r_user;\n\t\t\t\t\t\tpread.ignore(SSmax, '\\n');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tShared::passwd_path.clear();\n\t\t\t\t}\n\t\t\t\tpread.close();\n\t\t\t}\n\n\t\t\t//? Get cpu total times from /proc/stat\n\t\t\tcputimes = 0;\n\t\t\tpread.open(Shared::procPath / \"stat\");\n\t\t\tif (pread.good()) {\n\t\t\t\tpread.ignore(SSmax, ' ');\n\t\t\t\tfor (uint64_t times; pread >> times; cputimes += times);\n\t\t\t}\n\t\t\telse throw std::runtime_error(\"Failure to read /proc/stat\");\n\t\t\tpread.close();\n\n\t\t\t//? Iterate over all pids in /proc\n\t\t\tfor (const auto& d: fs::directory_iterator(Shared::procPath)) {\n\t\t\t\tif (Runner::stopping)\n\t\t\t\t\treturn current_procs;\n\n\t\t\t\tif (pread.is_open()) pread.close();\n\n\t\t\t\tconst string pid_str = d.path().filename();\n\t\t\t\tif (not isdigit(pid_str[0])) continue;\n\n\t\t\t\tconst size_t pid = stoul(pid_str);\n\n\t\t\t\tif (should_filter_kernel and kernels_procs.contains(pid)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfound.push_back(pid);\n\n\t\t\t\t//? Check if pid already exists in current_procs\n\t\t\t\tauto find_old = rng::find(current_procs, pid, &proc_info::pid);\n\t\t\t\tbool no_cache{};\n\t\t\t\t//? Only add new processes if not paused\n\t\t\t\tif (find_old == current_procs.end()) {\n\t\t\t\t\tif (not pause_proc_list) {\n\t\t\t\t\t\tcurrent_procs.push_back({pid});\n\t\t\t\t\t\tfind_old = current_procs.end() - 1;\n\t\t\t\t\t\tno_cache = true;\n\t\t\t\t\t}\n\t\t\t\t\telse continue;\n\t\t\t\t}\n\t\t\t\telse if (dead_procs.contains(pid)) continue;\n\n\t\t\t\tauto& new_proc = *find_old;\n\n\t\t\t\t//? Get program name, command and username\n\t\t\t\tif (no_cache) {\n\t\t\t\t\tpread.open(d.path() / \"comm\");\n\t\t\t\t\tif (not pread.good()) continue;\n\t\t\t\t\tgetline(pread, new_proc.name);\n\t\t\t\t\tpread.close();\n\t\t\t\t\t//? Check for whitespace characters in name and set offset to get correct fields from stat file\n\t\t\t\t\tnew_proc.name_offset = rng::count(new_proc.name, ' ');\n\n\t\t\t\t\tpread.open(d.path() / \"cmdline\");\n\t\t\t\t\tif (not pread.good()) continue;\n\t\t\t\t\tlong_string.clear();\n\t\t\t\t\twhile(getline(pread, long_string, '\\0')) {\n\t\t\t\t\t\tnew_proc.cmd += long_string + ' ';\n\t\t\t\t\t\tif (new_proc.cmd.size() > 1000) {\n\t\t\t\t\t\t\tnew_proc.cmd.resize(1000);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tpread.close();\n\t\t\t\t\tif (not new_proc.cmd.empty()) new_proc.cmd.pop_back();\n\n\t\t\t\t\tpread.open(d.path() / \"status\");\n\t\t\t\t\tif (not pread.good()) continue;\n\t\t\t\t\tstring uid;\n\t\t\t\t\tstring line;\n\t\t\t\t\twhile (pread.good()) {\n\t\t\t\t\t\tgetline(pread, line, ':');\n\t\t\t\t\t\tif (line == \"Uid\") {\n\t\t\t\t\t\t\tpread.ignore();\n\t\t\t\t\t\t\tgetline(pread, uid, '\\t');\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpread.ignore(SSmax, '\\n');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tpread.close();\n\t\t\t\t\tif (uid_user.contains(uid)) {\n\t\t\t\t\t\tnew_proc.user = uid_user.at(uid);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t#if !(defined(STATIC_BUILD) && defined(__GLIBC__))\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tstruct passwd* udet;\n\t\t\t\t\t\t\tudet = getpwuid(stoi(uid));\n\t\t\t\t\t\t\tif (udet != nullptr and udet->pw_name != nullptr) {\n\t\t\t\t\t\t\t\tnew_proc.user = string(udet->pw_name);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tnew_proc.user = uid;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch (...) { new_proc.user = uid; }\n\t\t\t\t\t#else\n\t\t\t\t\t\tnew_proc.user = uid;\n\t\t\t\t\t#endif\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//? Parse /proc/[pid]/stat\n\t\t\t\tpread.open(d.path() / \"stat\");\n\t\t\t\tif (not pread.good()) continue;\n\n\t\t\t\tconst auto& offset = new_proc.name_offset;\n\t\t\t\tshort_str.clear();\n\t\t\t\tint x = 0, next_x = 3;\n\t\t\t\tuint64_t cpu_t = 0;\n\t\t\t\ttry {\n\t\t\t\t\tfor (;;) {\n\t\t\t\t\t\twhile (pread.good() and ++x < next_x + offset) pread.ignore(SSmax, ' ');\n\t\t\t\t\t\tif (not pread.good()) break;\n\t\t\t\t\t\telse getline(pread, short_str, ' ');\n\n\t\t\t\t\t\tswitch (x-offset) {\n\t\t\t\t\t\t\tcase 3: //? Process state\n\t\t\t\t\t\t\t\tnew_proc.state = short_str.at(0);\n\t\t\t\t\t\t\t\tif (new_proc.ppid != 0) next_x = 14;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tcase 4: //? Parent pid\n\t\t\t\t\t\t\t\tnew_proc.ppid = stoull(short_str);\n\t\t\t\t\t\t\t\tnext_x = 14;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tcase 14: //? Process utime\n\t\t\t\t\t\t\t\tcpu_t = stoull(short_str);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tcase 15: //? Process stime\n\t\t\t\t\t\t\t\tcpu_t += stoull(short_str);\n\t\t\t\t\t\t\t\tnext_x = 19;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tcase 19: //? Nice value\n\t\t\t\t\t\t\t\tnew_proc.p_nice = stoll(short_str);\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tcase 20: //? Number of threads\n\t\t\t\t\t\t\t\tnew_proc.threads = stoull(short_str);\n\t\t\t\t\t\t\t\tif (new_proc.cpu_s == 0) {\n\t\t\t\t\t\t\t\t\tnext_x = 22;\n\t\t\t\t\t\t\t\t\tnew_proc.cpu_t = cpu_t;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tnext_x = 24;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tcase 22: //? Get cpu seconds if missing\n\t\t\t\t\t\t\t\tnew_proc.cpu_s = stoull(short_str);\n\t\t\t\t\t\t\t\tnext_x = 24;\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tcase 24: //? RSS memory (can be inaccurate, but parsing smaps increases total cpu usage by ~20x)\n\t\t\t\t\t\t\t\tif (cmp_greater(short_str.size(), totalMem_len))\n\t\t\t\t\t\t\t\t\tnew_proc.mem = totalMem;\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tnew_proc.mem = stoull(short_str) * Shared::pageSize;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\tcatch (const std::invalid_argument&) { continue; }\n\t\t\t\tcatch (const std::out_of_range&) { continue; }\n\n\t\t\t\tpread.close();\n\n\t\t\t\tif (should_filter_kernel and new_proc.ppid == KTHREADD) {\n\t\t\t\t\tkernels_procs.emplace(new_proc.pid);\n\t\t\t\t\tfound.pop_back();\n\t\t\t\t}\n\n\t\t\t\tif (x-offset < 24) continue;\n\n\t\t\t\t//? Get RSS memory from /proc/[pid]/statm if value from /proc/[pid]/stat looks wrong\n\t\t\t\tif (new_proc.mem >= totalMem) {\n\t\t\t\t\tpread.open(d.path() / \"statm\");\n\t\t\t\t\tif (not pread.good()) continue;\n\t\t\t\t\tpread.ignore(SSmax, ' ');\n\t\t\t\t\tpread >> new_proc.mem;\n\t\t\t\t\tnew_proc.mem *= Shared::pageSize;\n\t\t\t\t\tpread.close();\n\t\t\t\t}\n\n\t\t\t\t//? Process cpu usage since last update\n\t\t\t\tnew_proc.cpu_p = clamp(round(cmult * 1000 * (cpu_t - new_proc.cpu_t) / max((uint64_t)1, cputimes - old_cputimes)) / 10.0, 0.0, 100.0 * Shared::coreCount);\n\n\t\t\t\t//? Process cumulative cpu usage since process start\n\t\t\t\tnew_proc.cpu_c = (double)cpu_t / max(1.0, (uptime * Shared::clkTck) - new_proc.cpu_s);\n\n\t\t\t\t//? Update cached value with latest cpu times\n\t\t\t\tnew_proc.cpu_t = cpu_t;\n\n\t\t\t\tif (show_detailed and not got_detailed and new_proc.pid == detailed_pid) {\n\t\t\t\t\tgot_detailed = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Clear dead processes from current_procs and remove kernel processes if enabled and not paused\n\t\t\tif (not pause_proc_list) {\n\t\t\t\tauto eraser = rng::remove_if(current_procs, [&](const auto& element){ return not v_contains(found, element.pid); });\n\t\t\t\tcurrent_procs.erase(eraser.begin(), eraser.end());\n\t\t\t\tif (!dead_procs.empty()) dead_procs.clear();\n\t\t\t}\n\t\t\t//? Set correct state of dead processes if paused\n\t\t\telse {\n\t\t\t\tconst bool keep_dead_proc_usage = Config::getB(\"keep_dead_proc_usage\");\n\t\t\t\tfor (auto& r : current_procs) {\n\t\t\t\t\tif (rng::find(found, r.pid) == found.end()) {\n\t\t\t\t\t\tif (r.state != 'X') r.death_time = round(uptime) - (r.cpu_s / Shared::clkTck);\n\t\t\t\t\t\tr.state = 'X';\n\t\t\t\t\t\tdead_procs.emplace(r.pid);\n\t\t\t\t\t\t//? Reset cpu usage for dead processes if paused and option is set\n\t\t\t\t\t\tif (!keep_dead_proc_usage) {\n\t\t\t\t\t\t\tr.cpu_p = 0.0;\n\t\t\t\t\t\t\tr.mem = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Update the details info box for process if active\n\t\t\tif (show_detailed and got_detailed) {\n\t\t\t\t_collect_details(detailed_pid, round(uptime), current_procs);\n\t\t\t}\n\t\t\telse if (show_detailed and not got_detailed and detailed.status != \"Dead\") {\n\t\t\t\tdetailed.status = \"Dead\";\n\t\t\t\tredraw = true;\n\t\t\t}\n\n\t\t\told_cputimes = cputimes;\n\t\t}\n\t\t//* ---------------------------------------------Collection done-----------------------------------------------\n\n\t\t//* Match filter if defined\n\t\tif (should_filter) {\n\t\t\tfilter_found = 0;\n\t\t\tfor (auto& p : current_procs) {\n\t\t\t\tif (not tree and not filter.empty()) {\n\t\t\t\t\tif (!matches_filter(p, filter)) {\n\t\t\t\t\t\tp.filtered = true;\n\t\t\t\t\t\tfilter_found++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tp.filtered = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tp.filtered = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//* Sort processes\n\t\tif ((sorted_change or tree_mode_change) or (not no_update and not pause_proc_list)) {\n\t\t\tproc_sorter(current_procs, sorting, reverse, tree);\n\t\t}\n\n\t\t//* Generate tree view if enabled\n\t\tif (tree and (not no_update or should_filter or sorted_change)) {\n\t\t\tbool locate_selection = false;\n\n\t\t\tif (toggle_children != -1) {\n\t\t\t\tauto collapser = rng::find(current_procs, toggle_children, &proc_info::pid);\n\t\t\t\tif (collapser != current_procs.end()){\n\t\t\t\t\tfor (auto& p : current_procs) {\n\t\t\t\t\t\tif (p.ppid == collapser->pid) {\n\t\t\t\t\t\t\tauto child = rng::find(current_procs, p.pid, &proc_info::pid);\n\t\t\t\t\t\t\tif (child != current_procs.end()){\n\t\t\t\t\t\t\t\tchild->collapsed = not child->collapsed;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (Config::ints.at(\"proc_selected\") > 0) locate_selection = true;\n\t\t\t\t}\n\t\t\t\ttoggle_children = -1;\n\t\t\t}\n\t\t\t\n\t\t\tif (auto find_pid = (collapse != -1 ? collapse : expand); find_pid != -1) {\n\t\t\t\tauto collapser = rng::find(current_procs, find_pid, &proc_info::pid);\n\t\t\t\tif (collapser != current_procs.end()) {\n\t\t\t\t\tif (collapse == expand) {\n\t\t\t\t\t\tcollapser->collapsed = not collapser->collapsed;\n\t\t\t\t\t}\n\t\t\t\t\telse if (collapse > -1) {\n\t\t\t\t\t\tcollapser->collapsed = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (expand > -1) {\n\t\t\t\t\t\tcollapser->collapsed = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (Config::ints.at(\"proc_selected\") > 0) locate_selection = true;\n\t\t\t\t}\n\t\t\t\tcollapse = expand = -1;\n\t\t\t}\n\t\t\tif (should_filter or not filter.empty()) filter_found = 0;\n\n\t\t\tvector<tree_proc> tree_procs;\n\t\t\ttree_procs.reserve(current_procs.size());\n\n\t\t\tif (!pause_proc_list) {\n\t\t\t\tfor (auto& p : current_procs) {\n\t\t\t\t\tif (not v_contains(found, p.ppid)) p.ppid = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Stable sort to retain selected sorting among processes with the same parent\n\t\t\trng::stable_sort(current_procs, rng::less{}, & proc_info::ppid);\n\n\t\t\t//? Start recursive iteration over processes with the lowest shared parent pids\n\t\t\tfor (auto& p : rng::equal_range(current_procs, current_procs.at(0).ppid, rng::less{}, &proc_info::ppid)) {\n\t\t\t\t_tree_gen(p, current_procs, tree_procs, 0, false, filter, false, no_update, should_filter);\n\t\t\t}\n\n\t\t\t//? Recursive sort over tree structure to account for collapsed processes in the tree\n\t\t\tint index = 0;\n\t\t\ttree_sort(tree_procs, sorting, reverse, (pause_proc_list and not (sorted_change or tree_mode_change)), index, current_procs.size());\n\n\t\t\t//? Recursive construction of ASCII tree prefixes.\n\t\t\tfor (auto t = tree_procs.begin(); t != tree_procs.end(); ++t) {\n\t\t\t\t_collect_prefixes(*t, t == tree_procs.end() - 1);\n\t\t\t}\n\n\t\t\t//? Final sort based on tree index\n\t\t\trng::stable_sort(current_procs, rng::less {}, &proc_info::tree_index);\n\n\t\t\t//? Move current selection/view to the selected process when collapsing/expanding in the tree\n\t\t\tif (locate_selection) {\n\t\t\t\tint loc = rng::find(current_procs, Proc::selected_pid, &proc_info::pid)->tree_index;\n\t\t\t\tif (Config::ints.at(\"proc_start\") >= loc or Config::ints.at(\"proc_start\") <= loc - Proc::select_max)\n\t\t\t\t\tConfig::ints.at(\"proc_start\") = max(0, loc - 1);\n\t\t\t\tConfig::ints.at(\"proc_selected\") = loc - Config::ints.at(\"proc_start\") + 1;\n\t\t\t}\n\t\t}\n\n\t\tnumpids = (int)current_procs.size() - filter_found;\n\n\t\treturn current_procs;\n\t}\n}\n\nnamespace Tools {\n\tdouble system_uptime() {\n\t\tstring upstr;\n\t\tifstream pread(Shared::procPath / \"uptime\");\n\t\tif (pread.good()) {\n\t\t\ttry {\n\t\t\t\tgetline(pread, upstr, ' ');\n\t\t\t\tpread.close();\n\t\t\t\treturn stod(upstr);\n\t\t\t}\n\t\t\tcatch (const std::invalid_argument&) {}\n\t\t\tcatch (const std::out_of_range&) {}\n\t\t}\n        throw std::runtime_error(fmt::format(\"Failed to get uptime from {}\", Shared::procPath / \"uptime\"));\n\t}\n}\n"
  },
  {
    "path": "src/linux/intel_gpu_top/CMakeLists.txt",
    "content": "enable_language(C)\n\nadd_library(igt OBJECT\n  igt_perf.c\n  intel_device_info.c\n  intel_gpu_top.c\n  intel_name_lookup_shim.c\n)\n\nif(BTOP_LTO)\n  # We have checked LTO support already and it's supported :)\n  set_target_properties(igt PROPERTIES INTERPROCEDURAL_OPTIMIZATION ON)\nendif()\n\n# Disable all warnings\ntarget_compile_options(igt PRIVATE -w)\n\n# Link igt into btop\ntarget_link_libraries(libbtop $<TARGET_OBJECTS:igt>)\n"
  },
  {
    "path": "src/linux/intel_gpu_top/drm.h",
    "content": "/*\n * Header for the Direct Rendering Manager\n *\n * Author: Rickard E. (Rik) Faith <faith@valinux.com>\n *\n * Acknowledgments:\n * Dec 1999, Richard Henderson <rth@twiddle.net>, move to generic cmpxchg.\n */\n\n/*\n * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.\n * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.\n * All rights reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\n * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n */\n\n#ifndef _DRM_H_\n#define _DRM_H_\n\n#if   defined(__linux__)\n\n#include <linux/types.h>\n#include <asm/ioctl.h>\ntypedef unsigned int drm_handle_t;\n\n#else /* One of the BSDs */\n\n#include <stdint.h>\n#include <sys/ioccom.h>\n#include <sys/types.h>\ntypedef int8_t   __s8;\ntypedef uint8_t  __u8;\ntypedef int16_t  __s16;\ntypedef uint16_t __u16;\ntypedef int32_t  __s32;\ntypedef uint32_t __u32;\ntypedef int64_t  __s64;\ntypedef uint64_t __u64;\ntypedef size_t   __kernel_size_t;\ntypedef unsigned long drm_handle_t;\n\n#endif\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\n#define DRM_NAME\t\"drm\"\t  /**< Name in kernel, /dev, and /proc */\n#define DRM_MIN_ORDER\t5\t  /**< At least 2^5 bytes = 32 bytes */\n#define DRM_MAX_ORDER\t22\t  /**< Up to 2^22 bytes = 4MB */\n#define DRM_RAM_PERCENT 10\t  /**< How much system ram can we lock? */\n\n#define _DRM_LOCK_HELD\t0x80000000U /**< Hardware lock is held */\n#define _DRM_LOCK_CONT\t0x40000000U /**< Hardware lock is contended */\n#define _DRM_LOCK_IS_HELD(lock)\t   ((lock) & _DRM_LOCK_HELD)\n#define _DRM_LOCK_IS_CONT(lock)\t   ((lock) & _DRM_LOCK_CONT)\n#define _DRM_LOCKING_CONTEXT(lock) ((lock) & ~(_DRM_LOCK_HELD|_DRM_LOCK_CONT))\n\ntypedef unsigned int drm_context_t;\ntypedef unsigned int drm_drawable_t;\ntypedef unsigned int drm_magic_t;\n\n/*\n * Cliprect.\n *\n * \\warning: If you change this structure, make sure you change\n * XF86DRIClipRectRec in the server as well\n *\n * \\note KW: Actually it's illegal to change either for\n * backwards-compatibility reasons.\n */\nstruct drm_clip_rect {\n\tunsigned short x1;\n\tunsigned short y1;\n\tunsigned short x2;\n\tunsigned short y2;\n};\n\n/*\n * Drawable information.\n */\nstruct drm_drawable_info {\n\tunsigned int num_rects;\n\tstruct drm_clip_rect *rects;\n};\n\n/*\n * Texture region,\n */\nstruct drm_tex_region {\n\tunsigned char next;\n\tunsigned char prev;\n\tunsigned char in_use;\n\tunsigned char padding;\n\tunsigned int age;\n};\n\n/*\n * Hardware lock.\n *\n * The lock structure is a simple cache-line aligned integer.  To avoid\n * processor bus contention on a multiprocessor system, there should not be any\n * other data stored in the same cache line.\n */\nstruct drm_hw_lock {\n\t__volatile__ unsigned int lock;\t\t/**< lock variable */\n\tchar padding[60];\t\t\t/**< Pad to cache line */\n};\n\n/*\n * DRM_IOCTL_VERSION ioctl argument type.\n *\n * \\sa drmGetVersion().\n */\nstruct drm_version {\n\tint version_major;\t  /**< Major version */\n\tint version_minor;\t  /**< Minor version */\n\tint version_patchlevel;\t  /**< Patch level */\n\t__kernel_size_t name_len;\t  /**< Length of name buffer */\n\tchar *name;\t  /**< Name of driver */\n\t__kernel_size_t date_len;\t  /**< Length of date buffer */\n\tchar *date;\t  /**< User-space buffer to hold date */\n\t__kernel_size_t desc_len;\t  /**< Length of desc buffer */\n\tchar *desc;\t  /**< User-space buffer to hold desc */\n};\n\n/*\n * DRM_IOCTL_GET_UNIQUE ioctl argument type.\n *\n * \\sa drmGetBusid() and drmSetBusId().\n */\nstruct drm_unique {\n\t__kernel_size_t unique_len;\t  /**< Length of unique */\n\tchar *unique;\t  /**< Unique name for driver instantiation */\n};\n\nstruct drm_list {\n\tint count;\t\t  /**< Length of user-space structures */\n\tstruct drm_version *version;\n};\n\nstruct drm_block {\n\tint unused;\n};\n\n/*\n * DRM_IOCTL_CONTROL ioctl argument type.\n *\n * \\sa drmCtlInstHandler() and drmCtlUninstHandler().\n */\nstruct drm_control {\n\tenum {\n\t\tDRM_ADD_COMMAND,\n\t\tDRM_RM_COMMAND,\n\t\tDRM_INST_HANDLER,\n\t\tDRM_UNINST_HANDLER\n\t} func;\n\tint irq;\n};\n\n/*\n * Type of memory to map.\n */\nenum drm_map_type {\n\t_DRM_FRAME_BUFFER = 0,\t  /**< WC (no caching), no core dump */\n\t_DRM_REGISTERS = 1,\t  /**< no caching, no core dump */\n\t_DRM_SHM = 2,\t\t  /**< shared, cached */\n\t_DRM_AGP = 3,\t\t  /**< AGP/GART */\n\t_DRM_SCATTER_GATHER = 4,  /**< Scatter/gather memory for PCI DMA */\n\t_DRM_CONSISTENT = 5\t  /**< Consistent memory for PCI DMA */\n};\n\n/*\n * Memory mapping flags.\n */\nenum drm_map_flags {\n\t_DRM_RESTRICTED = 0x01,\t     /**< Cannot be mapped to user-virtual */\n\t_DRM_READ_ONLY = 0x02,\n\t_DRM_LOCKED = 0x04,\t     /**< shared, cached, locked */\n\t_DRM_KERNEL = 0x08,\t     /**< kernel requires access */\n\t_DRM_WRITE_COMBINING = 0x10, /**< use write-combining if available */\n\t_DRM_CONTAINS_LOCK = 0x20,   /**< SHM page that contains lock */\n\t_DRM_REMOVABLE = 0x40,\t     /**< Removable mapping */\n\t_DRM_DRIVER = 0x80\t     /**< Managed by driver */\n};\n\nstruct drm_ctx_priv_map {\n\tunsigned int ctx_id;\t /**< Context requesting private mapping */\n\tvoid *handle;\t\t /**< Handle of map */\n};\n\n/*\n * DRM_IOCTL_GET_MAP, DRM_IOCTL_ADD_MAP and DRM_IOCTL_RM_MAP ioctls\n * argument type.\n *\n * \\sa drmAddMap().\n */\nstruct drm_map {\n\tunsigned long offset;\t /**< Requested physical address (0 for SAREA)*/\n\tunsigned long size;\t /**< Requested physical size (bytes) */\n\tenum drm_map_type type;\t /**< Type of memory to map */\n\tenum drm_map_flags flags;\t /**< Flags */\n\tvoid *handle;\t\t /**< User-space: \"Handle\" to pass to mmap() */\n\t\t\t\t /**< Kernel-space: kernel-virtual address */\n\tint mtrr;\t\t /**< MTRR slot used */\n\t/*   Private data */\n};\n\n/*\n * DRM_IOCTL_GET_CLIENT ioctl argument type.\n */\nstruct drm_client {\n\tint idx;\t\t/**< Which client desired? */\n\tint auth;\t\t/**< Is client authenticated? */\n\tunsigned long pid;\t/**< Process ID */\n\tunsigned long uid;\t/**< User ID */\n\tunsigned long magic;\t/**< Magic */\n\tunsigned long iocs;\t/**< Ioctl count */\n};\n\nenum drm_stat_type {\n\t_DRM_STAT_LOCK,\n\t_DRM_STAT_OPENS,\n\t_DRM_STAT_CLOSES,\n\t_DRM_STAT_IOCTLS,\n\t_DRM_STAT_LOCKS,\n\t_DRM_STAT_UNLOCKS,\n\t_DRM_STAT_VALUE,\t/**< Generic value */\n\t_DRM_STAT_BYTE,\t\t/**< Generic byte counter (1024bytes/K) */\n\t_DRM_STAT_COUNT,\t/**< Generic non-byte counter (1000/k) */\n\n\t_DRM_STAT_IRQ,\t\t/**< IRQ */\n\t_DRM_STAT_PRIMARY,\t/**< Primary DMA bytes */\n\t_DRM_STAT_SECONDARY,\t/**< Secondary DMA bytes */\n\t_DRM_STAT_DMA,\t\t/**< DMA */\n\t_DRM_STAT_SPECIAL,\t/**< Special DMA (e.g., priority or polled) */\n\t_DRM_STAT_MISSED\t/**< Missed DMA opportunity */\n\t    /* Add to the *END* of the list */\n};\n\n/*\n * DRM_IOCTL_GET_STATS ioctl argument type.\n */\nstruct drm_stats {\n\tunsigned long count;\n\tstruct {\n\t\tunsigned long value;\n\t\tenum drm_stat_type type;\n\t} data[15];\n};\n\n/*\n * Hardware locking flags.\n */\nenum drm_lock_flags {\n\t_DRM_LOCK_READY = 0x01,\t     /**< Wait until hardware is ready for DMA */\n\t_DRM_LOCK_QUIESCENT = 0x02,  /**< Wait until hardware quiescent */\n\t_DRM_LOCK_FLUSH = 0x04,\t     /**< Flush this context's DMA queue first */\n\t_DRM_LOCK_FLUSH_ALL = 0x08,  /**< Flush all DMA queues first */\n\t/* These *HALT* flags aren't supported yet\n\t   -- they will be used to support the\n\t   full-screen DGA-like mode. */\n\t_DRM_HALT_ALL_QUEUES = 0x10, /**< Halt all current and future queues */\n\t_DRM_HALT_CUR_QUEUES = 0x20  /**< Halt all current queues */\n};\n\n/*\n * DRM_IOCTL_LOCK, DRM_IOCTL_UNLOCK and DRM_IOCTL_FINISH ioctl argument type.\n *\n * \\sa drmGetLock() and drmUnlock().\n */\nstruct drm_lock {\n\tint context;\n\tenum drm_lock_flags flags;\n};\n\n/*\n * DMA flags\n *\n * \\warning\n * These values \\e must match xf86drm.h.\n *\n * \\sa drm_dma.\n */\nenum drm_dma_flags {\n\t/* Flags for DMA buffer dispatch */\n\t_DRM_DMA_BLOCK = 0x01,\t      /**<\n\t\t\t\t       * Block until buffer dispatched.\n\t\t\t\t       *\n\t\t\t\t       * \\note The buffer may not yet have\n\t\t\t\t       * been processed by the hardware --\n\t\t\t\t       * getting a hardware lock with the\n\t\t\t\t       * hardware quiescent will ensure\n\t\t\t\t       * that the buffer has been\n\t\t\t\t       * processed.\n\t\t\t\t       */\n\t_DRM_DMA_WHILE_LOCKED = 0x02, /**< Dispatch while lock held */\n\t_DRM_DMA_PRIORITY = 0x04,     /**< High priority dispatch */\n\n\t/* Flags for DMA buffer request */\n\t_DRM_DMA_WAIT = 0x10,\t      /**< Wait for free buffers */\n\t_DRM_DMA_SMALLER_OK = 0x20,   /**< Smaller-than-requested buffers OK */\n\t_DRM_DMA_LARGER_OK = 0x40     /**< Larger-than-requested buffers OK */\n};\n\n/*\n * DRM_IOCTL_ADD_BUFS and DRM_IOCTL_MARK_BUFS ioctl argument type.\n *\n * \\sa drmAddBufs().\n */\nstruct drm_buf_desc {\n\tint count;\t\t /**< Number of buffers of this size */\n\tint size;\t\t /**< Size in bytes */\n\tint low_mark;\t\t /**< Low water mark */\n\tint high_mark;\t\t /**< High water mark */\n\tenum {\n\t\t_DRM_PAGE_ALIGN = 0x01,\t/**< Align on page boundaries for DMA */\n\t\t_DRM_AGP_BUFFER = 0x02,\t/**< Buffer is in AGP space */\n\t\t_DRM_SG_BUFFER = 0x04,\t/**< Scatter/gather memory buffer */\n\t\t_DRM_FB_BUFFER = 0x08,\t/**< Buffer is in frame buffer */\n\t\t_DRM_PCI_BUFFER_RO = 0x10 /**< Map PCI DMA buffer read-only */\n\t} flags;\n\tunsigned long agp_start; /**<\n\t\t\t\t  * Start address of where the AGP buffers are\n\t\t\t\t  * in the AGP aperture\n\t\t\t\t  */\n};\n\n/*\n * DRM_IOCTL_INFO_BUFS ioctl argument type.\n */\nstruct drm_buf_info {\n\tint count;\t\t/**< Entries in list */\n\tstruct drm_buf_desc *list;\n};\n\n/*\n * DRM_IOCTL_FREE_BUFS ioctl argument type.\n */\nstruct drm_buf_free {\n\tint count;\n\tint *list;\n};\n\n/*\n * Buffer information\n *\n * \\sa drm_buf_map.\n */\nstruct drm_buf_pub {\n\tint idx;\t\t       /**< Index into the master buffer list */\n\tint total;\t\t       /**< Buffer size */\n\tint used;\t\t       /**< Amount of buffer in use (for DMA) */\n\tvoid *address;\t       /**< Address of buffer */\n};\n\n/*\n * DRM_IOCTL_MAP_BUFS ioctl argument type.\n */\nstruct drm_buf_map {\n\tint count;\t\t/**< Length of the buffer list */\n#ifdef __cplusplus\n\tvoid *virt;\n#else\n\tvoid *virtual;\t\t/**< Mmap'd area in user-virtual */\n#endif\n\tstruct drm_buf_pub *list;\t/**< Buffer information */\n};\n\n/*\n * DRM_IOCTL_DMA ioctl argument type.\n *\n * Indices here refer to the offset into the buffer list in drm_buf_get.\n *\n * \\sa drmDMA().\n */\nstruct drm_dma {\n\tint context;\t\t\t  /**< Context handle */\n\tint send_count;\t\t\t  /**< Number of buffers to send */\n\tint *send_indices;\t  /**< List of handles to buffers */\n\tint *send_sizes;\t\t  /**< Lengths of data to send */\n\tenum drm_dma_flags flags;\t  /**< Flags */\n\tint request_count;\t\t  /**< Number of buffers requested */\n\tint request_size;\t\t  /**< Desired size for buffers */\n\tint *request_indices;\t  /**< Buffer information */\n\tint *request_sizes;\n\tint granted_count;\t\t  /**< Number of buffers granted */\n};\n\nenum drm_ctx_flags {\n\t_DRM_CONTEXT_PRESERVED = 0x01,\n\t_DRM_CONTEXT_2DONLY = 0x02\n};\n\n/*\n * DRM_IOCTL_ADD_CTX ioctl argument type.\n *\n * \\sa drmCreateContext() and drmDestroyContext().\n */\nstruct drm_ctx {\n\tdrm_context_t handle;\n\tenum drm_ctx_flags flags;\n};\n\n/*\n * DRM_IOCTL_RES_CTX ioctl argument type.\n */\nstruct drm_ctx_res {\n\tint count;\n\tstruct drm_ctx *contexts;\n};\n\n/*\n * DRM_IOCTL_ADD_DRAW and DRM_IOCTL_RM_DRAW ioctl argument type.\n */\nstruct drm_draw {\n\tdrm_drawable_t handle;\n};\n\n/*\n * DRM_IOCTL_UPDATE_DRAW ioctl argument type.\n */\ntypedef enum {\n\tDRM_DRAWABLE_CLIPRECTS\n} drm_drawable_info_type_t;\n\nstruct drm_update_draw {\n\tdrm_drawable_t handle;\n\tunsigned int type;\n\tunsigned int num;\n\tunsigned long long data;\n};\n\n/*\n * DRM_IOCTL_GET_MAGIC and DRM_IOCTL_AUTH_MAGIC ioctl argument type.\n */\nstruct drm_auth {\n\tdrm_magic_t magic;\n};\n\n/*\n * DRM_IOCTL_IRQ_BUSID ioctl argument type.\n *\n * \\sa drmGetInterruptFromBusID().\n */\nstruct drm_irq_busid {\n\tint irq;\t/**< IRQ number */\n\tint busnum;\t/**< bus number */\n\tint devnum;\t/**< device number */\n\tint funcnum;\t/**< function number */\n};\n\nenum drm_vblank_seq_type {\n\t_DRM_VBLANK_ABSOLUTE = 0x0,\t/**< Wait for specific vblank sequence number */\n\t_DRM_VBLANK_RELATIVE = 0x1,\t/**< Wait for given number of vblanks */\n\t/* bits 1-6 are reserved for high crtcs */\n\t_DRM_VBLANK_HIGH_CRTC_MASK = 0x0000003e,\n\t_DRM_VBLANK_EVENT = 0x4000000,   /**< Send event instead of blocking */\n\t_DRM_VBLANK_FLIP = 0x8000000,   /**< Scheduled buffer swap should flip */\n\t_DRM_VBLANK_NEXTONMISS = 0x10000000,\t/**< If missed, wait for next vblank */\n\t_DRM_VBLANK_SECONDARY = 0x20000000,\t/**< Secondary display controller */\n\t_DRM_VBLANK_SIGNAL = 0x40000000\t/**< Send signal instead of blocking, unsupported */\n};\n#define _DRM_VBLANK_HIGH_CRTC_SHIFT 1\n\n#define _DRM_VBLANK_TYPES_MASK (_DRM_VBLANK_ABSOLUTE | _DRM_VBLANK_RELATIVE)\n#define _DRM_VBLANK_FLAGS_MASK (_DRM_VBLANK_EVENT | _DRM_VBLANK_SIGNAL | \\\n\t\t\t\t_DRM_VBLANK_SECONDARY | _DRM_VBLANK_NEXTONMISS)\n\nstruct drm_wait_vblank_request {\n\tenum drm_vblank_seq_type type;\n\tunsigned int sequence;\n\tunsigned long signal;\n};\n\nstruct drm_wait_vblank_reply {\n\tenum drm_vblank_seq_type type;\n\tunsigned int sequence;\n\tlong tval_sec;\n\tlong tval_usec;\n};\n\n/*\n * DRM_IOCTL_WAIT_VBLANK ioctl argument type.\n *\n * \\sa drmWaitVBlank().\n */\nunion drm_wait_vblank {\n\tstruct drm_wait_vblank_request request;\n\tstruct drm_wait_vblank_reply reply;\n};\n\n#define _DRM_PRE_MODESET 1\n#define _DRM_POST_MODESET 2\n\n/*\n * DRM_IOCTL_MODESET_CTL ioctl argument type\n *\n * \\sa drmModesetCtl().\n */\nstruct drm_modeset_ctl {\n\t__u32 crtc;\n\t__u32 cmd;\n};\n\n/*\n * DRM_IOCTL_AGP_ENABLE ioctl argument type.\n *\n * \\sa drmAgpEnable().\n */\nstruct drm_agp_mode {\n\tunsigned long mode;\t/**< AGP mode */\n};\n\n/*\n * DRM_IOCTL_AGP_ALLOC and DRM_IOCTL_AGP_FREE ioctls argument type.\n *\n * \\sa drmAgpAlloc() and drmAgpFree().\n */\nstruct drm_agp_buffer {\n\tunsigned long size;\t/**< In bytes -- will round to page boundary */\n\tunsigned long handle;\t/**< Used for binding / unbinding */\n\tunsigned long type;\t/**< Type of memory to allocate */\n\tunsigned long physical;\t/**< Physical used by i810 */\n};\n\n/*\n * DRM_IOCTL_AGP_BIND and DRM_IOCTL_AGP_UNBIND ioctls argument type.\n *\n * \\sa drmAgpBind() and drmAgpUnbind().\n */\nstruct drm_agp_binding {\n\tunsigned long handle;\t/**< From drm_agp_buffer */\n\tunsigned long offset;\t/**< In bytes -- will round to page boundary */\n};\n\n/*\n * DRM_IOCTL_AGP_INFO ioctl argument type.\n *\n * \\sa drmAgpVersionMajor(), drmAgpVersionMinor(), drmAgpGetMode(),\n * drmAgpBase(), drmAgpSize(), drmAgpMemoryUsed(), drmAgpMemoryAvail(),\n * drmAgpVendorId() and drmAgpDeviceId().\n */\nstruct drm_agp_info {\n\tint agp_version_major;\n\tint agp_version_minor;\n\tunsigned long mode;\n\tunsigned long aperture_base;\t/* physical address */\n\tunsigned long aperture_size;\t/* bytes */\n\tunsigned long memory_allowed;\t/* bytes */\n\tunsigned long memory_used;\n\n\t/* PCI information */\n\tunsigned short id_vendor;\n\tunsigned short id_device;\n};\n\n/*\n * DRM_IOCTL_SG_ALLOC ioctl argument type.\n */\nstruct drm_scatter_gather {\n\tunsigned long size;\t/**< In bytes -- will round to page boundary */\n\tunsigned long handle;\t/**< Used for mapping / unmapping */\n};\n\n/*\n * DRM_IOCTL_SET_VERSION ioctl argument type.\n */\nstruct drm_set_version {\n\tint drm_di_major;\n\tint drm_di_minor;\n\tint drm_dd_major;\n\tint drm_dd_minor;\n};\n\n/* DRM_IOCTL_GEM_CLOSE ioctl argument type */\nstruct drm_gem_close {\n\t/** Handle of the object to be closed. */\n\t__u32 handle;\n\t__u32 pad;\n};\n\n/* DRM_IOCTL_GEM_FLINK ioctl argument type */\nstruct drm_gem_flink {\n\t/** Handle for the object being named */\n\t__u32 handle;\n\n\t/** Returned global name */\n\t__u32 name;\n};\n\n/* DRM_IOCTL_GEM_OPEN ioctl argument type */\nstruct drm_gem_open {\n\t/** Name of object being opened */\n\t__u32 name;\n\n\t/** Returned handle for the object */\n\t__u32 handle;\n\n\t/** Returned size of the object */\n\t__u64 size;\n};\n\n/**\n * DRM_CAP_DUMB_BUFFER\n *\n * If set to 1, the driver supports creating dumb buffers via the\n * &DRM_IOCTL_MODE_CREATE_DUMB ioctl.\n */\n#define DRM_CAP_DUMB_BUFFER\t\t0x1\n/**\n * DRM_CAP_VBLANK_HIGH_CRTC\n *\n * If set to 1, the kernel supports specifying a :ref:`CRTC index<crtc_index>`\n * in the high bits of &drm_wait_vblank_request.type.\n *\n * Starting kernel version 2.6.39, this capability is always set to 1.\n */\n#define DRM_CAP_VBLANK_HIGH_CRTC\t0x2\n/**\n * DRM_CAP_DUMB_PREFERRED_DEPTH\n *\n * The preferred bit depth for dumb buffers.\n *\n * The bit depth is the number of bits used to indicate the color of a single\n * pixel excluding any padding. This is different from the number of bits per\n * pixel. For instance, XRGB8888 has a bit depth of 24 but has 32 bits per\n * pixel.\n *\n * Note that this preference only applies to dumb buffers, it's irrelevant for\n * other types of buffers.\n */\n#define DRM_CAP_DUMB_PREFERRED_DEPTH\t0x3\n/**\n * DRM_CAP_DUMB_PREFER_SHADOW\n *\n * If set to 1, the driver prefers userspace to render to a shadow buffer\n * instead of directly rendering to a dumb buffer. For best speed, userspace\n * should do streaming ordered memory copies into the dumb buffer and never\n * read from it.\n *\n * Note that this preference only applies to dumb buffers, it's irrelevant for\n * other types of buffers.\n */\n#define DRM_CAP_DUMB_PREFER_SHADOW\t0x4\n/**\n * DRM_CAP_PRIME\n *\n * Bitfield of supported PRIME sharing capabilities. See &DRM_PRIME_CAP_IMPORT\n * and &DRM_PRIME_CAP_EXPORT.\n *\n * Starting from kernel version 6.6, both &DRM_PRIME_CAP_IMPORT and\n * &DRM_PRIME_CAP_EXPORT are always advertised.\n *\n * PRIME buffers are exposed as dma-buf file descriptors.\n * See :ref:`prime_buffer_sharing`.\n */\n#define DRM_CAP_PRIME\t\t\t0x5\n/**\n * DRM_PRIME_CAP_IMPORT\n *\n * If this bit is set in &DRM_CAP_PRIME, the driver supports importing PRIME\n * buffers via the &DRM_IOCTL_PRIME_FD_TO_HANDLE ioctl.\n *\n * Starting from kernel version 6.6, this bit is always set in &DRM_CAP_PRIME.\n */\n#define  DRM_PRIME_CAP_IMPORT\t\t0x1\n/**\n * DRM_PRIME_CAP_EXPORT\n *\n * If this bit is set in &DRM_CAP_PRIME, the driver supports exporting PRIME\n * buffers via the &DRM_IOCTL_PRIME_HANDLE_TO_FD ioctl.\n *\n * Starting from kernel version 6.6, this bit is always set in &DRM_CAP_PRIME.\n */\n#define  DRM_PRIME_CAP_EXPORT\t\t0x2\n/**\n * DRM_CAP_TIMESTAMP_MONOTONIC\n *\n * If set to 0, the kernel will report timestamps with ``CLOCK_REALTIME`` in\n * struct drm_event_vblank. If set to 1, the kernel will report timestamps with\n * ``CLOCK_MONOTONIC``. See ``clock_gettime(2)`` for the definition of these\n * clocks.\n *\n * Starting from kernel version 2.6.39, the default value for this capability\n * is 1. Starting kernel version 4.15, this capability is always set to 1.\n */\n#define DRM_CAP_TIMESTAMP_MONOTONIC\t0x6\n/**\n * DRM_CAP_ASYNC_PAGE_FLIP\n *\n * If set to 1, the driver supports &DRM_MODE_PAGE_FLIP_ASYNC.\n */\n#define DRM_CAP_ASYNC_PAGE_FLIP\t\t0x7\n/**\n * DRM_CAP_CURSOR_WIDTH\n *\n * The ``CURSOR_WIDTH`` and ``CURSOR_HEIGHT`` capabilities return a valid\n * width x height combination for the hardware cursor. The intention is that a\n * hardware agnostic userspace can query a cursor plane size to use.\n *\n * Note that the cross-driver contract is to merely return a valid size;\n * drivers are free to attach another meaning on top, eg. i915 returns the\n * maximum plane size.\n */\n#define DRM_CAP_CURSOR_WIDTH\t\t0x8\n/**\n * DRM_CAP_CURSOR_HEIGHT\n *\n * See &DRM_CAP_CURSOR_WIDTH.\n */\n#define DRM_CAP_CURSOR_HEIGHT\t\t0x9\n/**\n * DRM_CAP_ADDFB2_MODIFIERS\n *\n * If set to 1, the driver supports supplying modifiers in the\n * &DRM_IOCTL_MODE_ADDFB2 ioctl.\n */\n#define DRM_CAP_ADDFB2_MODIFIERS\t0x10\n/**\n * DRM_CAP_PAGE_FLIP_TARGET\n *\n * If set to 1, the driver supports the &DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE and\n * &DRM_MODE_PAGE_FLIP_TARGET_RELATIVE flags in\n * &drm_mode_crtc_page_flip_target.flags for the &DRM_IOCTL_MODE_PAGE_FLIP\n * ioctl.\n */\n#define DRM_CAP_PAGE_FLIP_TARGET\t0x11\n/**\n * DRM_CAP_CRTC_IN_VBLANK_EVENT\n *\n * If set to 1, the kernel supports reporting the CRTC ID in\n * &drm_event_vblank.crtc_id for the &DRM_EVENT_VBLANK and\n * &DRM_EVENT_FLIP_COMPLETE events.\n *\n * Starting kernel version 4.12, this capability is always set to 1.\n */\n#define DRM_CAP_CRTC_IN_VBLANK_EVENT\t0x12\n/**\n * DRM_CAP_SYNCOBJ\n *\n * If set to 1, the driver supports sync objects. See :ref:`drm_sync_objects`.\n */\n#define DRM_CAP_SYNCOBJ\t\t0x13\n/**\n * DRM_CAP_SYNCOBJ_TIMELINE\n *\n * If set to 1, the driver supports timeline operations on sync objects. See\n * :ref:`drm_sync_objects`.\n */\n#define DRM_CAP_SYNCOBJ_TIMELINE\t0x14\n\n/* DRM_IOCTL_GET_CAP ioctl argument type */\nstruct drm_get_cap {\n\t__u64 capability;\n\t__u64 value;\n};\n\n/**\n * DRM_CLIENT_CAP_STEREO_3D\n *\n * If set to 1, the DRM core will expose the stereo 3D capabilities of the\n * monitor by advertising the supported 3D layouts in the flags of struct\n * drm_mode_modeinfo. See ``DRM_MODE_FLAG_3D_*``.\n *\n * This capability is always supported for all drivers starting from kernel\n * version 3.13.\n */\n#define DRM_CLIENT_CAP_STEREO_3D\t1\n\n/**\n * DRM_CLIENT_CAP_UNIVERSAL_PLANES\n *\n * If set to 1, the DRM core will expose all planes (overlay, primary, and\n * cursor) to userspace.\n *\n * This capability has been introduced in kernel version 3.15. Starting from\n * kernel version 3.17, this capability is always supported for all drivers.\n */\n#define DRM_CLIENT_CAP_UNIVERSAL_PLANES  2\n\n/**\n * DRM_CLIENT_CAP_ATOMIC\n *\n * If set to 1, the DRM core will expose atomic properties to userspace. This\n * implicitly enables &DRM_CLIENT_CAP_UNIVERSAL_PLANES and\n * &DRM_CLIENT_CAP_ASPECT_RATIO.\n *\n * If the driver doesn't support atomic mode-setting, enabling this capability\n * will fail with -EOPNOTSUPP.\n *\n * This capability has been introduced in kernel version 4.0. Starting from\n * kernel version 4.2, this capability is always supported for atomic-capable\n * drivers.\n */\n#define DRM_CLIENT_CAP_ATOMIC\t3\n\n/**\n * DRM_CLIENT_CAP_ASPECT_RATIO\n *\n * If set to 1, the DRM core will provide aspect ratio information in modes.\n * See ``DRM_MODE_FLAG_PIC_AR_*``.\n *\n * This capability is always supported for all drivers starting from kernel\n * version 4.18.\n */\n#define DRM_CLIENT_CAP_ASPECT_RATIO    4\n\n/**\n * DRM_CLIENT_CAP_WRITEBACK_CONNECTORS\n *\n * If set to 1, the DRM core will expose special connectors to be used for\n * writing back to memory the scene setup in the commit. The client must enable\n * &DRM_CLIENT_CAP_ATOMIC first.\n *\n * This capability is always supported for atomic-capable drivers starting from\n * kernel version 4.19.\n */\n#define DRM_CLIENT_CAP_WRITEBACK_CONNECTORS\t5\n\n/* DRM_IOCTL_SET_CLIENT_CAP ioctl argument type */\nstruct drm_set_client_cap {\n\t__u64 capability;\n\t__u64 value;\n};\n\n#define DRM_RDWR O_RDWR\n#define DRM_CLOEXEC O_CLOEXEC\nstruct drm_prime_handle {\n\t__u32 handle;\n\n\t/** Flags.. only applicable for handle->fd */\n\t__u32 flags;\n\n\t/** Returned dmabuf file descriptor */\n\t__s32 fd;\n};\n\nstruct drm_syncobj_create {\n\t__u32 handle;\n#define DRM_SYNCOBJ_CREATE_SIGNALED (1 << 0)\n\t__u32 flags;\n};\n\nstruct drm_syncobj_destroy {\n\t__u32 handle;\n\t__u32 pad;\n};\n\n#define DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE (1 << 0)\n#define DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE (1 << 0)\nstruct drm_syncobj_handle {\n\t__u32 handle;\n\t__u32 flags;\n\n\t__s32 fd;\n\t__u32 pad;\n};\n\nstruct drm_syncobj_transfer {\n\t__u32 src_handle;\n\t__u32 dst_handle;\n\t__u64 src_point;\n\t__u64 dst_point;\n\t__u32 flags;\n\t__u32 pad;\n};\n\n#define DRM_SYNCOBJ_WAIT_FLAGS_WAIT_ALL (1 << 0)\n#define DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT (1 << 1)\n#define DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE (1 << 2) /* wait for time point to become available */\nstruct drm_syncobj_wait {\n\t__u64 handles;\n\t/* absolute timeout */\n\t__s64 timeout_nsec;\n\t__u32 count_handles;\n\t__u32 flags;\n\t__u32 first_signaled; /* only valid when not waiting all */\n\t__u32 pad;\n};\n\nstruct drm_syncobj_timeline_wait {\n\t__u64 handles;\n\t/* wait on specific timeline point for every handles*/\n\t__u64 points;\n\t/* absolute timeout */\n\t__s64 timeout_nsec;\n\t__u32 count_handles;\n\t__u32 flags;\n\t__u32 first_signaled; /* only valid when not waiting all */\n\t__u32 pad;\n};\n\n/**\n * struct drm_syncobj_eventfd\n * @handle: syncobj handle.\n * @flags: Zero to wait for the point to be signalled, or\n *         &DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE to wait for a fence to be\n *         available for the point.\n * @point: syncobj timeline point (set to zero for binary syncobjs).\n * @fd: Existing eventfd to sent events to.\n * @pad: Must be zero.\n *\n * Register an eventfd to be signalled by a syncobj. The eventfd counter will\n * be incremented by one.\n */\nstruct drm_syncobj_eventfd {\n\t__u32 handle;\n\t__u32 flags;\n\t__u64 point;\n\t__s32 fd;\n\t__u32 pad;\n};\n\n\nstruct drm_syncobj_array {\n\t__u64 handles;\n\t__u32 count_handles;\n\t__u32 pad;\n};\n\n#define DRM_SYNCOBJ_QUERY_FLAGS_LAST_SUBMITTED (1 << 0) /* last available point on timeline syncobj */\nstruct drm_syncobj_timeline_array {\n\t__u64 handles;\n\t__u64 points;\n\t__u32 count_handles;\n\t__u32 flags;\n};\n\n\n/* Query current scanout sequence number */\nstruct drm_crtc_get_sequence {\n\t__u32 crtc_id;\t\t/* requested crtc_id */\n\t__u32 active;\t\t/* return: crtc output is active */\n\t__u64 sequence;\t\t/* return: most recent vblank sequence */\n\t__s64 sequence_ns;\t/* return: most recent time of first pixel out */\n};\n\n/* Queue event to be delivered at specified sequence. Time stamp marks\n * when the first pixel of the refresh cycle leaves the display engine\n * for the display\n */\n#define DRM_CRTC_SEQUENCE_RELATIVE\t\t0x00000001\t/* sequence is relative to current */\n#define DRM_CRTC_SEQUENCE_NEXT_ON_MISS\t\t0x00000002\t/* Use next sequence if we've missed */\n\nstruct drm_crtc_queue_sequence {\n\t__u32 crtc_id;\n\t__u32 flags;\n\t__u64 sequence;\t\t/* on input, target sequence. on output, actual sequence */\n\t__u64 user_data;\t/* user data passed to event */\n};\n\n#if defined(__cplusplus)\n}\n#endif\n\n#include \"drm_mode.h\"\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\n#define DRM_IOCTL_BASE\t\t\t'd'\n#define DRM_IO(nr)\t\t\t_IO(DRM_IOCTL_BASE,nr)\n#define DRM_IOR(nr,type)\t\t_IOR(DRM_IOCTL_BASE,nr,type)\n#define DRM_IOW(nr,type)\t\t_IOW(DRM_IOCTL_BASE,nr,type)\n#define DRM_IOWR(nr,type)\t\t_IOWR(DRM_IOCTL_BASE,nr,type)\n\n#define DRM_IOCTL_VERSION\t\tDRM_IOWR(0x00, struct drm_version)\n#define DRM_IOCTL_GET_UNIQUE\t\tDRM_IOWR(0x01, struct drm_unique)\n#define DRM_IOCTL_GET_MAGIC\t\tDRM_IOR( 0x02, struct drm_auth)\n#define DRM_IOCTL_IRQ_BUSID\t\tDRM_IOWR(0x03, struct drm_irq_busid)\n#define DRM_IOCTL_GET_MAP               DRM_IOWR(0x04, struct drm_map)\n#define DRM_IOCTL_GET_CLIENT            DRM_IOWR(0x05, struct drm_client)\n#define DRM_IOCTL_GET_STATS             DRM_IOR( 0x06, struct drm_stats)\n#define DRM_IOCTL_SET_VERSION\t\tDRM_IOWR(0x07, struct drm_set_version)\n#define DRM_IOCTL_MODESET_CTL           DRM_IOW(0x08, struct drm_modeset_ctl)\n/**\n * DRM_IOCTL_GEM_CLOSE - Close a GEM handle.\n *\n * GEM handles are not reference-counted by the kernel. User-space is\n * responsible for managing their lifetime. For example, if user-space imports\n * the same memory object twice on the same DRM file description, the same GEM\n * handle is returned by both imports, and user-space needs to ensure\n * &DRM_IOCTL_GEM_CLOSE is performed once only. The same situation can happen\n * when a memory object is allocated, then exported and imported again on the\n * same DRM file description. The &DRM_IOCTL_MODE_GETFB2 IOCTL is an exception\n * and always returns fresh new GEM handles even if an existing GEM handle\n * already refers to the same memory object before the IOCTL is performed.\n */\n#define DRM_IOCTL_GEM_CLOSE\t\tDRM_IOW (0x09, struct drm_gem_close)\n#define DRM_IOCTL_GEM_FLINK\t\tDRM_IOWR(0x0a, struct drm_gem_flink)\n#define DRM_IOCTL_GEM_OPEN\t\tDRM_IOWR(0x0b, struct drm_gem_open)\n#define DRM_IOCTL_GET_CAP\t\tDRM_IOWR(0x0c, struct drm_get_cap)\n#define DRM_IOCTL_SET_CLIENT_CAP\tDRM_IOW( 0x0d, struct drm_set_client_cap)\n\n#define DRM_IOCTL_SET_UNIQUE\t\tDRM_IOW( 0x10, struct drm_unique)\n#define DRM_IOCTL_AUTH_MAGIC\t\tDRM_IOW( 0x11, struct drm_auth)\n#define DRM_IOCTL_BLOCK\t\t\tDRM_IOWR(0x12, struct drm_block)\n#define DRM_IOCTL_UNBLOCK\t\tDRM_IOWR(0x13, struct drm_block)\n#define DRM_IOCTL_CONTROL\t\tDRM_IOW( 0x14, struct drm_control)\n#define DRM_IOCTL_ADD_MAP\t\tDRM_IOWR(0x15, struct drm_map)\n#define DRM_IOCTL_ADD_BUFS\t\tDRM_IOWR(0x16, struct drm_buf_desc)\n#define DRM_IOCTL_MARK_BUFS\t\tDRM_IOW( 0x17, struct drm_buf_desc)\n#define DRM_IOCTL_INFO_BUFS\t\tDRM_IOWR(0x18, struct drm_buf_info)\n#define DRM_IOCTL_MAP_BUFS\t\tDRM_IOWR(0x19, struct drm_buf_map)\n#define DRM_IOCTL_FREE_BUFS\t\tDRM_IOW( 0x1a, struct drm_buf_free)\n\n#define DRM_IOCTL_RM_MAP\t\tDRM_IOW( 0x1b, struct drm_map)\n\n#define DRM_IOCTL_SET_SAREA_CTX\t\tDRM_IOW( 0x1c, struct drm_ctx_priv_map)\n#define DRM_IOCTL_GET_SAREA_CTX \tDRM_IOWR(0x1d, struct drm_ctx_priv_map)\n\n#define DRM_IOCTL_SET_MASTER            DRM_IO(0x1e)\n#define DRM_IOCTL_DROP_MASTER           DRM_IO(0x1f)\n\n#define DRM_IOCTL_ADD_CTX\t\tDRM_IOWR(0x20, struct drm_ctx)\n#define DRM_IOCTL_RM_CTX\t\tDRM_IOWR(0x21, struct drm_ctx)\n#define DRM_IOCTL_MOD_CTX\t\tDRM_IOW( 0x22, struct drm_ctx)\n#define DRM_IOCTL_GET_CTX\t\tDRM_IOWR(0x23, struct drm_ctx)\n#define DRM_IOCTL_SWITCH_CTX\t\tDRM_IOW( 0x24, struct drm_ctx)\n#define DRM_IOCTL_NEW_CTX\t\tDRM_IOW( 0x25, struct drm_ctx)\n#define DRM_IOCTL_RES_CTX\t\tDRM_IOWR(0x26, struct drm_ctx_res)\n#define DRM_IOCTL_ADD_DRAW\t\tDRM_IOWR(0x27, struct drm_draw)\n#define DRM_IOCTL_RM_DRAW\t\tDRM_IOWR(0x28, struct drm_draw)\n#define DRM_IOCTL_DMA\t\t\tDRM_IOWR(0x29, struct drm_dma)\n#define DRM_IOCTL_LOCK\t\t\tDRM_IOW( 0x2a, struct drm_lock)\n#define DRM_IOCTL_UNLOCK\t\tDRM_IOW( 0x2b, struct drm_lock)\n#define DRM_IOCTL_FINISH\t\tDRM_IOW( 0x2c, struct drm_lock)\n\n/**\n * DRM_IOCTL_PRIME_HANDLE_TO_FD - Convert a GEM handle to a DMA-BUF FD.\n *\n * User-space sets &drm_prime_handle.handle with the GEM handle to export and\n * &drm_prime_handle.flags, and gets back a DMA-BUF file descriptor in\n * &drm_prime_handle.fd.\n *\n * The export can fail for any driver-specific reason, e.g. because export is\n * not supported for this specific GEM handle (but might be for others).\n *\n * Support for exporting DMA-BUFs is advertised via &DRM_PRIME_CAP_EXPORT.\n */\n#define DRM_IOCTL_PRIME_HANDLE_TO_FD    DRM_IOWR(0x2d, struct drm_prime_handle)\n/**\n * DRM_IOCTL_PRIME_FD_TO_HANDLE - Convert a DMA-BUF FD to a GEM handle.\n *\n * User-space sets &drm_prime_handle.fd with a DMA-BUF file descriptor to\n * import, and gets back a GEM handle in &drm_prime_handle.handle.\n * &drm_prime_handle.flags is unused.\n *\n * If an existing GEM handle refers to the memory object backing the DMA-BUF,\n * that GEM handle is returned. Therefore user-space which needs to handle\n * arbitrary DMA-BUFs must have a user-space lookup data structure to manually\n * reference-count duplicated GEM handles. For more information see\n * &DRM_IOCTL_GEM_CLOSE.\n *\n * The import can fail for any driver-specific reason, e.g. because import is\n * only supported for DMA-BUFs allocated on this DRM device.\n *\n * Support for importing DMA-BUFs is advertised via &DRM_PRIME_CAP_IMPORT.\n */\n#define DRM_IOCTL_PRIME_FD_TO_HANDLE    DRM_IOWR(0x2e, struct drm_prime_handle)\n\n#define DRM_IOCTL_AGP_ACQUIRE\t\tDRM_IO(  0x30)\n#define DRM_IOCTL_AGP_RELEASE\t\tDRM_IO(  0x31)\n#define DRM_IOCTL_AGP_ENABLE\t\tDRM_IOW( 0x32, struct drm_agp_mode)\n#define DRM_IOCTL_AGP_INFO\t\tDRM_IOR( 0x33, struct drm_agp_info)\n#define DRM_IOCTL_AGP_ALLOC\t\tDRM_IOWR(0x34, struct drm_agp_buffer)\n#define DRM_IOCTL_AGP_FREE\t\tDRM_IOW( 0x35, struct drm_agp_buffer)\n#define DRM_IOCTL_AGP_BIND\t\tDRM_IOW( 0x36, struct drm_agp_binding)\n#define DRM_IOCTL_AGP_UNBIND\t\tDRM_IOW( 0x37, struct drm_agp_binding)\n\n#define DRM_IOCTL_SG_ALLOC\t\tDRM_IOWR(0x38, struct drm_scatter_gather)\n#define DRM_IOCTL_SG_FREE\t\tDRM_IOW( 0x39, struct drm_scatter_gather)\n\n#define DRM_IOCTL_WAIT_VBLANK\t\tDRM_IOWR(0x3a, union drm_wait_vblank)\n\n#define DRM_IOCTL_CRTC_GET_SEQUENCE\tDRM_IOWR(0x3b, struct drm_crtc_get_sequence)\n#define DRM_IOCTL_CRTC_QUEUE_SEQUENCE\tDRM_IOWR(0x3c, struct drm_crtc_queue_sequence)\n\n#define DRM_IOCTL_UPDATE_DRAW\t\tDRM_IOW(0x3f, struct drm_update_draw)\n\n#define DRM_IOCTL_MODE_GETRESOURCES\tDRM_IOWR(0xA0, struct drm_mode_card_res)\n#define DRM_IOCTL_MODE_GETCRTC\t\tDRM_IOWR(0xA1, struct drm_mode_crtc)\n#define DRM_IOCTL_MODE_SETCRTC\t\tDRM_IOWR(0xA2, struct drm_mode_crtc)\n#define DRM_IOCTL_MODE_CURSOR\t\tDRM_IOWR(0xA3, struct drm_mode_cursor)\n#define DRM_IOCTL_MODE_GETGAMMA\t\tDRM_IOWR(0xA4, struct drm_mode_crtc_lut)\n#define DRM_IOCTL_MODE_SETGAMMA\t\tDRM_IOWR(0xA5, struct drm_mode_crtc_lut)\n#define DRM_IOCTL_MODE_GETENCODER\tDRM_IOWR(0xA6, struct drm_mode_get_encoder)\n#define DRM_IOCTL_MODE_GETCONNECTOR\tDRM_IOWR(0xA7, struct drm_mode_get_connector)\n#define DRM_IOCTL_MODE_ATTACHMODE\tDRM_IOWR(0xA8, struct drm_mode_mode_cmd) /* deprecated (never worked) */\n#define DRM_IOCTL_MODE_DETACHMODE\tDRM_IOWR(0xA9, struct drm_mode_mode_cmd) /* deprecated (never worked) */\n\n#define DRM_IOCTL_MODE_GETPROPERTY\tDRM_IOWR(0xAA, struct drm_mode_get_property)\n#define DRM_IOCTL_MODE_SETPROPERTY\tDRM_IOWR(0xAB, struct drm_mode_connector_set_property)\n#define DRM_IOCTL_MODE_GETPROPBLOB\tDRM_IOWR(0xAC, struct drm_mode_get_blob)\n#define DRM_IOCTL_MODE_GETFB\t\tDRM_IOWR(0xAD, struct drm_mode_fb_cmd)\n#define DRM_IOCTL_MODE_ADDFB\t\tDRM_IOWR(0xAE, struct drm_mode_fb_cmd)\n/**\n * DRM_IOCTL_MODE_RMFB - Remove a framebuffer.\n *\n * This removes a framebuffer previously added via ADDFB/ADDFB2. The IOCTL\n * argument is a framebuffer object ID.\n *\n * Warning: removing a framebuffer currently in-use on an enabled plane will\n * disable that plane. The CRTC the plane is linked to may also be disabled\n * (depending on driver capabilities).\n */\n#define DRM_IOCTL_MODE_RMFB\t\tDRM_IOWR(0xAF, unsigned int)\n#define DRM_IOCTL_MODE_PAGE_FLIP\tDRM_IOWR(0xB0, struct drm_mode_crtc_page_flip)\n#define DRM_IOCTL_MODE_DIRTYFB\t\tDRM_IOWR(0xB1, struct drm_mode_fb_dirty_cmd)\n\n#define DRM_IOCTL_MODE_CREATE_DUMB DRM_IOWR(0xB2, struct drm_mode_create_dumb)\n#define DRM_IOCTL_MODE_MAP_DUMB    DRM_IOWR(0xB3, struct drm_mode_map_dumb)\n#define DRM_IOCTL_MODE_DESTROY_DUMB    DRM_IOWR(0xB4, struct drm_mode_destroy_dumb)\n#define DRM_IOCTL_MODE_GETPLANERESOURCES DRM_IOWR(0xB5, struct drm_mode_get_plane_res)\n#define DRM_IOCTL_MODE_GETPLANE\tDRM_IOWR(0xB6, struct drm_mode_get_plane)\n#define DRM_IOCTL_MODE_SETPLANE\tDRM_IOWR(0xB7, struct drm_mode_set_plane)\n#define DRM_IOCTL_MODE_ADDFB2\t\tDRM_IOWR(0xB8, struct drm_mode_fb_cmd2)\n#define DRM_IOCTL_MODE_OBJ_GETPROPERTIES\tDRM_IOWR(0xB9, struct drm_mode_obj_get_properties)\n#define DRM_IOCTL_MODE_OBJ_SETPROPERTY\tDRM_IOWR(0xBA, struct drm_mode_obj_set_property)\n#define DRM_IOCTL_MODE_CURSOR2\t\tDRM_IOWR(0xBB, struct drm_mode_cursor2)\n#define DRM_IOCTL_MODE_ATOMIC\t\tDRM_IOWR(0xBC, struct drm_mode_atomic)\n#define DRM_IOCTL_MODE_CREATEPROPBLOB\tDRM_IOWR(0xBD, struct drm_mode_create_blob)\n#define DRM_IOCTL_MODE_DESTROYPROPBLOB\tDRM_IOWR(0xBE, struct drm_mode_destroy_blob)\n\n#define DRM_IOCTL_SYNCOBJ_CREATE\tDRM_IOWR(0xBF, struct drm_syncobj_create)\n#define DRM_IOCTL_SYNCOBJ_DESTROY\tDRM_IOWR(0xC0, struct drm_syncobj_destroy)\n#define DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD\tDRM_IOWR(0xC1, struct drm_syncobj_handle)\n#define DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE\tDRM_IOWR(0xC2, struct drm_syncobj_handle)\n#define DRM_IOCTL_SYNCOBJ_WAIT\t\tDRM_IOWR(0xC3, struct drm_syncobj_wait)\n#define DRM_IOCTL_SYNCOBJ_RESET\t\tDRM_IOWR(0xC4, struct drm_syncobj_array)\n#define DRM_IOCTL_SYNCOBJ_SIGNAL\tDRM_IOWR(0xC5, struct drm_syncobj_array)\n\n#define DRM_IOCTL_MODE_CREATE_LEASE\tDRM_IOWR(0xC6, struct drm_mode_create_lease)\n#define DRM_IOCTL_MODE_LIST_LESSEES\tDRM_IOWR(0xC7, struct drm_mode_list_lessees)\n#define DRM_IOCTL_MODE_GET_LEASE\tDRM_IOWR(0xC8, struct drm_mode_get_lease)\n#define DRM_IOCTL_MODE_REVOKE_LEASE\tDRM_IOWR(0xC9, struct drm_mode_revoke_lease)\n\n#define DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT\tDRM_IOWR(0xCA, struct drm_syncobj_timeline_wait)\n#define DRM_IOCTL_SYNCOBJ_QUERY\t\tDRM_IOWR(0xCB, struct drm_syncobj_timeline_array)\n#define DRM_IOCTL_SYNCOBJ_TRANSFER\tDRM_IOWR(0xCC, struct drm_syncobj_transfer)\n#define DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL\tDRM_IOWR(0xCD, struct drm_syncobj_timeline_array)\n\n/**\n * DRM_IOCTL_MODE_GETFB2 - Get framebuffer metadata.\n *\n * This queries metadata about a framebuffer. User-space fills\n * &drm_mode_fb_cmd2.fb_id as the input, and the kernels fills the rest of the\n * struct as the output.\n *\n * If the client is DRM master or has &CAP_SYS_ADMIN, &drm_mode_fb_cmd2.handles\n * will be filled with GEM buffer handles. Fresh new GEM handles are always\n * returned, even if another GEM handle referring to the same memory object\n * already exists on the DRM file description. The caller is responsible for\n * removing the new handles, e.g. via the &DRM_IOCTL_GEM_CLOSE IOCTL. The same\n * new handle will be returned for multiple planes in case they use the same\n * memory object. Planes are valid until one has a zero handle -- this can be\n * used to compute the number of planes.\n *\n * Otherwise, &drm_mode_fb_cmd2.handles will be zeroed and planes are valid\n * until one has a zero &drm_mode_fb_cmd2.pitches.\n *\n * If the framebuffer has a format modifier, &DRM_MODE_FB_MODIFIERS will be set\n * in &drm_mode_fb_cmd2.flags and &drm_mode_fb_cmd2.modifier will contain the\n * modifier. Otherwise, user-space must ignore &drm_mode_fb_cmd2.modifier.\n *\n * To obtain DMA-BUF FDs for each plane without leaking GEM handles, user-space\n * can export each handle via &DRM_IOCTL_PRIME_HANDLE_TO_FD, then immediately\n * close each unique handle via &DRM_IOCTL_GEM_CLOSE, making sure to not\n * double-close handles which are specified multiple times in the array.\n */\n#define DRM_IOCTL_MODE_GETFB2\t\tDRM_IOWR(0xCE, struct drm_mode_fb_cmd2)\n\n#define DRM_IOCTL_SYNCOBJ_EVENTFD\tDRM_IOWR(0xCF, struct drm_syncobj_eventfd)\n\n/*\n * Device specific ioctls should only be in their respective headers\n * The device specific ioctl range is from 0x40 to 0x9f.\n * Generic IOCTLS restart at 0xA0.\n *\n * \\sa drmCommandNone(), drmCommandRead(), drmCommandWrite(), and\n * drmCommandReadWrite().\n */\n#define DRM_COMMAND_BASE                0x40\n#define DRM_COMMAND_END\t\t\t0xA0\n\n/**\n * struct drm_event - Header for DRM events\n * @type: event type.\n * @length: total number of payload bytes (including header).\n *\n * This struct is a header for events written back to user-space on the DRM FD.\n * A read on the DRM FD will always only return complete events: e.g. if the\n * read buffer is 100 bytes large and there are two 64 byte events pending,\n * only one will be returned.\n *\n * Event types 0 - 0x7fffffff are generic DRM events, 0x80000000 and\n * up are chipset specific. Generic DRM events include &DRM_EVENT_VBLANK,\n * &DRM_EVENT_FLIP_COMPLETE and &DRM_EVENT_CRTC_SEQUENCE.\n */\nstruct drm_event {\n\t__u32 type;\n\t__u32 length;\n};\n\n/**\n * DRM_EVENT_VBLANK - vertical blanking event\n *\n * This event is sent in response to &DRM_IOCTL_WAIT_VBLANK with the\n * &_DRM_VBLANK_EVENT flag set.\n *\n * The event payload is a struct drm_event_vblank.\n */\n#define DRM_EVENT_VBLANK 0x01\n/**\n * DRM_EVENT_FLIP_COMPLETE - page-flip completion event\n *\n * This event is sent in response to an atomic commit or legacy page-flip with\n * the &DRM_MODE_PAGE_FLIP_EVENT flag set.\n *\n * The event payload is a struct drm_event_vblank.\n */\n#define DRM_EVENT_FLIP_COMPLETE 0x02\n/**\n * DRM_EVENT_CRTC_SEQUENCE - CRTC sequence event\n *\n * This event is sent in response to &DRM_IOCTL_CRTC_QUEUE_SEQUENCE.\n *\n * The event payload is a struct drm_event_crtc_sequence.\n */\n#define DRM_EVENT_CRTC_SEQUENCE\t0x03\n\nstruct drm_event_vblank {\n\tstruct drm_event base;\n\t__u64 user_data;\n\t__u32 tv_sec;\n\t__u32 tv_usec;\n\t__u32 sequence;\n\t__u32 crtc_id; /* 0 on older kernels that do not support this */\n};\n\n/* Event delivered at sequence. Time stamp marks when the first pixel\n * of the refresh cycle leaves the display engine for the display\n */\nstruct drm_event_crtc_sequence {\n\tstruct drm_event\tbase;\n\t__u64\t\t\tuser_data;\n\t__s64\t\t\ttime_ns;\n\t__u64\t\t\tsequence;\n};\n\n/* typedef area */\ntypedef struct drm_clip_rect drm_clip_rect_t;\ntypedef struct drm_drawable_info drm_drawable_info_t;\ntypedef struct drm_tex_region drm_tex_region_t;\ntypedef struct drm_hw_lock drm_hw_lock_t;\ntypedef struct drm_version drm_version_t;\ntypedef struct drm_unique drm_unique_t;\ntypedef struct drm_list drm_list_t;\ntypedef struct drm_block drm_block_t;\ntypedef struct drm_control drm_control_t;\ntypedef enum drm_map_type drm_map_type_t;\ntypedef enum drm_map_flags drm_map_flags_t;\ntypedef struct drm_ctx_priv_map drm_ctx_priv_map_t;\ntypedef struct drm_map drm_map_t;\ntypedef struct drm_client drm_client_t;\ntypedef enum drm_stat_type drm_stat_type_t;\ntypedef struct drm_stats drm_stats_t;\ntypedef enum drm_lock_flags drm_lock_flags_t;\ntypedef struct drm_lock drm_lock_t;\ntypedef enum drm_dma_flags drm_dma_flags_t;\ntypedef struct drm_buf_desc drm_buf_desc_t;\ntypedef struct drm_buf_info drm_buf_info_t;\ntypedef struct drm_buf_free drm_buf_free_t;\ntypedef struct drm_buf_pub drm_buf_pub_t;\ntypedef struct drm_buf_map drm_buf_map_t;\ntypedef struct drm_dma drm_dma_t;\ntypedef union drm_wait_vblank drm_wait_vblank_t;\ntypedef struct drm_agp_mode drm_agp_mode_t;\ntypedef enum drm_ctx_flags drm_ctx_flags_t;\ntypedef struct drm_ctx drm_ctx_t;\ntypedef struct drm_ctx_res drm_ctx_res_t;\ntypedef struct drm_draw drm_draw_t;\ntypedef struct drm_update_draw drm_update_draw_t;\ntypedef struct drm_auth drm_auth_t;\ntypedef struct drm_irq_busid drm_irq_busid_t;\ntypedef enum drm_vblank_seq_type drm_vblank_seq_type_t;\n\ntypedef struct drm_agp_buffer drm_agp_buffer_t;\ntypedef struct drm_agp_binding drm_agp_binding_t;\ntypedef struct drm_agp_info drm_agp_info_t;\ntypedef struct drm_scatter_gather drm_scatter_gather_t;\ntypedef struct drm_set_version drm_set_version_t;\n\n#if defined(__cplusplus)\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "src/linux/intel_gpu_top/drm_mode.h",
    "content": "/*\n * Copyright (c) 2007 Dave Airlie <airlied@linux.ie>\n * Copyright (c) 2007 Jakob Bornecrantz <wallbraker@gmail.com>\n * Copyright (c) 2008 Red Hat Inc.\n * Copyright (c) 2007-2008 Tungsten Graphics, Inc., Cedar Park, TX., USA\n * Copyright (c) 2007-2008 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n */\n\n#ifndef _DRM_MODE_H\n#define _DRM_MODE_H\n\n#include \"drm.h\"\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\n/**\n * DOC: overview\n *\n * DRM exposes many UAPI and structure definition to have a consistent\n * and standardized interface with user.\n * Userspace can refer to these structure definitions and UAPI formats\n * to communicate to driver\n */\n\n#define DRM_CONNECTOR_NAME_LEN\t32\n#define DRM_DISPLAY_MODE_LEN\t32\n#define DRM_PROP_NAME_LEN\t32\n\n#define DRM_MODE_TYPE_BUILTIN\t(1<<0) /* deprecated */\n#define DRM_MODE_TYPE_CLOCK_C\t((1<<1) | DRM_MODE_TYPE_BUILTIN) /* deprecated */\n#define DRM_MODE_TYPE_CRTC_C\t((1<<2) | DRM_MODE_TYPE_BUILTIN) /* deprecated */\n#define DRM_MODE_TYPE_PREFERRED\t(1<<3)\n#define DRM_MODE_TYPE_DEFAULT\t(1<<4) /* deprecated */\n#define DRM_MODE_TYPE_USERDEF\t(1<<5)\n#define DRM_MODE_TYPE_DRIVER\t(1<<6)\n\n#define DRM_MODE_TYPE_ALL\t(DRM_MODE_TYPE_PREFERRED |\t\\\n\t\t\t\t DRM_MODE_TYPE_USERDEF |\t\\\n\t\t\t\t DRM_MODE_TYPE_DRIVER)\n\n/* Video mode flags */\n/* bit compatible with the xrandr RR_ definitions (bits 0-13)\n *\n * ABI warning: Existing userspace really expects\n * the mode flags to match the xrandr definitions. Any\n * changes that don't match the xrandr definitions will\n * likely need a new client cap or some other mechanism\n * to avoid breaking existing userspace. This includes\n * allocating new flags in the previously unused bits!\n */\n#define DRM_MODE_FLAG_PHSYNC\t\t\t(1<<0)\n#define DRM_MODE_FLAG_NHSYNC\t\t\t(1<<1)\n#define DRM_MODE_FLAG_PVSYNC\t\t\t(1<<2)\n#define DRM_MODE_FLAG_NVSYNC\t\t\t(1<<3)\n#define DRM_MODE_FLAG_INTERLACE\t\t\t(1<<4)\n#define DRM_MODE_FLAG_DBLSCAN\t\t\t(1<<5)\n#define DRM_MODE_FLAG_CSYNC\t\t\t(1<<6)\n#define DRM_MODE_FLAG_PCSYNC\t\t\t(1<<7)\n#define DRM_MODE_FLAG_NCSYNC\t\t\t(1<<8)\n#define DRM_MODE_FLAG_HSKEW\t\t\t(1<<9) /* hskew provided */\n#define DRM_MODE_FLAG_BCAST\t\t\t(1<<10) /* deprecated */\n#define DRM_MODE_FLAG_PIXMUX\t\t\t(1<<11) /* deprecated */\n#define DRM_MODE_FLAG_DBLCLK\t\t\t(1<<12)\n#define DRM_MODE_FLAG_CLKDIV2\t\t\t(1<<13)\n /*\n  * When adding a new stereo mode don't forget to adjust DRM_MODE_FLAGS_3D_MAX\n  * (define not exposed to user space).\n  */\n#define DRM_MODE_FLAG_3D_MASK\t\t\t(0x1f<<14)\n#define  DRM_MODE_FLAG_3D_NONE\t\t(0<<14)\n#define  DRM_MODE_FLAG_3D_FRAME_PACKING\t\t(1<<14)\n#define  DRM_MODE_FLAG_3D_FIELD_ALTERNATIVE\t(2<<14)\n#define  DRM_MODE_FLAG_3D_LINE_ALTERNATIVE\t(3<<14)\n#define  DRM_MODE_FLAG_3D_SIDE_BY_SIDE_FULL\t(4<<14)\n#define  DRM_MODE_FLAG_3D_L_DEPTH\t\t(5<<14)\n#define  DRM_MODE_FLAG_3D_L_DEPTH_GFX_GFX_DEPTH\t(6<<14)\n#define  DRM_MODE_FLAG_3D_TOP_AND_BOTTOM\t(7<<14)\n#define  DRM_MODE_FLAG_3D_SIDE_BY_SIDE_HALF\t(8<<14)\n\n/* Picture aspect ratio options */\n#define DRM_MODE_PICTURE_ASPECT_NONE\t\t0\n#define DRM_MODE_PICTURE_ASPECT_4_3\t\t1\n#define DRM_MODE_PICTURE_ASPECT_16_9\t\t2\n#define DRM_MODE_PICTURE_ASPECT_64_27\t\t3\n#define DRM_MODE_PICTURE_ASPECT_256_135\t\t4\n\n/* Content type options */\n#define DRM_MODE_CONTENT_TYPE_NO_DATA\t\t0\n#define DRM_MODE_CONTENT_TYPE_GRAPHICS\t\t1\n#define DRM_MODE_CONTENT_TYPE_PHOTO\t\t2\n#define DRM_MODE_CONTENT_TYPE_CINEMA\t\t3\n#define DRM_MODE_CONTENT_TYPE_GAME\t\t4\n\n/* Aspect ratio flag bitmask (4 bits 22:19) */\n#define DRM_MODE_FLAG_PIC_AR_MASK\t\t(0x0F<<19)\n#define  DRM_MODE_FLAG_PIC_AR_NONE \\\n\t\t\t(DRM_MODE_PICTURE_ASPECT_NONE<<19)\n#define  DRM_MODE_FLAG_PIC_AR_4_3 \\\n\t\t\t(DRM_MODE_PICTURE_ASPECT_4_3<<19)\n#define  DRM_MODE_FLAG_PIC_AR_16_9 \\\n\t\t\t(DRM_MODE_PICTURE_ASPECT_16_9<<19)\n#define  DRM_MODE_FLAG_PIC_AR_64_27 \\\n\t\t\t(DRM_MODE_PICTURE_ASPECT_64_27<<19)\n#define  DRM_MODE_FLAG_PIC_AR_256_135 \\\n\t\t\t(DRM_MODE_PICTURE_ASPECT_256_135<<19)\n\n#define  DRM_MODE_FLAG_ALL\t(DRM_MODE_FLAG_PHSYNC |\t\t\\\n\t\t\t\t DRM_MODE_FLAG_NHSYNC |\t\t\\\n\t\t\t\t DRM_MODE_FLAG_PVSYNC |\t\t\\\n\t\t\t\t DRM_MODE_FLAG_NVSYNC |\t\t\\\n\t\t\t\t DRM_MODE_FLAG_INTERLACE |\t\\\n\t\t\t\t DRM_MODE_FLAG_DBLSCAN |\t\\\n\t\t\t\t DRM_MODE_FLAG_CSYNC |\t\t\\\n\t\t\t\t DRM_MODE_FLAG_PCSYNC |\t\t\\\n\t\t\t\t DRM_MODE_FLAG_NCSYNC |\t\t\\\n\t\t\t\t DRM_MODE_FLAG_HSKEW |\t\t\\\n\t\t\t\t DRM_MODE_FLAG_DBLCLK |\t\t\\\n\t\t\t\t DRM_MODE_FLAG_CLKDIV2 |\t\\\n\t\t\t\t DRM_MODE_FLAG_3D_MASK)\n\n/* DPMS flags */\n/* bit compatible with the xorg definitions. */\n#define DRM_MODE_DPMS_ON\t0\n#define DRM_MODE_DPMS_STANDBY\t1\n#define DRM_MODE_DPMS_SUSPEND\t2\n#define DRM_MODE_DPMS_OFF\t3\n\n/* Scaling mode options */\n#define DRM_MODE_SCALE_NONE\t\t0 /* Unmodified timing (display or\n\t\t\t\t\t     software can still scale) */\n#define DRM_MODE_SCALE_FULLSCREEN\t1 /* Full screen, ignore aspect */\n#define DRM_MODE_SCALE_CENTER\t\t2 /* Centered, no scaling */\n#define DRM_MODE_SCALE_ASPECT\t\t3 /* Full screen, preserve aspect */\n\n/* Dithering mode options */\n#define DRM_MODE_DITHERING_OFF\t0\n#define DRM_MODE_DITHERING_ON\t1\n#define DRM_MODE_DITHERING_AUTO 2\n\n/* Dirty info options */\n#define DRM_MODE_DIRTY_OFF      0\n#define DRM_MODE_DIRTY_ON       1\n#define DRM_MODE_DIRTY_ANNOTATE 2\n\n/* Link Status options */\n#define DRM_MODE_LINK_STATUS_GOOD\t0\n#define DRM_MODE_LINK_STATUS_BAD\t1\n\n/*\n * DRM_MODE_ROTATE_<degrees>\n *\n * Signals that a drm plane is been rotated <degrees> degrees in counter\n * clockwise direction.\n *\n * This define is provided as a convenience, looking up the property id\n * using the name->prop id lookup is the preferred method.\n */\n#define DRM_MODE_ROTATE_0       (1<<0)\n#define DRM_MODE_ROTATE_90      (1<<1)\n#define DRM_MODE_ROTATE_180     (1<<2)\n#define DRM_MODE_ROTATE_270     (1<<3)\n\n/*\n * DRM_MODE_ROTATE_MASK\n *\n * Bitmask used to look for drm plane rotations.\n */\n#define DRM_MODE_ROTATE_MASK (\\\n\t\tDRM_MODE_ROTATE_0  | \\\n\t\tDRM_MODE_ROTATE_90  | \\\n\t\tDRM_MODE_ROTATE_180 | \\\n\t\tDRM_MODE_ROTATE_270)\n\n/*\n * DRM_MODE_REFLECT_<axis>\n *\n * Signals that the contents of a drm plane is reflected along the <axis> axis,\n * in the same way as mirroring.\n * See kerneldoc chapter \"Plane Composition Properties\" for more details.\n *\n * This define is provided as a convenience, looking up the property id\n * using the name->prop id lookup is the preferred method.\n */\n#define DRM_MODE_REFLECT_X      (1<<4)\n#define DRM_MODE_REFLECT_Y      (1<<5)\n\n/*\n * DRM_MODE_REFLECT_MASK\n *\n * Bitmask used to look for drm plane reflections.\n */\n#define DRM_MODE_REFLECT_MASK (\\\n\t\tDRM_MODE_REFLECT_X | \\\n\t\tDRM_MODE_REFLECT_Y)\n\n/* Content Protection Flags */\n#define DRM_MODE_CONTENT_PROTECTION_UNDESIRED\t0\n#define DRM_MODE_CONTENT_PROTECTION_DESIRED     1\n#define DRM_MODE_CONTENT_PROTECTION_ENABLED     2\n\n/**\n * struct drm_mode_modeinfo - Display mode information.\n * @clock: pixel clock in kHz\n * @hdisplay: horizontal display size\n * @hsync_start: horizontal sync start\n * @hsync_end: horizontal sync end\n * @htotal: horizontal total size\n * @hskew: horizontal skew\n * @vdisplay: vertical display size\n * @vsync_start: vertical sync start\n * @vsync_end: vertical sync end\n * @vtotal: vertical total size\n * @vscan: vertical scan\n * @vrefresh: approximate vertical refresh rate in Hz\n * @flags: bitmask of misc. flags, see DRM_MODE_FLAG_* defines\n * @type: bitmask of type flags, see DRM_MODE_TYPE_* defines\n * @name: string describing the mode resolution\n *\n * This is the user-space API display mode information structure. For the\n * kernel version see struct drm_display_mode.\n */\nstruct drm_mode_modeinfo {\n\t__u32 clock;\n\t__u16 hdisplay;\n\t__u16 hsync_start;\n\t__u16 hsync_end;\n\t__u16 htotal;\n\t__u16 hskew;\n\t__u16 vdisplay;\n\t__u16 vsync_start;\n\t__u16 vsync_end;\n\t__u16 vtotal;\n\t__u16 vscan;\n\n\t__u32 vrefresh;\n\n\t__u32 flags;\n\t__u32 type;\n\tchar name[DRM_DISPLAY_MODE_LEN];\n};\n\nstruct drm_mode_card_res {\n\t__u64 fb_id_ptr;\n\t__u64 crtc_id_ptr;\n\t__u64 connector_id_ptr;\n\t__u64 encoder_id_ptr;\n\t__u32 count_fbs;\n\t__u32 count_crtcs;\n\t__u32 count_connectors;\n\t__u32 count_encoders;\n\t__u32 min_width;\n\t__u32 max_width;\n\t__u32 min_height;\n\t__u32 max_height;\n};\n\nstruct drm_mode_crtc {\n\t__u64 set_connectors_ptr;\n\t__u32 count_connectors;\n\n\t__u32 crtc_id; /**< Id */\n\t__u32 fb_id; /**< Id of framebuffer */\n\n\t__u32 x; /**< x Position on the framebuffer */\n\t__u32 y; /**< y Position on the framebuffer */\n\n\t__u32 gamma_size;\n\t__u32 mode_valid;\n\tstruct drm_mode_modeinfo mode;\n};\n\n#define DRM_MODE_PRESENT_TOP_FIELD\t(1<<0)\n#define DRM_MODE_PRESENT_BOTTOM_FIELD\t(1<<1)\n\n/* Planes blend with or override other bits on the CRTC */\nstruct drm_mode_set_plane {\n\t__u32 plane_id;\n\t__u32 crtc_id;\n\t__u32 fb_id; /* fb object contains surface format type */\n\t__u32 flags; /* see above flags */\n\n\t/* Signed dest location allows it to be partially off screen */\n\t__s32 crtc_x;\n\t__s32 crtc_y;\n\t__u32 crtc_w;\n\t__u32 crtc_h;\n\n\t/* Source values are 16.16 fixed point */\n\t__u32 src_x;\n\t__u32 src_y;\n\t__u32 src_h;\n\t__u32 src_w;\n};\n\n/**\n * struct drm_mode_get_plane - Get plane metadata.\n *\n * Userspace can perform a GETPLANE ioctl to retrieve information about a\n * plane.\n *\n * To retrieve the number of formats supported, set @count_format_types to zero\n * and call the ioctl. @count_format_types will be updated with the value.\n *\n * To retrieve these formats, allocate an array with the memory needed to store\n * @count_format_types formats. Point @format_type_ptr to this array and call\n * the ioctl again (with @count_format_types still set to the value returned in\n * the first ioctl call).\n */\nstruct drm_mode_get_plane {\n\t/**\n\t * @plane_id: Object ID of the plane whose information should be\n\t * retrieved. Set by caller.\n\t */\n\t__u32 plane_id;\n\n\t/** @crtc_id: Object ID of the current CRTC. */\n\t__u32 crtc_id;\n\t/** @fb_id: Object ID of the current fb. */\n\t__u32 fb_id;\n\n\t/**\n\t * @possible_crtcs: Bitmask of CRTC's compatible with the plane. CRTC's\n\t * are created and they receive an index, which corresponds to their\n\t * position in the bitmask. Bit N corresponds to\n\t * :ref:`CRTC index<crtc_index>` N.\n\t */\n\t__u32 possible_crtcs;\n\t/** @gamma_size: Never used. */\n\t__u32 gamma_size;\n\n\t/** @count_format_types: Number of formats. */\n\t__u32 count_format_types;\n\t/**\n\t * @format_type_ptr: Pointer to ``__u32`` array of formats that are\n\t * supported by the plane. These formats do not require modifiers.\n\t */\n\t__u64 format_type_ptr;\n};\n\nstruct drm_mode_get_plane_res {\n\t__u64 plane_id_ptr;\n\t__u32 count_planes;\n};\n\n#define DRM_MODE_ENCODER_NONE\t0\n#define DRM_MODE_ENCODER_DAC\t1\n#define DRM_MODE_ENCODER_TMDS\t2\n#define DRM_MODE_ENCODER_LVDS\t3\n#define DRM_MODE_ENCODER_TVDAC\t4\n#define DRM_MODE_ENCODER_VIRTUAL 5\n#define DRM_MODE_ENCODER_DSI\t6\n#define DRM_MODE_ENCODER_DPMST\t7\n#define DRM_MODE_ENCODER_DPI\t8\n\nstruct drm_mode_get_encoder {\n\t__u32 encoder_id;\n\t__u32 encoder_type;\n\n\t__u32 crtc_id; /**< Id of crtc */\n\n\t__u32 possible_crtcs;\n\t__u32 possible_clones;\n};\n\n/* This is for connectors with multiple signal types. */\n/* Try to match DRM_MODE_CONNECTOR_X as closely as possible. */\nenum drm_mode_subconnector {\n\tDRM_MODE_SUBCONNECTOR_Automatic   = 0,  /* DVI-I, TV     */\n\tDRM_MODE_SUBCONNECTOR_Unknown     = 0,  /* DVI-I, TV, DP */\n\tDRM_MODE_SUBCONNECTOR_VGA\t  = 1,  /*            DP */\n\tDRM_MODE_SUBCONNECTOR_DVID\t  = 3,  /* DVI-I      DP */\n\tDRM_MODE_SUBCONNECTOR_DVIA\t  = 4,  /* DVI-I         */\n\tDRM_MODE_SUBCONNECTOR_Composite   = 5,  /*        TV     */\n\tDRM_MODE_SUBCONNECTOR_SVIDEO\t  = 6,  /*        TV     */\n\tDRM_MODE_SUBCONNECTOR_Component   = 8,  /*        TV     */\n\tDRM_MODE_SUBCONNECTOR_SCART\t  = 9,  /*        TV     */\n\tDRM_MODE_SUBCONNECTOR_DisplayPort = 10, /*            DP */\n\tDRM_MODE_SUBCONNECTOR_HDMIA       = 11, /*            DP */\n\tDRM_MODE_SUBCONNECTOR_Native      = 15, /*            DP */\n\tDRM_MODE_SUBCONNECTOR_Wireless    = 18, /*            DP */\n};\n\n#define DRM_MODE_CONNECTOR_Unknown\t0\n#define DRM_MODE_CONNECTOR_VGA\t\t1\n#define DRM_MODE_CONNECTOR_DVII\t\t2\n#define DRM_MODE_CONNECTOR_DVID\t\t3\n#define DRM_MODE_CONNECTOR_DVIA\t\t4\n#define DRM_MODE_CONNECTOR_Composite\t5\n#define DRM_MODE_CONNECTOR_SVIDEO\t6\n#define DRM_MODE_CONNECTOR_LVDS\t\t7\n#define DRM_MODE_CONNECTOR_Component\t8\n#define DRM_MODE_CONNECTOR_9PinDIN\t9\n#define DRM_MODE_CONNECTOR_DisplayPort\t10\n#define DRM_MODE_CONNECTOR_HDMIA\t11\n#define DRM_MODE_CONNECTOR_HDMIB\t12\n#define DRM_MODE_CONNECTOR_TV\t\t13\n#define DRM_MODE_CONNECTOR_eDP\t\t14\n#define DRM_MODE_CONNECTOR_VIRTUAL      15\n#define DRM_MODE_CONNECTOR_DSI\t\t16\n#define DRM_MODE_CONNECTOR_DPI\t\t17\n#define DRM_MODE_CONNECTOR_WRITEBACK\t18\n#define DRM_MODE_CONNECTOR_SPI\t\t19\n#define DRM_MODE_CONNECTOR_USB\t\t20\n\n/**\n * struct drm_mode_get_connector - Get connector metadata.\n *\n * User-space can perform a GETCONNECTOR ioctl to retrieve information about a\n * connector. User-space is expected to retrieve encoders, modes and properties\n * by performing this ioctl at least twice: the first time to retrieve the\n * number of elements, the second time to retrieve the elements themselves.\n *\n * To retrieve the number of elements, set @count_props and @count_encoders to\n * zero, set @count_modes to 1, and set @modes_ptr to a temporary struct\n * drm_mode_modeinfo element.\n *\n * To retrieve the elements, allocate arrays for @encoders_ptr, @modes_ptr,\n * @props_ptr and @prop_values_ptr, then set @count_modes, @count_props and\n * @count_encoders to their capacity.\n *\n * Performing the ioctl only twice may be racy: the number of elements may have\n * changed with a hotplug event in-between the two ioctls. User-space is\n * expected to retry the last ioctl until the number of elements stabilizes.\n * The kernel won't fill any array which doesn't have the expected length.\n *\n * **Force-probing a connector**\n *\n * If the @count_modes field is set to zero and the DRM client is the current\n * DRM master, the kernel will perform a forced probe on the connector to\n * refresh the connector status, modes and EDID. A forced-probe can be slow,\n * might cause flickering and the ioctl will block.\n *\n * User-space needs to force-probe connectors to ensure their metadata is\n * up-to-date at startup and after receiving a hot-plug event. User-space\n * may perform a forced-probe when the user explicitly requests it. User-space\n * shouldn't perform a forced-probe in other situations.\n */\nstruct drm_mode_get_connector {\n\t/** @encoders_ptr: Pointer to ``__u32`` array of object IDs. */\n\t__u64 encoders_ptr;\n\t/** @modes_ptr: Pointer to struct drm_mode_modeinfo array. */\n\t__u64 modes_ptr;\n\t/** @props_ptr: Pointer to ``__u32`` array of property IDs. */\n\t__u64 props_ptr;\n\t/** @prop_values_ptr: Pointer to ``__u64`` array of property values. */\n\t__u64 prop_values_ptr;\n\n\t/** @count_modes: Number of modes. */\n\t__u32 count_modes;\n\t/** @count_props: Number of properties. */\n\t__u32 count_props;\n\t/** @count_encoders: Number of encoders. */\n\t__u32 count_encoders;\n\n\t/** @encoder_id: Object ID of the current encoder. */\n\t__u32 encoder_id;\n\t/** @connector_id: Object ID of the connector. */\n\t__u32 connector_id;\n\t/**\n\t * @connector_type: Type of the connector.\n\t *\n\t * See DRM_MODE_CONNECTOR_* defines.\n\t */\n\t__u32 connector_type;\n\t/**\n\t * @connector_type_id: Type-specific connector number.\n\t *\n\t * This is not an object ID. This is a per-type connector number. Each\n\t * (type, type_id) combination is unique across all connectors of a DRM\n\t * device.\n\t *\n\t * The (type, type_id) combination is not a stable identifier: the\n\t * type_id can change depending on the driver probe order.\n\t */\n\t__u32 connector_type_id;\n\n\t/**\n\t * @connection: Status of the connector.\n\t *\n\t * See enum drm_connector_status.\n\t */\n\t__u32 connection;\n\t/** @mm_width: Width of the connected sink in millimeters. */\n\t__u32 mm_width;\n\t/** @mm_height: Height of the connected sink in millimeters. */\n\t__u32 mm_height;\n\t/**\n\t * @subpixel: Subpixel order of the connected sink.\n\t *\n\t * See enum subpixel_order.\n\t */\n\t__u32 subpixel;\n\n\t/** @pad: Padding, must be zero. */\n\t__u32 pad;\n};\n\n#define DRM_MODE_PROP_PENDING\t(1<<0) /* deprecated, do not use */\n#define DRM_MODE_PROP_RANGE\t(1<<1)\n#define DRM_MODE_PROP_IMMUTABLE\t(1<<2)\n#define DRM_MODE_PROP_ENUM\t(1<<3) /* enumerated type with text strings */\n#define DRM_MODE_PROP_BLOB\t(1<<4)\n#define DRM_MODE_PROP_BITMASK\t(1<<5) /* bitmask of enumerated types */\n\n/* non-extended types: legacy bitmask, one bit per type: */\n#define DRM_MODE_PROP_LEGACY_TYPE  ( \\\n\t\tDRM_MODE_PROP_RANGE | \\\n\t\tDRM_MODE_PROP_ENUM | \\\n\t\tDRM_MODE_PROP_BLOB | \\\n\t\tDRM_MODE_PROP_BITMASK)\n\n/* extended-types: rather than continue to consume a bit per type,\n * grab a chunk of the bits to use as integer type id.\n */\n#define DRM_MODE_PROP_EXTENDED_TYPE\t0x0000ffc0\n#define DRM_MODE_PROP_TYPE(n)\t\t((n) << 6)\n#define DRM_MODE_PROP_OBJECT\t\tDRM_MODE_PROP_TYPE(1)\n#define DRM_MODE_PROP_SIGNED_RANGE\tDRM_MODE_PROP_TYPE(2)\n\n/* the PROP_ATOMIC flag is used to hide properties from userspace that\n * is not aware of atomic properties.  This is mostly to work around\n * older userspace (DDX drivers) that read/write each prop they find,\n * witout being aware that this could be triggering a lengthy modeset.\n */\n#define DRM_MODE_PROP_ATOMIC        0x80000000\n\n/**\n * struct drm_mode_property_enum - Description for an enum/bitfield entry.\n * @value: numeric value for this enum entry.\n * @name: symbolic name for this enum entry.\n *\n * See struct drm_property_enum for details.\n */\nstruct drm_mode_property_enum {\n\t__u64 value;\n\tchar name[DRM_PROP_NAME_LEN];\n};\n\n/**\n * struct drm_mode_get_property - Get property metadata.\n *\n * User-space can perform a GETPROPERTY ioctl to retrieve information about a\n * property. The same property may be attached to multiple objects, see\n * \"Modeset Base Object Abstraction\".\n *\n * The meaning of the @values_ptr field changes depending on the property type.\n * See &drm_property.flags for more details.\n *\n * The @enum_blob_ptr and @count_enum_blobs fields are only meaningful when the\n * property has the type &DRM_MODE_PROP_ENUM or &DRM_MODE_PROP_BITMASK. For\n * backwards compatibility, the kernel will always set @count_enum_blobs to\n * zero when the property has the type &DRM_MODE_PROP_BLOB. User-space must\n * ignore these two fields if the property has a different type.\n *\n * User-space is expected to retrieve values and enums by performing this ioctl\n * at least twice: the first time to retrieve the number of elements, the\n * second time to retrieve the elements themselves.\n *\n * To retrieve the number of elements, set @count_values and @count_enum_blobs\n * to zero, then call the ioctl. @count_values will be updated with the number\n * of elements. If the property has the type &DRM_MODE_PROP_ENUM or\n * &DRM_MODE_PROP_BITMASK, @count_enum_blobs will be updated as well.\n *\n * To retrieve the elements themselves, allocate an array for @values_ptr and\n * set @count_values to its capacity. If the property has the type\n * &DRM_MODE_PROP_ENUM or &DRM_MODE_PROP_BITMASK, allocate an array for\n * @enum_blob_ptr and set @count_enum_blobs to its capacity. Calling the ioctl\n * again will fill the arrays.\n */\nstruct drm_mode_get_property {\n\t/** @values_ptr: Pointer to a ``__u64`` array. */\n\t__u64 values_ptr;\n\t/** @enum_blob_ptr: Pointer to a struct drm_mode_property_enum array. */\n\t__u64 enum_blob_ptr;\n\n\t/**\n\t * @prop_id: Object ID of the property which should be retrieved. Set\n\t * by the caller.\n\t */\n\t__u32 prop_id;\n\t/**\n\t * @flags: ``DRM_MODE_PROP_*`` bitfield. See &drm_property.flags for\n\t * a definition of the flags.\n\t */\n\t__u32 flags;\n\t/**\n\t * @name: Symbolic property name. User-space should use this field to\n\t * recognize properties.\n\t */\n\tchar name[DRM_PROP_NAME_LEN];\n\n\t/** @count_values: Number of elements in @values_ptr. */\n\t__u32 count_values;\n\t/** @count_enum_blobs: Number of elements in @enum_blob_ptr. */\n\t__u32 count_enum_blobs;\n};\n\nstruct drm_mode_connector_set_property {\n\t__u64 value;\n\t__u32 prop_id;\n\t__u32 connector_id;\n};\n\n#define DRM_MODE_OBJECT_CRTC 0xcccccccc\n#define DRM_MODE_OBJECT_CONNECTOR 0xc0c0c0c0\n#define DRM_MODE_OBJECT_ENCODER 0xe0e0e0e0\n#define DRM_MODE_OBJECT_MODE 0xdededede\n#define DRM_MODE_OBJECT_PROPERTY 0xb0b0b0b0\n#define DRM_MODE_OBJECT_FB 0xfbfbfbfb\n#define DRM_MODE_OBJECT_BLOB 0xbbbbbbbb\n#define DRM_MODE_OBJECT_PLANE 0xeeeeeeee\n#define DRM_MODE_OBJECT_ANY 0\n\nstruct drm_mode_obj_get_properties {\n\t__u64 props_ptr;\n\t__u64 prop_values_ptr;\n\t__u32 count_props;\n\t__u32 obj_id;\n\t__u32 obj_type;\n};\n\nstruct drm_mode_obj_set_property {\n\t__u64 value;\n\t__u32 prop_id;\n\t__u32 obj_id;\n\t__u32 obj_type;\n};\n\nstruct drm_mode_get_blob {\n\t__u32 blob_id;\n\t__u32 length;\n\t__u64 data;\n};\n\nstruct drm_mode_fb_cmd {\n\t__u32 fb_id;\n\t__u32 width;\n\t__u32 height;\n\t__u32 pitch;\n\t__u32 bpp;\n\t__u32 depth;\n\t/* driver specific handle */\n\t__u32 handle;\n};\n\n#define DRM_MODE_FB_INTERLACED\t(1<<0) /* for interlaced framebuffers */\n#define DRM_MODE_FB_MODIFIERS\t(1<<1) /* enables ->modifer[] */\n\n/**\n * struct drm_mode_fb_cmd2 - Frame-buffer metadata.\n *\n * This struct holds frame-buffer metadata. There are two ways to use it:\n *\n * - User-space can fill this struct and perform a &DRM_IOCTL_MODE_ADDFB2\n *   ioctl to register a new frame-buffer. The new frame-buffer object ID will\n *   be set by the kernel in @fb_id.\n * - User-space can set @fb_id and perform a &DRM_IOCTL_MODE_GETFB2 ioctl to\n *   fetch metadata about an existing frame-buffer.\n *\n * In case of planar formats, this struct allows up to 4 buffer objects with\n * offsets and pitches per plane. The pitch and offset order are dictated by\n * the format FourCC as defined by ``drm_fourcc.h``, e.g. NV12 is described as:\n *\n *     YUV 4:2:0 image with a plane of 8-bit Y samples followed by an\n *     interleaved U/V plane containing 8-bit 2x2 subsampled colour difference\n *     samples.\n *\n * So it would consist of a Y plane at ``offsets[0]`` and a UV plane at\n * ``offsets[1]``.\n *\n * To accommodate tiled, compressed, etc formats, a modifier can be specified.\n * For more information see the \"Format Modifiers\" section. Note that even\n * though it looks like we have a modifier per-plane, we in fact do not. The\n * modifier for each plane must be identical. Thus all combinations of\n * different data layouts for multi-plane formats must be enumerated as\n * separate modifiers.\n *\n * All of the entries in @handles, @pitches, @offsets and @modifier must be\n * zero when unused. Warning, for @offsets and @modifier zero can't be used to\n * figure out whether the entry is used or not since it's a valid value (a zero\n * offset is common, and a zero modifier is &DRM_FORMAT_MOD_LINEAR).\n */\nstruct drm_mode_fb_cmd2 {\n\t/** @fb_id: Object ID of the frame-buffer. */\n\t__u32 fb_id;\n\t/** @width: Width of the frame-buffer. */\n\t__u32 width;\n\t/** @height: Height of the frame-buffer. */\n\t__u32 height;\n\t/**\n\t * @pixel_format: FourCC format code, see ``DRM_FORMAT_*`` constants in\n\t * ``drm_fourcc.h``.\n\t */\n\t__u32 pixel_format;\n\t/**\n\t * @flags: Frame-buffer flags (see &DRM_MODE_FB_INTERLACED and\n\t * &DRM_MODE_FB_MODIFIERS).\n\t */\n\t__u32 flags;\n\n\t/**\n\t * @handles: GEM buffer handle, one per plane. Set to 0 if the plane is\n\t * unused. The same handle can be used for multiple planes.\n\t */\n\t__u32 handles[4];\n\t/** @pitches: Pitch (aka. stride) in bytes, one per plane. */\n\t__u32 pitches[4];\n\t/** @offsets: Offset into the buffer in bytes, one per plane. */\n\t__u32 offsets[4];\n\t/**\n\t * @modifier: Format modifier, one per plane. See ``DRM_FORMAT_MOD_*``\n\t * constants in ``drm_fourcc.h``. All planes must use the same\n\t * modifier. Ignored unless &DRM_MODE_FB_MODIFIERS is set in @flags.\n\t */\n\t__u64 modifier[4];\n};\n\n#define DRM_MODE_FB_DIRTY_ANNOTATE_COPY 0x01\n#define DRM_MODE_FB_DIRTY_ANNOTATE_FILL 0x02\n#define DRM_MODE_FB_DIRTY_FLAGS         0x03\n\n#define DRM_MODE_FB_DIRTY_MAX_CLIPS     256\n\n/*\n * Mark a region of a framebuffer as dirty.\n *\n * Some hardware does not automatically update display contents\n * as a hardware or software draw to a framebuffer. This ioctl\n * allows userspace to tell the kernel and the hardware what\n * regions of the framebuffer have changed.\n *\n * The kernel or hardware is free to update more then just the\n * region specified by the clip rects. The kernel or hardware\n * may also delay and/or coalesce several calls to dirty into a\n * single update.\n *\n * Userspace may annotate the updates, the annotates are a\n * promise made by the caller that the change is either a copy\n * of pixels or a fill of a single color in the region specified.\n *\n * If the DRM_MODE_FB_DIRTY_ANNOTATE_COPY flag is given then\n * the number of updated regions are half of num_clips given,\n * where the clip rects are paired in src and dst. The width and\n * height of each one of the pairs must match.\n *\n * If the DRM_MODE_FB_DIRTY_ANNOTATE_FILL flag is given the caller\n * promises that the region specified of the clip rects is filled\n * completely with a single color as given in the color argument.\n */\n\nstruct drm_mode_fb_dirty_cmd {\n\t__u32 fb_id;\n\t__u32 flags;\n\t__u32 color;\n\t__u32 num_clips;\n\t__u64 clips_ptr;\n};\n\nstruct drm_mode_mode_cmd {\n\t__u32 connector_id;\n\tstruct drm_mode_modeinfo mode;\n};\n\n#define DRM_MODE_CURSOR_BO\t0x01\n#define DRM_MODE_CURSOR_MOVE\t0x02\n#define DRM_MODE_CURSOR_FLAGS\t0x03\n\n/*\n * depending on the value in flags different members are used.\n *\n * CURSOR_BO uses\n *    crtc_id\n *    width\n *    height\n *    handle - if 0 turns the cursor off\n *\n * CURSOR_MOVE uses\n *    crtc_id\n *    x\n *    y\n */\nstruct drm_mode_cursor {\n\t__u32 flags;\n\t__u32 crtc_id;\n\t__s32 x;\n\t__s32 y;\n\t__u32 width;\n\t__u32 height;\n\t/* driver specific handle */\n\t__u32 handle;\n};\n\nstruct drm_mode_cursor2 {\n\t__u32 flags;\n\t__u32 crtc_id;\n\t__s32 x;\n\t__s32 y;\n\t__u32 width;\n\t__u32 height;\n\t/* driver specific handle */\n\t__u32 handle;\n\t__s32 hot_x;\n\t__s32 hot_y;\n};\n\nstruct drm_mode_crtc_lut {\n\t__u32 crtc_id;\n\t__u32 gamma_size;\n\n\t/* pointers to arrays */\n\t__u64 red;\n\t__u64 green;\n\t__u64 blue;\n};\n\nstruct drm_color_ctm {\n\t/*\n\t * Conversion matrix in S31.32 sign-magnitude\n\t * (not two's complement!) format.\n\t *\n\t * out   matrix    in\n\t * |R|   |0 1 2|   |R|\n\t * |G| = |3 4 5| x |G|\n\t * |B|   |6 7 8|   |B|\n\t */\n\t__u64 matrix[9];\n};\n\nstruct drm_color_lut {\n\t/*\n\t * Values are mapped linearly to 0.0 - 1.0 range, with 0x0 == 0.0 and\n\t * 0xffff == 1.0.\n\t */\n\t__u16 red;\n\t__u16 green;\n\t__u16 blue;\n\t__u16 reserved;\n};\n\n/**\n * struct hdr_metadata_infoframe - HDR Metadata Infoframe Data.\n *\n * HDR Metadata Infoframe as per CTA 861.G spec. This is expected\n * to match exactly with the spec.\n *\n * Userspace is expected to pass the metadata information as per\n * the format described in this structure.\n */\nstruct hdr_metadata_infoframe {\n\t/**\n\t * @eotf: Electro-Optical Transfer Function (EOTF)\n\t * used in the stream.\n\t */\n\t__u8 eotf;\n\t/**\n\t * @metadata_type: Static_Metadata_Descriptor_ID.\n\t */\n\t__u8 metadata_type;\n\t/**\n\t * @display_primaries: Color Primaries of the Data.\n\t * These are coded as unsigned 16-bit values in units of\n\t * 0.00002, where 0x0000 represents zero and 0xC350\n\t * represents 1.0000.\n\t * @display_primaries.x: X cordinate of color primary.\n\t * @display_primaries.y: Y cordinate of color primary.\n\t */\n\tstruct {\n\t\t__u16 x, y;\n\t} display_primaries[3];\n\t/**\n\t * @white_point: White Point of Colorspace Data.\n\t * These are coded as unsigned 16-bit values in units of\n\t * 0.00002, where 0x0000 represents zero and 0xC350\n\t * represents 1.0000.\n\t * @white_point.x: X cordinate of whitepoint of color primary.\n\t * @white_point.y: Y cordinate of whitepoint of color primary.\n\t */\n\tstruct {\n\t\t__u16 x, y;\n\t} white_point;\n\t/**\n\t * @max_display_mastering_luminance: Max Mastering Display Luminance.\n\t * This value is coded as an unsigned 16-bit value in units of 1 cd/m2,\n\t * where 0x0001 represents 1 cd/m2 and 0xFFFF represents 65535 cd/m2.\n\t */\n\t__u16 max_display_mastering_luminance;\n\t/**\n\t * @min_display_mastering_luminance: Min Mastering Display Luminance.\n\t * This value is coded as an unsigned 16-bit value in units of\n\t * 0.0001 cd/m2, where 0x0001 represents 0.0001 cd/m2 and 0xFFFF\n\t * represents 6.5535 cd/m2.\n\t */\n\t__u16 min_display_mastering_luminance;\n\t/**\n\t * @max_cll: Max Content Light Level.\n\t * This value is coded as an unsigned 16-bit value in units of 1 cd/m2,\n\t * where 0x0001 represents 1 cd/m2 and 0xFFFF represents 65535 cd/m2.\n\t */\n\t__u16 max_cll;\n\t/**\n\t * @max_fall: Max Frame Average Light Level.\n\t * This value is coded as an unsigned 16-bit value in units of 1 cd/m2,\n\t * where 0x0001 represents 1 cd/m2 and 0xFFFF represents 65535 cd/m2.\n\t */\n\t__u16 max_fall;\n};\n\n/**\n * struct hdr_output_metadata - HDR output metadata\n *\n * Metadata Information to be passed from userspace\n */\nstruct hdr_output_metadata {\n\t/**\n\t * @metadata_type: Static_Metadata_Descriptor_ID.\n\t */\n\t__u32 metadata_type;\n\t/**\n\t * @hdmi_metadata_type1: HDR Metadata Infoframe.\n\t */\n\tunion {\n\t\tstruct hdr_metadata_infoframe hdmi_metadata_type1;\n\t};\n};\n\n/**\n * DRM_MODE_PAGE_FLIP_EVENT\n *\n * Request that the kernel sends back a vblank event (see\n * struct drm_event_vblank) with the &DRM_EVENT_FLIP_COMPLETE type when the\n * page-flip is done.\n */\n#define DRM_MODE_PAGE_FLIP_EVENT 0x01\n/**\n * DRM_MODE_PAGE_FLIP_ASYNC\n *\n * Request that the page-flip is performed as soon as possible, ie. with no\n * delay due to waiting for vblank. This may cause tearing to be visible on\n * the screen.\n */\n#define DRM_MODE_PAGE_FLIP_ASYNC 0x02\n#define DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE 0x4\n#define DRM_MODE_PAGE_FLIP_TARGET_RELATIVE 0x8\n#define DRM_MODE_PAGE_FLIP_TARGET (DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE | \\\n\t\t\t\t   DRM_MODE_PAGE_FLIP_TARGET_RELATIVE)\n/**\n * DRM_MODE_PAGE_FLIP_FLAGS\n *\n * Bitmask of flags suitable for &drm_mode_crtc_page_flip_target.flags.\n */\n#define DRM_MODE_PAGE_FLIP_FLAGS (DRM_MODE_PAGE_FLIP_EVENT | \\\n\t\t\t\t  DRM_MODE_PAGE_FLIP_ASYNC | \\\n\t\t\t\t  DRM_MODE_PAGE_FLIP_TARGET)\n\n/*\n * Request a page flip on the specified crtc.\n *\n * This ioctl will ask KMS to schedule a page flip for the specified\n * crtc.  Once any pending rendering targeting the specified fb (as of\n * ioctl time) has completed, the crtc will be reprogrammed to display\n * that fb after the next vertical refresh.  The ioctl returns\n * immediately, but subsequent rendering to the current fb will block\n * in the execbuffer ioctl until the page flip happens.  If a page\n * flip is already pending as the ioctl is called, EBUSY will be\n * returned.\n *\n * Flag DRM_MODE_PAGE_FLIP_EVENT requests that drm sends back a vblank\n * event (see drm.h: struct drm_event_vblank) when the page flip is\n * done.  The user_data field passed in with this ioctl will be\n * returned as the user_data field in the vblank event struct.\n *\n * Flag DRM_MODE_PAGE_FLIP_ASYNC requests that the flip happen\n * 'as soon as possible', meaning that it not delay waiting for vblank.\n * This may cause tearing on the screen.\n *\n * The reserved field must be zero.\n */\n\nstruct drm_mode_crtc_page_flip {\n\t__u32 crtc_id;\n\t__u32 fb_id;\n\t__u32 flags;\n\t__u32 reserved;\n\t__u64 user_data;\n};\n\n/*\n * Request a page flip on the specified crtc.\n *\n * Same as struct drm_mode_crtc_page_flip, but supports new flags and\n * re-purposes the reserved field:\n *\n * The sequence field must be zero unless either of the\n * DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE/RELATIVE flags is specified. When\n * the ABSOLUTE flag is specified, the sequence field denotes the absolute\n * vblank sequence when the flip should take effect. When the RELATIVE\n * flag is specified, the sequence field denotes the relative (to the\n * current one when the ioctl is called) vblank sequence when the flip\n * should take effect. NOTE: DRM_IOCTL_WAIT_VBLANK must still be used to\n * make sure the vblank sequence before the target one has passed before\n * calling this ioctl. The purpose of the\n * DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE/RELATIVE flags is merely to clarify\n * the target for when code dealing with a page flip runs during a\n * vertical blank period.\n */\n\nstruct drm_mode_crtc_page_flip_target {\n\t__u32 crtc_id;\n\t__u32 fb_id;\n\t__u32 flags;\n\t__u32 sequence;\n\t__u64 user_data;\n};\n\n/* create a dumb scanout buffer */\nstruct drm_mode_create_dumb {\n\t__u32 height;\n\t__u32 width;\n\t__u32 bpp;\n\t__u32 flags;\n\t/* handle, pitch, size will be returned */\n\t__u32 handle;\n\t__u32 pitch;\n\t__u64 size;\n};\n\n/* set up for mmap of a dumb scanout buffer */\nstruct drm_mode_map_dumb {\n\t/** Handle for the object being mapped. */\n\t__u32 handle;\n\t__u32 pad;\n\t/**\n\t * Fake offset to use for subsequent mmap call\n\t *\n\t * This is a fixed-size type for 32/64 compatibility.\n\t */\n\t__u64 offset;\n};\n\nstruct drm_mode_destroy_dumb {\n\t__u32 handle;\n};\n\n/**\n * DRM_MODE_ATOMIC_TEST_ONLY\n *\n * Do not apply the atomic commit, instead check whether the hardware supports\n * this configuration.\n *\n * See &drm_mode_config_funcs.atomic_check for more details on test-only\n * commits.\n */\n#define DRM_MODE_ATOMIC_TEST_ONLY 0x0100\n/**\n * DRM_MODE_ATOMIC_NONBLOCK\n *\n * Do not block while applying the atomic commit. The &DRM_IOCTL_MODE_ATOMIC\n * IOCTL returns immediately instead of waiting for the changes to be applied\n * in hardware. Note, the driver will still check that the update can be\n * applied before retuning.\n */\n#define DRM_MODE_ATOMIC_NONBLOCK  0x0200\n/**\n * DRM_MODE_ATOMIC_ALLOW_MODESET\n *\n * Allow the update to result in temporary or transient visible artifacts while\n * the update is being applied. Applying the update may also take significantly\n * more time than a page flip. All visual artifacts will disappear by the time\n * the update is completed, as signalled through the vblank event's timestamp\n * (see struct drm_event_vblank).\n *\n * This flag must be set when the KMS update might cause visible artifacts.\n * Without this flag such KMS update will return a EINVAL error. What kind of\n * update may cause visible artifacts depends on the driver and the hardware.\n * User-space that needs to know beforehand if an update might cause visible\n * artifacts can use &DRM_MODE_ATOMIC_TEST_ONLY without\n * &DRM_MODE_ATOMIC_ALLOW_MODESET to see if it fails.\n *\n * To the best of the driver's knowledge, visual artifacts are guaranteed to\n * not appear when this flag is not set. Some sinks might display visual\n * artifacts outside of the driver's control.\n */\n#define DRM_MODE_ATOMIC_ALLOW_MODESET 0x0400\n\n/**\n * DRM_MODE_ATOMIC_FLAGS\n *\n * Bitfield of flags accepted by the &DRM_IOCTL_MODE_ATOMIC IOCTL in\n * &drm_mode_atomic.flags.\n */\n#define DRM_MODE_ATOMIC_FLAGS (\\\n\t\tDRM_MODE_PAGE_FLIP_EVENT |\\\n\t\tDRM_MODE_PAGE_FLIP_ASYNC |\\\n\t\tDRM_MODE_ATOMIC_TEST_ONLY |\\\n\t\tDRM_MODE_ATOMIC_NONBLOCK |\\\n\t\tDRM_MODE_ATOMIC_ALLOW_MODESET)\n\nstruct drm_mode_atomic {\n\t__u32 flags;\n\t__u32 count_objs;\n\t__u64 objs_ptr;\n\t__u64 count_props_ptr;\n\t__u64 props_ptr;\n\t__u64 prop_values_ptr;\n\t__u64 reserved;\n\t__u64 user_data;\n};\n\nstruct drm_format_modifier_blob {\n#define FORMAT_BLOB_CURRENT 1\n\t/* Version of this blob format */\n\t__u32 version;\n\n\t/* Flags */\n\t__u32 flags;\n\n\t/* Number of fourcc formats supported */\n\t__u32 count_formats;\n\n\t/* Where in this blob the formats exist (in bytes) */\n\t__u32 formats_offset;\n\n\t/* Number of drm_format_modifiers */\n\t__u32 count_modifiers;\n\n\t/* Where in this blob the modifiers exist (in bytes) */\n\t__u32 modifiers_offset;\n\n\t/* __u32 formats[] */\n\t/* struct drm_format_modifier modifiers[] */\n};\n\nstruct drm_format_modifier {\n\t/* Bitmask of formats in get_plane format list this info applies to. The\n\t * offset allows a sliding window of which 64 formats (bits).\n\t *\n\t * Some examples:\n\t * In today's world with < 65 formats, and formats 0, and 2 are\n\t * supported\n\t * 0x0000000000000005\n\t *\t\t  ^-offset = 0, formats = 5\n\t *\n\t * If the number formats grew to 128, and formats 98-102 are\n\t * supported with the modifier:\n\t *\n\t * 0x0000007c00000000 0000000000000000\n\t *\t\t  ^\n\t *\t\t  |__offset = 64, formats = 0x7c00000000\n\t *\n\t */\n\t__u64 formats;\n\t__u32 offset;\n\t__u32 pad;\n\n\t/* The modifier that applies to the >get_plane format list bitmask. */\n\t__u64 modifier;\n};\n\n/**\n * struct drm_mode_create_blob - Create New blob property\n *\n * Create a new 'blob' data property, copying length bytes from data pointer,\n * and returning new blob ID.\n */\nstruct drm_mode_create_blob {\n\t/** @data: Pointer to data to copy. */\n\t__u64 data;\n\t/** @length: Length of data to copy. */\n\t__u32 length;\n\t/** @blob_id: Return: new property ID. */\n\t__u32 blob_id;\n};\n\n/**\n * struct drm_mode_destroy_blob - Destroy user blob\n * @blob_id: blob_id to destroy\n *\n * Destroy a user-created blob property.\n *\n * User-space can release blobs as soon as they do not need to refer to them by\n * their blob object ID.  For instance, if you are using a MODE_ID blob in an\n * atomic commit and you will not make another commit re-using the same ID, you\n * can destroy the blob as soon as the commit has been issued, without waiting\n * for it to complete.\n */\nstruct drm_mode_destroy_blob {\n\t__u32 blob_id;\n};\n\n/**\n * struct drm_mode_create_lease - Create lease\n *\n * Lease mode resources, creating another drm_master.\n *\n * The @object_ids array must reference at least one CRTC, one connector and\n * one plane if &DRM_CLIENT_CAP_UNIVERSAL_PLANES is enabled. Alternatively,\n * the lease can be completely empty.\n */\nstruct drm_mode_create_lease {\n\t/** @object_ids: Pointer to array of object ids (__u32) */\n\t__u64 object_ids;\n\t/** @object_count: Number of object ids */\n\t__u32 object_count;\n\t/** @flags: flags for new FD (O_CLOEXEC, etc) */\n\t__u32 flags;\n\n\t/** @lessee_id: Return: unique identifier for lessee. */\n\t__u32 lessee_id;\n\t/** @fd: Return: file descriptor to new drm_master file */\n\t__u32 fd;\n};\n\n/**\n * struct drm_mode_list_lessees - List lessees\n *\n * List lesses from a drm_master.\n */\nstruct drm_mode_list_lessees {\n\t/**\n\t * @count_lessees: Number of lessees.\n\t *\n\t * On input, provides length of the array.\n\t * On output, provides total number. No\n\t * more than the input number will be written\n\t * back, so two calls can be used to get\n\t * the size and then the data.\n\t */\n\t__u32 count_lessees;\n\t/** @pad: Padding. */\n\t__u32 pad;\n\n\t/**\n\t * @lessees_ptr: Pointer to lessees.\n\t *\n\t * Pointer to __u64 array of lessee ids\n\t */\n\t__u64 lessees_ptr;\n};\n\n/**\n * struct drm_mode_get_lease - Get Lease\n *\n * Get leased objects.\n */\nstruct drm_mode_get_lease {\n\t/**\n\t * @count_objects: Number of leased objects.\n\t *\n\t * On input, provides length of the array.\n\t * On output, provides total number. No\n\t * more than the input number will be written\n\t * back, so two calls can be used to get\n\t * the size and then the data.\n\t */\n\t__u32 count_objects;\n\t/** @pad: Padding. */\n\t__u32 pad;\n\n\t/**\n\t * @objects_ptr: Pointer to objects.\n\t *\n\t * Pointer to __u32 array of object ids.\n\t */\n\t__u64 objects_ptr;\n};\n\n/**\n * struct drm_mode_revoke_lease - Revoke lease\n */\nstruct drm_mode_revoke_lease {\n\t/** @lessee_id: Unique ID of lessee */\n\t__u32 lessee_id;\n};\n\n/**\n * struct drm_mode_rect - Two dimensional rectangle.\n * @x1: Horizontal starting coordinate (inclusive).\n * @y1: Vertical starting coordinate (inclusive).\n * @x2: Horizontal ending coordinate (exclusive).\n * @y2: Vertical ending coordinate (exclusive).\n *\n * With drm subsystem using struct drm_rect to manage rectangular area this\n * export it to user-space.\n *\n * Currently used by drm_mode_atomic blob property FB_DAMAGE_CLIPS.\n */\nstruct drm_mode_rect {\n\t__s32 x1;\n\t__s32 y1;\n\t__s32 x2;\n\t__s32 y2;\n};\n\n#if defined(__cplusplus)\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "src/linux/intel_gpu_top/i915_drm.h",
    "content": "/*\n * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas.\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sub license, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice (including the\n * next paragraph) shall be included in all copies or substantial portions\n * of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.\n * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR\n * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n */\n\n#ifndef _I915_DRM_H_\n#define _I915_DRM_H_\n\n#include \"drm.h\"\n\n#if defined(__cplusplus)\nextern \"C\" {\n#endif\n\n/* Please note that modifications to all structs defined here are\n * subject to backwards-compatibility constraints.\n */\n\n/**\n * DOC: uevents generated by i915 on its device node\n *\n * I915_L3_PARITY_UEVENT - Generated when the driver receives a parity mismatch\n *\tevent from the GPU L3 cache. Additional information supplied is ROW,\n *\tBANK, SUBBANK, SLICE of the affected cacheline. Userspace should keep\n *\ttrack of these events, and if a specific cache-line seems to have a\n *\tpersistent error, remap it with the L3 remapping tool supplied in\n *\tintel-gpu-tools.  The value supplied with the event is always 1.\n *\n * I915_ERROR_UEVENT - Generated upon error detection, currently only via\n *\thangcheck. The error detection event is a good indicator of when things\n *\tbegan to go badly. The value supplied with the event is a 1 upon error\n *\tdetection, and a 0 upon reset completion, signifying no more error\n *\texists. NOTE: Disabling hangcheck or reset via module parameter will\n *\tcause the related events to not be seen.\n *\n * I915_RESET_UEVENT - Event is generated just before an attempt to reset the\n *\tGPU. The value supplied with the event is always 1. NOTE: Disable\n *\treset via module parameter will cause this event to not be seen.\n */\n#define I915_L3_PARITY_UEVENT\t\t\"L3_PARITY_ERROR\"\n#define I915_ERROR_UEVENT\t\t\"ERROR\"\n#define I915_RESET_UEVENT\t\t\"RESET\"\n\n/**\n * struct i915_user_extension - Base class for defining a chain of extensions\n *\n * Many interfaces need to grow over time. In most cases we can simply\n * extend the struct and have userspace pass in more data. Another option,\n * as demonstrated by Vulkan's approach to providing extensions for forward\n * and backward compatibility, is to use a list of optional structs to\n * provide those extra details.\n *\n * The key advantage to using an extension chain is that it allows us to\n * redefine the interface more easily than an ever growing struct of\n * increasing complexity, and for large parts of that interface to be\n * entirely optional. The downside is more pointer chasing; chasing across\n * the boundary with pointers encapsulated inside u64.\n *\n * Example chaining:\n *\n * .. code-block:: C\n *\n *\tstruct i915_user_extension ext3 {\n *\t\t.next_extension = 0, // end\n *\t\t.name = ...,\n *\t};\n *\tstruct i915_user_extension ext2 {\n *\t\t.next_extension = (uintptr_t)&ext3,\n *\t\t.name = ...,\n *\t};\n *\tstruct i915_user_extension ext1 {\n *\t\t.next_extension = (uintptr_t)&ext2,\n *\t\t.name = ...,\n *\t};\n *\n * Typically the struct i915_user_extension would be embedded in some uAPI\n * struct, and in this case we would feed it the head of the chain(i.e ext1),\n * which would then apply all of the above extensions.\n *\n */\nstruct i915_user_extension {\n\t/**\n\t * @next_extension:\n\t *\n\t * Pointer to the next struct i915_user_extension, or zero if the end.\n\t */\n\t__u64 next_extension;\n\t/**\n\t * @name: Name of the extension.\n\t *\n\t * Note that the name here is just some integer.\n\t *\n\t * Also note that the name space for this is not global for the whole\n\t * driver, but rather its scope/meaning is limited to the specific piece\n\t * of uAPI which has embedded the struct i915_user_extension.\n\t */\n\t__u32 name;\n\t/**\n\t * @flags: MBZ\n\t *\n\t * All undefined bits must be zero.\n\t */\n\t__u32 flags;\n\t/**\n\t * @rsvd: MBZ\n\t *\n\t * Reserved for future use; must be zero.\n\t */\n\t__u32 rsvd[4];\n};\n\n/*\n * MOCS indexes used for GPU surfaces, defining the cacheability of the\n * surface data and the coherency for this data wrt. CPU vs. GPU accesses.\n */\nenum i915_mocs_table_index {\n\t/*\n\t * Not cached anywhere, coherency between CPU and GPU accesses is\n\t * guaranteed.\n\t */\n\tI915_MOCS_UNCACHED,\n\t/*\n\t * Cacheability and coherency controlled by the kernel automatically\n\t * based on the DRM_I915_GEM_SET_CACHING IOCTL setting and the current\n\t * usage of the surface (used for display scanout or not).\n\t */\n\tI915_MOCS_PTE,\n\t/*\n\t * Cached in all GPU caches available on the platform.\n\t * Coherency between CPU and GPU accesses to the surface is not\n\t * guaranteed without extra synchronization.\n\t */\n\tI915_MOCS_CACHED,\n};\n\n/**\n * enum drm_i915_gem_engine_class - uapi engine type enumeration\n *\n * Different engines serve different roles, and there may be more than one\n * engine serving each role.  This enum provides a classification of the role\n * of the engine, which may be used when requesting operations to be performed\n * on a certain subset of engines, or for providing information about that\n * group.\n */\nenum drm_i915_gem_engine_class {\n\t/**\n\t * @I915_ENGINE_CLASS_RENDER:\n\t *\n\t * Render engines support instructions used for 3D, Compute (GPGPU),\n\t * and programmable media workloads.  These instructions fetch data and\n\t * dispatch individual work items to threads that operate in parallel.\n\t * The threads run small programs (called \"kernels\" or \"shaders\") on\n\t * the GPU's execution units (EUs).\n\t */\n\tI915_ENGINE_CLASS_RENDER\t= 0,\n\n\t/**\n\t * @I915_ENGINE_CLASS_COPY:\n\t *\n\t * Copy engines (also referred to as \"blitters\") support instructions\n\t * that move blocks of data from one location in memory to another,\n\t * or that fill a specified location of memory with fixed data.\n\t * Copy engines can perform pre-defined logical or bitwise operations\n\t * on the source, destination, or pattern data.\n\t */\n\tI915_ENGINE_CLASS_COPY\t\t= 1,\n\n\t/**\n\t * @I915_ENGINE_CLASS_VIDEO:\n\t *\n\t * Video engines (also referred to as \"bit stream decode\" (BSD) or\n\t * \"vdbox\") support instructions that perform fixed-function media\n\t * decode and encode.\n\t */\n\tI915_ENGINE_CLASS_VIDEO\t\t= 2,\n\n\t/**\n\t * @I915_ENGINE_CLASS_VIDEO_ENHANCE:\n\t *\n\t * Video enhancement engines (also referred to as \"vebox\") support\n\t * instructions related to image enhancement.\n\t */\n\tI915_ENGINE_CLASS_VIDEO_ENHANCE\t= 3,\n\n\t/**\n\t * @I915_ENGINE_CLASS_COMPUTE:\n\t *\n\t * Compute engines support a subset of the instructions available\n\t * on render engines:  compute engines support Compute (GPGPU) and\n\t * programmable media workloads, but do not support the 3D pipeline.\n\t */\n\tI915_ENGINE_CLASS_COMPUTE\t= 4,\n\n\t/* Values in this enum should be kept compact. */\n\n\t/**\n\t * @I915_ENGINE_CLASS_INVALID:\n\t *\n\t * Placeholder value to represent an invalid engine class assignment.\n\t */\n\tI915_ENGINE_CLASS_INVALID\t= -1\n};\n\n/**\n * struct i915_engine_class_instance - Engine class/instance identifier\n *\n * There may be more than one engine fulfilling any role within the system.\n * Each engine of a class is given a unique instance number and therefore\n * any engine can be specified by its class:instance tuplet. APIs that allow\n * access to any engine in the system will use struct i915_engine_class_instance\n * for this identification.\n */\nstruct i915_engine_class_instance {\n\t/**\n\t * @engine_class:\n\t *\n\t * Engine class from enum drm_i915_gem_engine_class\n\t */\n\t__u16 engine_class;\n#define I915_ENGINE_CLASS_INVALID_NONE -1\n#define I915_ENGINE_CLASS_INVALID_VIRTUAL -2\n\n\t/**\n\t * @engine_instance:\n\t *\n\t * Engine instance.\n\t */\n\t__u16 engine_instance;\n};\n\n/**\n * DOC: perf_events exposed by i915 through /sys/bus/event_sources/drivers/i915\n *\n */\n\nenum drm_i915_pmu_engine_sample {\n\tI915_SAMPLE_BUSY = 0,\n\tI915_SAMPLE_WAIT = 1,\n\tI915_SAMPLE_SEMA = 2\n};\n\n#define I915_PMU_SAMPLE_BITS (4)\n#define I915_PMU_SAMPLE_MASK (0xf)\n#define I915_PMU_SAMPLE_INSTANCE_BITS (8)\n#define I915_PMU_CLASS_SHIFT \\\n\t(I915_PMU_SAMPLE_BITS + I915_PMU_SAMPLE_INSTANCE_BITS)\n\n#define __I915_PMU_ENGINE(class, instance, sample) \\\n\t((class) << I915_PMU_CLASS_SHIFT | \\\n\t(instance) << I915_PMU_SAMPLE_BITS | \\\n\t(sample))\n\n#define I915_PMU_ENGINE_BUSY(class, instance) \\\n\t__I915_PMU_ENGINE(class, instance, I915_SAMPLE_BUSY)\n\n#define I915_PMU_ENGINE_WAIT(class, instance) \\\n\t__I915_PMU_ENGINE(class, instance, I915_SAMPLE_WAIT)\n\n#define I915_PMU_ENGINE_SEMA(class, instance) \\\n\t__I915_PMU_ENGINE(class, instance, I915_SAMPLE_SEMA)\n\n/*\n * Top 4 bits of every non-engine counter are GT id.\n */\n#define __I915_PMU_GT_SHIFT (60)\n\n#define ___I915_PMU_OTHER(gt, x) \\\n\t(((__u64)__I915_PMU_ENGINE(0xff, 0xff, 0xf) + 1 + (x)) | \\\n\t((__u64)(gt) << __I915_PMU_GT_SHIFT))\n\n#define __I915_PMU_OTHER(x) ___I915_PMU_OTHER(0, x)\n\n#define I915_PMU_ACTUAL_FREQUENCY\t__I915_PMU_OTHER(0)\n#define I915_PMU_REQUESTED_FREQUENCY\t__I915_PMU_OTHER(1)\n#define I915_PMU_INTERRUPTS\t\t__I915_PMU_OTHER(2)\n#define I915_PMU_RC6_RESIDENCY\t\t__I915_PMU_OTHER(3)\n#define I915_PMU_SOFTWARE_GT_AWAKE_TIME\t__I915_PMU_OTHER(4)\n\n#define I915_PMU_LAST /* Deprecated - do not use */ I915_PMU_RC6_RESIDENCY\n\n#define __I915_PMU_ACTUAL_FREQUENCY(gt)\t\t___I915_PMU_OTHER(gt, 0)\n#define __I915_PMU_REQUESTED_FREQUENCY(gt)\t___I915_PMU_OTHER(gt, 1)\n#define __I915_PMU_INTERRUPTS(gt)\t\t___I915_PMU_OTHER(gt, 2)\n#define __I915_PMU_RC6_RESIDENCY(gt)\t\t___I915_PMU_OTHER(gt, 3)\n#define __I915_PMU_SOFTWARE_GT_AWAKE_TIME(gt)\t___I915_PMU_OTHER(gt, 4)\n\n/* Each region is a minimum of 16k, and there are at most 255 of them.\n */\n#define I915_NR_TEX_REGIONS 255\t/* table size 2k - maximum due to use\n\t\t\t\t * of chars for next/prev indices */\n#define I915_LOG_MIN_TEX_REGION_SIZE 14\n\ntypedef struct _drm_i915_init {\n\tenum {\n\t\tI915_INIT_DMA = 0x01,\n\t\tI915_CLEANUP_DMA = 0x02,\n\t\tI915_RESUME_DMA = 0x03\n\t} func;\n\tunsigned int mmio_offset;\n\tint sarea_priv_offset;\n\tunsigned int ring_start;\n\tunsigned int ring_end;\n\tunsigned int ring_size;\n\tunsigned int front_offset;\n\tunsigned int back_offset;\n\tunsigned int depth_offset;\n\tunsigned int w;\n\tunsigned int h;\n\tunsigned int pitch;\n\tunsigned int pitch_bits;\n\tunsigned int back_pitch;\n\tunsigned int depth_pitch;\n\tunsigned int cpp;\n\tunsigned int chipset;\n} drm_i915_init_t;\n\ntypedef struct _drm_i915_sarea {\n\tstruct drm_tex_region texList[I915_NR_TEX_REGIONS + 1];\n\tint last_upload;\t/* last time texture was uploaded */\n\tint last_enqueue;\t/* last time a buffer was enqueued */\n\tint last_dispatch;\t/* age of the most recently dispatched buffer */\n\tint ctxOwner;\t\t/* last context to upload state */\n\tint texAge;\n\tint pf_enabled;\t\t/* is pageflipping allowed? */\n\tint pf_active;\n\tint pf_current_page;\t/* which buffer is being displayed? */\n\tint perf_boxes;\t\t/* performance boxes to be displayed */\n\tint width, height;      /* screen size in pixels */\n\n\tdrm_handle_t front_handle;\n\tint front_offset;\n\tint front_size;\n\n\tdrm_handle_t back_handle;\n\tint back_offset;\n\tint back_size;\n\n\tdrm_handle_t depth_handle;\n\tint depth_offset;\n\tint depth_size;\n\n\tdrm_handle_t tex_handle;\n\tint tex_offset;\n\tint tex_size;\n\tint log_tex_granularity;\n\tint pitch;\n\tint rotation;           /* 0, 90, 180 or 270 */\n\tint rotated_offset;\n\tint rotated_size;\n\tint rotated_pitch;\n\tint virtualX, virtualY;\n\n\tunsigned int front_tiled;\n\tunsigned int back_tiled;\n\tunsigned int depth_tiled;\n\tunsigned int rotated_tiled;\n\tunsigned int rotated2_tiled;\n\n\tint pipeA_x;\n\tint pipeA_y;\n\tint pipeA_w;\n\tint pipeA_h;\n\tint pipeB_x;\n\tint pipeB_y;\n\tint pipeB_w;\n\tint pipeB_h;\n\n\t/* fill out some space for old userspace triple buffer */\n\tdrm_handle_t unused_handle;\n\t__u32 unused1, unused2, unused3;\n\n\t/* buffer object handles for static buffers. May change\n\t * over the lifetime of the client.\n\t */\n\t__u32 front_bo_handle;\n\t__u32 back_bo_handle;\n\t__u32 unused_bo_handle;\n\t__u32 depth_bo_handle;\n\n} drm_i915_sarea_t;\n\n/* due to userspace building against these headers we need some compat here */\n#define planeA_x pipeA_x\n#define planeA_y pipeA_y\n#define planeA_w pipeA_w\n#define planeA_h pipeA_h\n#define planeB_x pipeB_x\n#define planeB_y pipeB_y\n#define planeB_w pipeB_w\n#define planeB_h pipeB_h\n\n/* Flags for perf_boxes\n */\n#define I915_BOX_RING_EMPTY    0x1\n#define I915_BOX_FLIP          0x2\n#define I915_BOX_WAIT          0x4\n#define I915_BOX_TEXTURE_LOAD  0x8\n#define I915_BOX_LOST_CONTEXT  0x10\n\n/*\n * i915 specific ioctls.\n *\n * The device specific ioctl range is [DRM_COMMAND_BASE, DRM_COMMAND_END) ie\n * [0x40, 0xa0) (a0 is excluded). The numbers below are defined as offset\n * against DRM_COMMAND_BASE and should be between [0x0, 0x60).\n */\n#define DRM_I915_INIT\t\t0x00\n#define DRM_I915_FLUSH\t\t0x01\n#define DRM_I915_FLIP\t\t0x02\n#define DRM_I915_BATCHBUFFER\t0x03\n#define DRM_I915_IRQ_EMIT\t0x04\n#define DRM_I915_IRQ_WAIT\t0x05\n#define DRM_I915_GETPARAM\t0x06\n#define DRM_I915_SETPARAM\t0x07\n#define DRM_I915_ALLOC\t\t0x08\n#define DRM_I915_FREE\t\t0x09\n#define DRM_I915_INIT_HEAP\t0x0a\n#define DRM_I915_CMDBUFFER\t0x0b\n#define DRM_I915_DESTROY_HEAP\t0x0c\n#define DRM_I915_SET_VBLANK_PIPE\t0x0d\n#define DRM_I915_GET_VBLANK_PIPE\t0x0e\n#define DRM_I915_VBLANK_SWAP\t0x0f\n#define DRM_I915_HWS_ADDR\t0x11\n#define DRM_I915_GEM_INIT\t0x13\n#define DRM_I915_GEM_EXECBUFFER\t0x14\n#define DRM_I915_GEM_PIN\t0x15\n#define DRM_I915_GEM_UNPIN\t0x16\n#define DRM_I915_GEM_BUSY\t0x17\n#define DRM_I915_GEM_THROTTLE\t0x18\n#define DRM_I915_GEM_ENTERVT\t0x19\n#define DRM_I915_GEM_LEAVEVT\t0x1a\n#define DRM_I915_GEM_CREATE\t0x1b\n#define DRM_I915_GEM_PREAD\t0x1c\n#define DRM_I915_GEM_PWRITE\t0x1d\n#define DRM_I915_GEM_MMAP\t0x1e\n#define DRM_I915_GEM_SET_DOMAIN\t0x1f\n#define DRM_I915_GEM_SW_FINISH\t0x20\n#define DRM_I915_GEM_SET_TILING\t0x21\n#define DRM_I915_GEM_GET_TILING\t0x22\n#define DRM_I915_GEM_GET_APERTURE 0x23\n#define DRM_I915_GEM_MMAP_GTT\t0x24\n#define DRM_I915_GET_PIPE_FROM_CRTC_ID\t0x25\n#define DRM_I915_GEM_MADVISE\t0x26\n#define DRM_I915_OVERLAY_PUT_IMAGE\t0x27\n#define DRM_I915_OVERLAY_ATTRS\t0x28\n#define DRM_I915_GEM_EXECBUFFER2\t0x29\n#define DRM_I915_GEM_EXECBUFFER2_WR\tDRM_I915_GEM_EXECBUFFER2\n#define DRM_I915_GET_SPRITE_COLORKEY\t0x2a\n#define DRM_I915_SET_SPRITE_COLORKEY\t0x2b\n#define DRM_I915_GEM_WAIT\t0x2c\n#define DRM_I915_GEM_CONTEXT_CREATE\t0x2d\n#define DRM_I915_GEM_CONTEXT_DESTROY\t0x2e\n#define DRM_I915_GEM_SET_CACHING\t0x2f\n#define DRM_I915_GEM_GET_CACHING\t0x30\n#define DRM_I915_REG_READ\t\t0x31\n#define DRM_I915_GET_RESET_STATS\t0x32\n#define DRM_I915_GEM_USERPTR\t\t0x33\n#define DRM_I915_GEM_CONTEXT_GETPARAM\t0x34\n#define DRM_I915_GEM_CONTEXT_SETPARAM\t0x35\n#define DRM_I915_PERF_OPEN\t\t0x36\n#define DRM_I915_PERF_ADD_CONFIG\t0x37\n#define DRM_I915_PERF_REMOVE_CONFIG\t0x38\n#define DRM_I915_QUERY\t\t\t0x39\n#define DRM_I915_GEM_VM_CREATE\t\t0x3a\n#define DRM_I915_GEM_VM_DESTROY\t\t0x3b\n#define DRM_I915_GEM_CREATE_EXT\t\t0x3c\n/* Must be kept compact -- no holes */\n\n#define DRM_IOCTL_I915_INIT\t\tDRM_IOW( DRM_COMMAND_BASE + DRM_I915_INIT, drm_i915_init_t)\n#define DRM_IOCTL_I915_FLUSH\t\tDRM_IO ( DRM_COMMAND_BASE + DRM_I915_FLUSH)\n#define DRM_IOCTL_I915_FLIP\t\tDRM_IO ( DRM_COMMAND_BASE + DRM_I915_FLIP)\n#define DRM_IOCTL_I915_BATCHBUFFER\tDRM_IOW( DRM_COMMAND_BASE + DRM_I915_BATCHBUFFER, drm_i915_batchbuffer_t)\n#define DRM_IOCTL_I915_IRQ_EMIT         DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_IRQ_EMIT, drm_i915_irq_emit_t)\n#define DRM_IOCTL_I915_IRQ_WAIT         DRM_IOW( DRM_COMMAND_BASE + DRM_I915_IRQ_WAIT, drm_i915_irq_wait_t)\n#define DRM_IOCTL_I915_GETPARAM         DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GETPARAM, drm_i915_getparam_t)\n#define DRM_IOCTL_I915_SETPARAM         DRM_IOW( DRM_COMMAND_BASE + DRM_I915_SETPARAM, drm_i915_setparam_t)\n#define DRM_IOCTL_I915_ALLOC            DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_ALLOC, drm_i915_mem_alloc_t)\n#define DRM_IOCTL_I915_FREE             DRM_IOW( DRM_COMMAND_BASE + DRM_I915_FREE, drm_i915_mem_free_t)\n#define DRM_IOCTL_I915_INIT_HEAP        DRM_IOW( DRM_COMMAND_BASE + DRM_I915_INIT_HEAP, drm_i915_mem_init_heap_t)\n#define DRM_IOCTL_I915_CMDBUFFER\tDRM_IOW( DRM_COMMAND_BASE + DRM_I915_CMDBUFFER, drm_i915_cmdbuffer_t)\n#define DRM_IOCTL_I915_DESTROY_HEAP\tDRM_IOW( DRM_COMMAND_BASE + DRM_I915_DESTROY_HEAP, drm_i915_mem_destroy_heap_t)\n#define DRM_IOCTL_I915_SET_VBLANK_PIPE\tDRM_IOW( DRM_COMMAND_BASE + DRM_I915_SET_VBLANK_PIPE, drm_i915_vblank_pipe_t)\n#define DRM_IOCTL_I915_GET_VBLANK_PIPE\tDRM_IOR( DRM_COMMAND_BASE + DRM_I915_GET_VBLANK_PIPE, drm_i915_vblank_pipe_t)\n#define DRM_IOCTL_I915_VBLANK_SWAP\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_VBLANK_SWAP, drm_i915_vblank_swap_t)\n#define DRM_IOCTL_I915_HWS_ADDR\t\tDRM_IOW(DRM_COMMAND_BASE + DRM_I915_HWS_ADDR, struct drm_i915_gem_init)\n#define DRM_IOCTL_I915_GEM_INIT\t\tDRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_INIT, struct drm_i915_gem_init)\n#define DRM_IOCTL_I915_GEM_EXECBUFFER\tDRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_EXECBUFFER, struct drm_i915_gem_execbuffer)\n#define DRM_IOCTL_I915_GEM_EXECBUFFER2\tDRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_EXECBUFFER2, struct drm_i915_gem_execbuffer2)\n#define DRM_IOCTL_I915_GEM_EXECBUFFER2_WR\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_EXECBUFFER2_WR, struct drm_i915_gem_execbuffer2)\n#define DRM_IOCTL_I915_GEM_PIN\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_PIN, struct drm_i915_gem_pin)\n#define DRM_IOCTL_I915_GEM_UNPIN\tDRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_UNPIN, struct drm_i915_gem_unpin)\n#define DRM_IOCTL_I915_GEM_BUSY\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_BUSY, struct drm_i915_gem_busy)\n#define DRM_IOCTL_I915_GEM_SET_CACHING\t\tDRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_SET_CACHING, struct drm_i915_gem_caching)\n#define DRM_IOCTL_I915_GEM_GET_CACHING\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_GET_CACHING, struct drm_i915_gem_caching)\n#define DRM_IOCTL_I915_GEM_THROTTLE\tDRM_IO ( DRM_COMMAND_BASE + DRM_I915_GEM_THROTTLE)\n#define DRM_IOCTL_I915_GEM_ENTERVT\tDRM_IO(DRM_COMMAND_BASE + DRM_I915_GEM_ENTERVT)\n#define DRM_IOCTL_I915_GEM_LEAVEVT\tDRM_IO(DRM_COMMAND_BASE + DRM_I915_GEM_LEAVEVT)\n#define DRM_IOCTL_I915_GEM_CREATE\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_CREATE, struct drm_i915_gem_create)\n#define DRM_IOCTL_I915_GEM_CREATE_EXT\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_CREATE_EXT, struct drm_i915_gem_create_ext)\n#define DRM_IOCTL_I915_GEM_PREAD\tDRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_PREAD, struct drm_i915_gem_pread)\n#define DRM_IOCTL_I915_GEM_PWRITE\tDRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_PWRITE, struct drm_i915_gem_pwrite)\n#define DRM_IOCTL_I915_GEM_MMAP\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_MMAP, struct drm_i915_gem_mmap)\n#define DRM_IOCTL_I915_GEM_MMAP_GTT\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_MMAP_GTT, struct drm_i915_gem_mmap_gtt)\n#define DRM_IOCTL_I915_GEM_MMAP_OFFSET\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_MMAP_GTT, struct drm_i915_gem_mmap_offset)\n#define DRM_IOCTL_I915_GEM_SET_DOMAIN\tDRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_SET_DOMAIN, struct drm_i915_gem_set_domain)\n#define DRM_IOCTL_I915_GEM_SW_FINISH\tDRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_SW_FINISH, struct drm_i915_gem_sw_finish)\n#define DRM_IOCTL_I915_GEM_SET_TILING\tDRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_SET_TILING, struct drm_i915_gem_set_tiling)\n#define DRM_IOCTL_I915_GEM_GET_TILING\tDRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_GET_TILING, struct drm_i915_gem_get_tiling)\n#define DRM_IOCTL_I915_GEM_GET_APERTURE\tDRM_IOR  (DRM_COMMAND_BASE + DRM_I915_GEM_GET_APERTURE, struct drm_i915_gem_get_aperture)\n#define DRM_IOCTL_I915_GET_PIPE_FROM_CRTC_ID DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GET_PIPE_FROM_CRTC_ID, struct drm_i915_get_pipe_from_crtc_id)\n#define DRM_IOCTL_I915_GEM_MADVISE\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_MADVISE, struct drm_i915_gem_madvise)\n#define DRM_IOCTL_I915_OVERLAY_PUT_IMAGE\tDRM_IOW(DRM_COMMAND_BASE + DRM_I915_OVERLAY_PUT_IMAGE, struct drm_intel_overlay_put_image)\n#define DRM_IOCTL_I915_OVERLAY_ATTRS\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_OVERLAY_ATTRS, struct drm_intel_overlay_attrs)\n#define DRM_IOCTL_I915_SET_SPRITE_COLORKEY DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_SET_SPRITE_COLORKEY, struct drm_intel_sprite_colorkey)\n#define DRM_IOCTL_I915_GET_SPRITE_COLORKEY DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GET_SPRITE_COLORKEY, struct drm_intel_sprite_colorkey)\n#define DRM_IOCTL_I915_GEM_WAIT\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_WAIT, struct drm_i915_gem_wait)\n#define DRM_IOCTL_I915_GEM_CONTEXT_CREATE\tDRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_CREATE, struct drm_i915_gem_context_create)\n#define DRM_IOCTL_I915_GEM_CONTEXT_CREATE_EXT\tDRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_CREATE, struct drm_i915_gem_context_create_ext)\n#define DRM_IOCTL_I915_GEM_CONTEXT_DESTROY\tDRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_DESTROY, struct drm_i915_gem_context_destroy)\n#define DRM_IOCTL_I915_REG_READ\t\t\tDRM_IOWR (DRM_COMMAND_BASE + DRM_I915_REG_READ, struct drm_i915_reg_read)\n#define DRM_IOCTL_I915_GET_RESET_STATS\t\tDRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GET_RESET_STATS, struct drm_i915_reset_stats)\n#define DRM_IOCTL_I915_GEM_USERPTR\t\t\tDRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_USERPTR, struct drm_i915_gem_userptr)\n#define DRM_IOCTL_I915_GEM_CONTEXT_GETPARAM\tDRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_GETPARAM, struct drm_i915_gem_context_param)\n#define DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM\tDRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_SETPARAM, struct drm_i915_gem_context_param)\n#define DRM_IOCTL_I915_PERF_OPEN\tDRM_IOW(DRM_COMMAND_BASE + DRM_I915_PERF_OPEN, struct drm_i915_perf_open_param)\n#define DRM_IOCTL_I915_PERF_ADD_CONFIG\tDRM_IOW(DRM_COMMAND_BASE + DRM_I915_PERF_ADD_CONFIG, struct drm_i915_perf_oa_config)\n#define DRM_IOCTL_I915_PERF_REMOVE_CONFIG\tDRM_IOW(DRM_COMMAND_BASE + DRM_I915_PERF_REMOVE_CONFIG, __u64)\n#define DRM_IOCTL_I915_QUERY\t\t\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_QUERY, struct drm_i915_query)\n#define DRM_IOCTL_I915_GEM_VM_CREATE\tDRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_VM_CREATE, struct drm_i915_gem_vm_control)\n#define DRM_IOCTL_I915_GEM_VM_DESTROY\tDRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_VM_DESTROY, struct drm_i915_gem_vm_control)\n\n/* Allow drivers to submit batchbuffers directly to hardware, relying\n * on the security mechanisms provided by hardware.\n */\ntypedef struct drm_i915_batchbuffer {\n\tint start;\t\t/* agp offset */\n\tint used;\t\t/* nr bytes in use */\n\tint DR1;\t\t/* hw flags for GFX_OP_DRAWRECT_INFO */\n\tint DR4;\t\t/* window origin for GFX_OP_DRAWRECT_INFO */\n\tint num_cliprects;\t/* mulitpass with multiple cliprects? */\n\tstruct drm_clip_rect *cliprects;\t/* pointer to userspace cliprects */\n} drm_i915_batchbuffer_t;\n\n/* As above, but pass a pointer to userspace buffer which can be\n * validated by the kernel prior to sending to hardware.\n */\ntypedef struct _drm_i915_cmdbuffer {\n\tchar *buf;\t/* pointer to userspace command buffer */\n\tint sz;\t\t\t/* nr bytes in buf */\n\tint DR1;\t\t/* hw flags for GFX_OP_DRAWRECT_INFO */\n\tint DR4;\t\t/* window origin for GFX_OP_DRAWRECT_INFO */\n\tint num_cliprects;\t/* mulitpass with multiple cliprects? */\n\tstruct drm_clip_rect *cliprects;\t/* pointer to userspace cliprects */\n} drm_i915_cmdbuffer_t;\n\n/* Userspace can request & wait on irq's:\n */\ntypedef struct drm_i915_irq_emit {\n\tint *irq_seq;\n} drm_i915_irq_emit_t;\n\ntypedef struct drm_i915_irq_wait {\n\tint irq_seq;\n} drm_i915_irq_wait_t;\n\n/*\n * Different modes of per-process Graphics Translation Table,\n * see I915_PARAM_HAS_ALIASING_PPGTT\n */\n#define I915_GEM_PPGTT_NONE\t0\n#define I915_GEM_PPGTT_ALIASING\t1\n#define I915_GEM_PPGTT_FULL\t2\n\n/* Ioctl to query kernel params:\n */\n#define I915_PARAM_IRQ_ACTIVE            1\n#define I915_PARAM_ALLOW_BATCHBUFFER     2\n#define I915_PARAM_LAST_DISPATCH         3\n#define I915_PARAM_CHIPSET_ID            4\n#define I915_PARAM_HAS_GEM               5\n#define I915_PARAM_NUM_FENCES_AVAIL      6\n#define I915_PARAM_HAS_OVERLAY           7\n#define I915_PARAM_HAS_PAGEFLIPPING\t 8\n#define I915_PARAM_HAS_EXECBUF2          9\n#define I915_PARAM_HAS_BSD\t\t 10\n#define I915_PARAM_HAS_BLT\t\t 11\n#define I915_PARAM_HAS_RELAXED_FENCING\t 12\n#define I915_PARAM_HAS_COHERENT_RINGS\t 13\n#define I915_PARAM_HAS_EXEC_CONSTANTS\t 14\n#define I915_PARAM_HAS_RELAXED_DELTA\t 15\n#define I915_PARAM_HAS_GEN7_SOL_RESET\t 16\n#define I915_PARAM_HAS_LLC     \t \t 17\n#define I915_PARAM_HAS_ALIASING_PPGTT\t 18\n#define I915_PARAM_HAS_WAIT_TIMEOUT\t 19\n#define I915_PARAM_HAS_SEMAPHORES\t 20\n#define I915_PARAM_HAS_PRIME_VMAP_FLUSH\t 21\n#define I915_PARAM_HAS_VEBOX\t\t 22\n#define I915_PARAM_HAS_SECURE_BATCHES\t 23\n#define I915_PARAM_HAS_PINNED_BATCHES\t 24\n#define I915_PARAM_HAS_EXEC_NO_RELOC\t 25\n#define I915_PARAM_HAS_EXEC_HANDLE_LUT   26\n#define I915_PARAM_HAS_WT     \t \t 27\n#define I915_PARAM_CMD_PARSER_VERSION\t 28\n#define I915_PARAM_HAS_COHERENT_PHYS_GTT 29\n#define I915_PARAM_MMAP_VERSION          30\n#define I915_PARAM_HAS_BSD2\t\t 31\n#define I915_PARAM_REVISION              32\n#define I915_PARAM_SUBSLICE_TOTAL\t 33\n#define I915_PARAM_EU_TOTAL\t\t 34\n#define I915_PARAM_HAS_GPU_RESET\t 35\n#define I915_PARAM_HAS_RESOURCE_STREAMER 36\n#define I915_PARAM_HAS_EXEC_SOFTPIN\t 37\n#define I915_PARAM_HAS_POOLED_EU\t 38\n#define I915_PARAM_MIN_EU_IN_POOL\t 39\n#define I915_PARAM_MMAP_GTT_VERSION\t 40\n\n/*\n * Query whether DRM_I915_GEM_EXECBUFFER2 supports user defined execution\n * priorities and the driver will attempt to execute batches in priority order.\n * The param returns a capability bitmask, nonzero implies that the scheduler\n * is enabled, with different features present according to the mask.\n *\n * The initial priority for each batch is supplied by the context and is\n * controlled via I915_CONTEXT_PARAM_PRIORITY.\n */\n#define I915_PARAM_HAS_SCHEDULER\t 41\n#define   I915_SCHEDULER_CAP_ENABLED\t(1ul << 0)\n#define   I915_SCHEDULER_CAP_PRIORITY\t(1ul << 1)\n#define   I915_SCHEDULER_CAP_PREEMPTION\t(1ul << 2)\n#define   I915_SCHEDULER_CAP_SEMAPHORES\t(1ul << 3)\n#define   I915_SCHEDULER_CAP_ENGINE_BUSY_STATS\t(1ul << 4)\n/*\n * Indicates the 2k user priority levels are statically mapped into 3 buckets as\n * follows:\n *\n * -1k to -1\tLow priority\n * 0\t\tNormal priority\n * 1 to 1k\tHighest priority\n */\n#define   I915_SCHEDULER_CAP_STATIC_PRIORITY_MAP\t(1ul << 5)\n\n/*\n * Query the status of HuC load.\n *\n * The query can fail in the following scenarios with the listed error codes:\n *  -ENODEV if HuC is not present on this platform,\n *  -EOPNOTSUPP if HuC firmware usage is disabled,\n *  -ENOPKG if HuC firmware fetch failed,\n *  -ENOEXEC if HuC firmware is invalid or mismatched,\n *  -ENOMEM if i915 failed to prepare the FW objects for transfer to the uC,\n *  -EIO if the FW transfer or the FW authentication failed.\n *\n * If the IOCTL is successful, the returned parameter will be set to one of the\n * following values:\n *  * 0 if HuC firmware load is not complete,\n *  * 1 if HuC firmware is loaded and fully authenticated,\n *  * 2 if HuC firmware is loaded and authenticated for clear media only\n */\n#define I915_PARAM_HUC_STATUS\t\t 42\n\n/* Query whether DRM_I915_GEM_EXECBUFFER2 supports the ability to opt-out of\n * synchronisation with implicit fencing on individual objects.\n * See EXEC_OBJECT_ASYNC.\n */\n#define I915_PARAM_HAS_EXEC_ASYNC\t 43\n\n/* Query whether DRM_I915_GEM_EXECBUFFER2 supports explicit fence support -\n * both being able to pass in a sync_file fd to wait upon before executing,\n * and being able to return a new sync_file fd that is signaled when the\n * current request is complete. See I915_EXEC_FENCE_IN and I915_EXEC_FENCE_OUT.\n */\n#define I915_PARAM_HAS_EXEC_FENCE\t 44\n\n/* Query whether DRM_I915_GEM_EXECBUFFER2 supports the ability to capture\n * user-specified buffers for post-mortem debugging of GPU hangs. See\n * EXEC_OBJECT_CAPTURE.\n */\n#define I915_PARAM_HAS_EXEC_CAPTURE\t 45\n\n#define I915_PARAM_SLICE_MASK\t\t 46\n\n/* Assuming it's uniform for each slice, this queries the mask of subslices\n * per-slice for this system.\n */\n#define I915_PARAM_SUBSLICE_MASK\t 47\n\n/*\n * Query whether DRM_I915_GEM_EXECBUFFER2 supports supplying the batch buffer\n * as the first execobject as opposed to the last. See I915_EXEC_BATCH_FIRST.\n */\n#define I915_PARAM_HAS_EXEC_BATCH_FIRST\t 48\n\n/* Query whether DRM_I915_GEM_EXECBUFFER2 supports supplying an array of\n * drm_i915_gem_exec_fence structures.  See I915_EXEC_FENCE_ARRAY.\n */\n#define I915_PARAM_HAS_EXEC_FENCE_ARRAY  49\n\n/*\n * Query whether every context (both per-file default and user created) is\n * isolated (insofar as HW supports). If this parameter is not true, then\n * freshly created contexts may inherit values from an existing context,\n * rather than default HW values. If true, it also ensures (insofar as HW\n * supports) that all state set by this context will not leak to any other\n * context.\n *\n * As not every engine across every gen support contexts, the returned\n * value reports the support of context isolation for individual engines by\n * returning a bitmask of each engine class set to true if that class supports\n * isolation.\n */\n#define I915_PARAM_HAS_CONTEXT_ISOLATION 50\n\n/* Frequency of the command streamer timestamps given by the *_TIMESTAMP\n * registers. This used to be fixed per platform but from CNL onwards, this\n * might vary depending on the parts.\n */\n#define I915_PARAM_CS_TIMESTAMP_FREQUENCY 51\n\n/*\n * Once upon a time we supposed that writes through the GGTT would be\n * immediately in physical memory (once flushed out of the CPU path). However,\n * on a few different processors and chipsets, this is not necessarily the case\n * as the writes appear to be buffered internally. Thus a read of the backing\n * storage (physical memory) via a different path (with different physical tags\n * to the indirect write via the GGTT) will see stale values from before\n * the GGTT write. Inside the kernel, we can for the most part keep track of\n * the different read/write domains in use (e.g. set-domain), but the assumption\n * of coherency is baked into the ABI, hence reporting its true state in this\n * parameter.\n *\n * Reports true when writes via mmap_gtt are immediately visible following an\n * lfence to flush the WCB.\n *\n * Reports false when writes via mmap_gtt are indeterminately delayed in an in\n * internal buffer and are _not_ immediately visible to third parties accessing\n * directly via mmap_cpu/mmap_wc. Use of mmap_gtt as part of an IPC\n * communications channel when reporting false is strongly disadvised.\n */\n#define I915_PARAM_MMAP_GTT_COHERENT\t52\n\n/*\n * Query whether DRM_I915_GEM_EXECBUFFER2 supports coordination of parallel\n * execution through use of explicit fence support.\n * See I915_EXEC_FENCE_OUT and I915_EXEC_FENCE_SUBMIT.\n */\n#define I915_PARAM_HAS_EXEC_SUBMIT_FENCE 53\n\n/*\n * Revision of the i915-perf uAPI. The value returned helps determine what\n * i915-perf features are available. See drm_i915_perf_property_id.\n */\n#define I915_PARAM_PERF_REVISION\t54\n\n/* Query whether DRM_I915_GEM_EXECBUFFER2 supports supplying an array of\n * timeline syncobj through drm_i915_gem_execbuffer_ext_timeline_fences. See\n * I915_EXEC_USE_EXTENSIONS.\n */\n#define I915_PARAM_HAS_EXEC_TIMELINE_FENCES 55\n\n/* Query if the kernel supports the I915_USERPTR_PROBE flag. */\n#define I915_PARAM_HAS_USERPTR_PROBE 56\n\n/*\n * Frequency of the timestamps in OA reports. This used to be the same as the CS\n * timestamp frequency, but differs on some platforms.\n */\n#define I915_PARAM_OA_TIMESTAMP_FREQUENCY 57\n\n/*\n * Query the status of PXP support in i915.\n *\n * The query can fail in the following scenarios with the listed error codes:\n *     -ENODEV = PXP support is not available on the GPU device or in the\n *               kernel due to missing component drivers or kernel configs.\n *\n * If the IOCTL is successful, the returned parameter will be set to one of\n * the following values:\n *     1 = PXP feature is supported and is ready for use.\n *     2 = PXP feature is supported but should be ready soon (pending\n *         initialization of non-i915 system dependencies).\n *\n * NOTE: When param is supported (positive return values), user space should\n *       still refer to the GEM PXP context-creation UAPI header specs to be\n *       aware of possible failure due to system state machine at the time.\n */\n#define I915_PARAM_PXP_STATUS\t\t 58\n\n/* Must be kept compact -- no holes and well documented */\n\n/**\n * struct drm_i915_getparam - Driver parameter query structure.\n */\nstruct drm_i915_getparam {\n\t/** @param: Driver parameter to query. */\n\t__s32 param;\n\n\t/**\n\t * @value: Address of memory where queried value should be put.\n\t *\n\t * WARNING: Using pointers instead of fixed-size u64 means we need to write\n\t * compat32 code. Don't repeat this mistake.\n\t */\n\tint *value;\n};\n\n/**\n * typedef drm_i915_getparam_t - Driver parameter query structure.\n * See struct drm_i915_getparam.\n */\ntypedef struct drm_i915_getparam drm_i915_getparam_t;\n\n/* Ioctl to set kernel params:\n */\n#define I915_SETPARAM_USE_MI_BATCHBUFFER_START            1\n#define I915_SETPARAM_TEX_LRU_LOG_GRANULARITY             2\n#define I915_SETPARAM_ALLOW_BATCHBUFFER                   3\n#define I915_SETPARAM_NUM_USED_FENCES                     4\n/* Must be kept compact -- no holes */\n\ntypedef struct drm_i915_setparam {\n\tint param;\n\tint value;\n} drm_i915_setparam_t;\n\n/* A memory manager for regions of shared memory:\n */\n#define I915_MEM_REGION_AGP 1\n\ntypedef struct drm_i915_mem_alloc {\n\tint region;\n\tint alignment;\n\tint size;\n\tint *region_offset;\t/* offset from start of fb or agp */\n} drm_i915_mem_alloc_t;\n\ntypedef struct drm_i915_mem_free {\n\tint region;\n\tint region_offset;\n} drm_i915_mem_free_t;\n\ntypedef struct drm_i915_mem_init_heap {\n\tint region;\n\tint size;\n\tint start;\n} drm_i915_mem_init_heap_t;\n\n/* Allow memory manager to be torn down and re-initialized (eg on\n * rotate):\n */\ntypedef struct drm_i915_mem_destroy_heap {\n\tint region;\n} drm_i915_mem_destroy_heap_t;\n\n/* Allow X server to configure which pipes to monitor for vblank signals\n */\n#define\tDRM_I915_VBLANK_PIPE_A\t1\n#define\tDRM_I915_VBLANK_PIPE_B\t2\n\ntypedef struct drm_i915_vblank_pipe {\n\tint pipe;\n} drm_i915_vblank_pipe_t;\n\n/* Schedule buffer swap at given vertical blank:\n */\ntypedef struct drm_i915_vblank_swap {\n\tdrm_drawable_t drawable;\n\tenum drm_vblank_seq_type seqtype;\n\tunsigned int sequence;\n} drm_i915_vblank_swap_t;\n\ntypedef struct drm_i915_hws_addr {\n\t__u64 addr;\n} drm_i915_hws_addr_t;\n\nstruct drm_i915_gem_init {\n\t/**\n\t * Beginning offset in the GTT to be managed by the DRM memory\n\t * manager.\n\t */\n\t__u64 gtt_start;\n\t/**\n\t * Ending offset in the GTT to be managed by the DRM memory\n\t * manager.\n\t */\n\t__u64 gtt_end;\n};\n\nstruct drm_i915_gem_create {\n\t/**\n\t * Requested size for the object.\n\t *\n\t * The (page-aligned) allocated size for the object will be returned.\n\t */\n\t__u64 size;\n\t/**\n\t * Returned handle for the object.\n\t *\n\t * Object handles are nonzero.\n\t */\n\t__u32 handle;\n\t__u32 pad;\n};\n\nstruct drm_i915_gem_pread {\n\t/** Handle for the object being read. */\n\t__u32 handle;\n\t__u32 pad;\n\t/** Offset into the object to read from */\n\t__u64 offset;\n\t/** Length of data to read */\n\t__u64 size;\n\t/**\n\t * Pointer to write the data into.\n\t *\n\t * This is a fixed-size type for 32/64 compatibility.\n\t */\n\t__u64 data_ptr;\n};\n\nstruct drm_i915_gem_pwrite {\n\t/** Handle for the object being written to. */\n\t__u32 handle;\n\t__u32 pad;\n\t/** Offset into the object to write to */\n\t__u64 offset;\n\t/** Length of data to write */\n\t__u64 size;\n\t/**\n\t * Pointer to read the data from.\n\t *\n\t * This is a fixed-size type for 32/64 compatibility.\n\t */\n\t__u64 data_ptr;\n};\n\nstruct drm_i915_gem_mmap {\n\t/** Handle for the object being mapped. */\n\t__u32 handle;\n\t__u32 pad;\n\t/** Offset in the object to map. */\n\t__u64 offset;\n\t/**\n\t * Length of data to map.\n\t *\n\t * The value will be page-aligned.\n\t */\n\t__u64 size;\n\t/**\n\t * Returned pointer the data was mapped at.\n\t *\n\t * This is a fixed-size type for 32/64 compatibility.\n\t */\n\t__u64 addr_ptr;\n\n\t/**\n\t * Flags for extended behaviour.\n\t *\n\t * Added in version 2.\n\t */\n\t__u64 flags;\n#define I915_MMAP_WC 0x1\n};\n\nstruct drm_i915_gem_mmap_gtt {\n\t/** Handle for the object being mapped. */\n\t__u32 handle;\n\t__u32 pad;\n\t/**\n\t * Fake offset to use for subsequent mmap call\n\t *\n\t * This is a fixed-size type for 32/64 compatibility.\n\t */\n\t__u64 offset;\n};\n\n/**\n * struct drm_i915_gem_mmap_offset - Retrieve an offset so we can mmap this buffer object.\n *\n * This struct is passed as argument to the `DRM_IOCTL_I915_GEM_MMAP_OFFSET` ioctl,\n * and is used to retrieve the fake offset to mmap an object specified by &handle.\n *\n * The legacy way of using `DRM_IOCTL_I915_GEM_MMAP` is removed on gen12+.\n * `DRM_IOCTL_I915_GEM_MMAP_GTT` is an older supported alias to this struct, but will behave\n * as setting the &extensions to 0, and &flags to `I915_MMAP_OFFSET_GTT`.\n */\nstruct drm_i915_gem_mmap_offset {\n\t/** @handle: Handle for the object being mapped. */\n\t__u32 handle;\n\t/** @pad: Must be zero */\n\t__u32 pad;\n\t/**\n\t * @offset: The fake offset to use for subsequent mmap call\n\t *\n\t * This is a fixed-size type for 32/64 compatibility.\n\t */\n\t__u64 offset;\n\n\t/**\n\t * @flags: Flags for extended behaviour.\n\t *\n\t * It is mandatory that one of the `MMAP_OFFSET` types\n\t * should be included:\n\t *\n\t * - `I915_MMAP_OFFSET_GTT`: Use mmap with the object bound to GTT. (Write-Combined)\n\t * - `I915_MMAP_OFFSET_WC`: Use Write-Combined caching.\n\t * - `I915_MMAP_OFFSET_WB`: Use Write-Back caching.\n\t * - `I915_MMAP_OFFSET_FIXED`: Use object placement to determine caching.\n\t *\n\t * On devices with local memory `I915_MMAP_OFFSET_FIXED` is the only valid\n\t * type. On devices without local memory, this caching mode is invalid.\n\t *\n\t * As caching mode when specifying `I915_MMAP_OFFSET_FIXED`, WC or WB will\n\t * be used, depending on the object placement on creation. WB will be used\n\t * when the object can only exist in system memory, WC otherwise.\n\t */\n\t__u64 flags;\n\n#define I915_MMAP_OFFSET_GTT\t0\n#define I915_MMAP_OFFSET_WC\t1\n#define I915_MMAP_OFFSET_WB\t2\n#define I915_MMAP_OFFSET_UC\t3\n#define I915_MMAP_OFFSET_FIXED\t4\n\n\t/**\n\t * @extensions: Zero-terminated chain of extensions.\n\t *\n\t * No current extensions defined; mbz.\n\t */\n\t__u64 extensions;\n};\n\n/**\n * struct drm_i915_gem_set_domain - Adjust the objects write or read domain, in\n * preparation for accessing the pages via some CPU domain.\n *\n * Specifying a new write or read domain will flush the object out of the\n * previous domain(if required), before then updating the objects domain\n * tracking with the new domain.\n *\n * Note this might involve waiting for the object first if it is still active on\n * the GPU.\n *\n * Supported values for @read_domains and @write_domain:\n *\n *\t- I915_GEM_DOMAIN_WC: Uncached write-combined domain\n *\t- I915_GEM_DOMAIN_CPU: CPU cache domain\n *\t- I915_GEM_DOMAIN_GTT: Mappable aperture domain\n *\n * All other domains are rejected.\n *\n * Note that for discrete, starting from DG1, this is no longer supported, and\n * is instead rejected. On such platforms the CPU domain is effectively static,\n * where we also only support a single &drm_i915_gem_mmap_offset cache mode,\n * which can't be set explicitly and instead depends on the object placements,\n * as per the below.\n *\n * Implicit caching rules, starting from DG1:\n *\n *\t- If any of the object placements (see &drm_i915_gem_create_ext_memory_regions)\n *\t  contain I915_MEMORY_CLASS_DEVICE then the object will be allocated and\n *\t  mapped as write-combined only.\n *\n *\t- Everything else is always allocated and mapped as write-back, with the\n *\t  guarantee that everything is also coherent with the GPU.\n *\n * Note that this is likely to change in the future again, where we might need\n * more flexibility on future devices, so making this all explicit as part of a\n * new &drm_i915_gem_create_ext extension is probable.\n */\nstruct drm_i915_gem_set_domain {\n\t/** @handle: Handle for the object. */\n\t__u32 handle;\n\n\t/** @read_domains: New read domains. */\n\t__u32 read_domains;\n\n\t/**\n\t * @write_domain: New write domain.\n\t *\n\t * Note that having something in the write domain implies it's in the\n\t * read domain, and only that read domain.\n\t */\n\t__u32 write_domain;\n};\n\nstruct drm_i915_gem_sw_finish {\n\t/** Handle for the object */\n\t__u32 handle;\n};\n\nstruct drm_i915_gem_relocation_entry {\n\t/**\n\t * Handle of the buffer being pointed to by this relocation entry.\n\t *\n\t * It's appealing to make this be an index into the mm_validate_entry\n\t * list to refer to the buffer, but this allows the driver to create\n\t * a relocation list for state buffers and not re-write it per\n\t * exec using the buffer.\n\t */\n\t__u32 target_handle;\n\n\t/**\n\t * Value to be added to the offset of the target buffer to make up\n\t * the relocation entry.\n\t */\n\t__u32 delta;\n\n\t/** Offset in the buffer the relocation entry will be written into */\n\t__u64 offset;\n\n\t/**\n\t * Offset value of the target buffer that the relocation entry was last\n\t * written as.\n\t *\n\t * If the buffer has the same offset as last time, we can skip syncing\n\t * and writing the relocation.  This value is written back out by\n\t * the execbuffer ioctl when the relocation is written.\n\t */\n\t__u64 presumed_offset;\n\n\t/**\n\t * Target memory domains read by this operation.\n\t */\n\t__u32 read_domains;\n\n\t/**\n\t * Target memory domains written by this operation.\n\t *\n\t * Note that only one domain may be written by the whole\n\t * execbuffer operation, so that where there are conflicts,\n\t * the application will get -EINVAL back.\n\t */\n\t__u32 write_domain;\n};\n\n/** @{\n * Intel memory domains\n *\n * Most of these just align with the various caches in\n * the system and are used to flush and invalidate as\n * objects end up cached in different domains.\n */\n/** CPU cache */\n#define I915_GEM_DOMAIN_CPU\t\t0x00000001\n/** Render cache, used by 2D and 3D drawing */\n#define I915_GEM_DOMAIN_RENDER\t\t0x00000002\n/** Sampler cache, used by texture engine */\n#define I915_GEM_DOMAIN_SAMPLER\t\t0x00000004\n/** Command queue, used to load batch buffers */\n#define I915_GEM_DOMAIN_COMMAND\t\t0x00000008\n/** Instruction cache, used by shader programs */\n#define I915_GEM_DOMAIN_INSTRUCTION\t0x00000010\n/** Vertex address cache */\n#define I915_GEM_DOMAIN_VERTEX\t\t0x00000020\n/** GTT domain - aperture and scanout */\n#define I915_GEM_DOMAIN_GTT\t\t0x00000040\n/** WC domain - uncached access */\n#define I915_GEM_DOMAIN_WC\t\t0x00000080\n/** @} */\n\nstruct drm_i915_gem_exec_object {\n\t/**\n\t * User's handle for a buffer to be bound into the GTT for this\n\t * operation.\n\t */\n\t__u32 handle;\n\n\t/** Number of relocations to be performed on this buffer */\n\t__u32 relocation_count;\n\t/**\n\t * Pointer to array of struct drm_i915_gem_relocation_entry containing\n\t * the relocations to be performed in this buffer.\n\t */\n\t__u64 relocs_ptr;\n\n\t/** Required alignment in graphics aperture */\n\t__u64 alignment;\n\n\t/**\n\t * Returned value of the updated offset of the object, for future\n\t * presumed_offset writes.\n\t */\n\t__u64 offset;\n};\n\n/* DRM_IOCTL_I915_GEM_EXECBUFFER was removed in Linux 5.13 */\nstruct drm_i915_gem_execbuffer {\n\t/**\n\t * List of buffers to be validated with their relocations to be\n\t * performend on them.\n\t *\n\t * This is a pointer to an array of struct drm_i915_gem_validate_entry.\n\t *\n\t * These buffers must be listed in an order such that all relocations\n\t * a buffer is performing refer to buffers that have already appeared\n\t * in the validate list.\n\t */\n\t__u64 buffers_ptr;\n\t__u32 buffer_count;\n\n\t/** Offset in the batchbuffer to start execution from. */\n\t__u32 batch_start_offset;\n\t/** Bytes used in batchbuffer from batch_start_offset */\n\t__u32 batch_len;\n\t__u32 DR1;\n\t__u32 DR4;\n\t__u32 num_cliprects;\n\t/** This is a struct drm_clip_rect *cliprects */\n\t__u64 cliprects_ptr;\n};\n\nstruct drm_i915_gem_exec_object2 {\n\t/**\n\t * User's handle for a buffer to be bound into the GTT for this\n\t * operation.\n\t */\n\t__u32 handle;\n\n\t/** Number of relocations to be performed on this buffer */\n\t__u32 relocation_count;\n\t/**\n\t * Pointer to array of struct drm_i915_gem_relocation_entry containing\n\t * the relocations to be performed in this buffer.\n\t */\n\t__u64 relocs_ptr;\n\n\t/** Required alignment in graphics aperture */\n\t__u64 alignment;\n\n\t/**\n\t * When the EXEC_OBJECT_PINNED flag is specified this is populated by\n\t * the user with the GTT offset at which this object will be pinned.\n\t *\n\t * When the I915_EXEC_NO_RELOC flag is specified this must contain the\n\t * presumed_offset of the object.\n\t *\n\t * During execbuffer2 the kernel populates it with the value of the\n\t * current GTT offset of the object, for future presumed_offset writes.\n\t *\n\t * See struct drm_i915_gem_create_ext for the rules when dealing with\n\t * alignment restrictions with I915_MEMORY_CLASS_DEVICE, on devices with\n\t * minimum page sizes, like DG2.\n\t */\n\t__u64 offset;\n\n#define EXEC_OBJECT_NEEDS_FENCE\t\t (1<<0)\n#define EXEC_OBJECT_NEEDS_GTT\t\t (1<<1)\n#define EXEC_OBJECT_WRITE\t\t (1<<2)\n#define EXEC_OBJECT_SUPPORTS_48B_ADDRESS (1<<3)\n#define EXEC_OBJECT_PINNED\t\t (1<<4)\n#define EXEC_OBJECT_PAD_TO_SIZE\t\t (1<<5)\n/* The kernel implicitly tracks GPU activity on all GEM objects, and\n * synchronises operations with outstanding rendering. This includes\n * rendering on other devices if exported via dma-buf. However, sometimes\n * this tracking is too coarse and the user knows better. For example,\n * if the object is split into non-overlapping ranges shared between different\n * clients or engines (i.e. suballocating objects), the implicit tracking\n * by kernel assumes that each operation affects the whole object rather\n * than an individual range, causing needless synchronisation between clients.\n * The kernel will also forgo any CPU cache flushes prior to rendering from\n * the object as the client is expected to be also handling such domain\n * tracking.\n *\n * The kernel maintains the implicit tracking in order to manage resources\n * used by the GPU - this flag only disables the synchronisation prior to\n * rendering with this object in this execbuf.\n *\n * Opting out of implicit synhronisation requires the user to do its own\n * explicit tracking to avoid rendering corruption. See, for example,\n * I915_PARAM_HAS_EXEC_FENCE to order execbufs and execute them asynchronously.\n */\n#define EXEC_OBJECT_ASYNC\t\t(1<<6)\n/* Request that the contents of this execobject be copied into the error\n * state upon a GPU hang involving this batch for post-mortem debugging.\n * These buffers are recorded in no particular order as \"user\" in\n * /sys/class/drm/cardN/error. Query I915_PARAM_HAS_EXEC_CAPTURE to see\n * if the kernel supports this flag.\n */\n#define EXEC_OBJECT_CAPTURE\t\t(1<<7)\n/* All remaining bits are MBZ and RESERVED FOR FUTURE USE */\n#define __EXEC_OBJECT_UNKNOWN_FLAGS -(EXEC_OBJECT_CAPTURE<<1)\n\t__u64 flags;\n\n\tunion {\n\t\t__u64 rsvd1;\n\t\t__u64 pad_to_size;\n\t};\n\t__u64 rsvd2;\n};\n\n/**\n * struct drm_i915_gem_exec_fence - An input or output fence for the execbuf\n * ioctl.\n *\n * The request will wait for input fence to signal before submission.\n *\n * The returned output fence will be signaled after the completion of the\n * request.\n */\nstruct drm_i915_gem_exec_fence {\n\t/** @handle: User's handle for a drm_syncobj to wait on or signal. */\n\t__u32 handle;\n\n\t/**\n\t * @flags: Supported flags are:\n\t *\n\t * I915_EXEC_FENCE_WAIT:\n\t * Wait for the input fence before request submission.\n\t *\n\t * I915_EXEC_FENCE_SIGNAL:\n\t * Return request completion fence as output\n\t */\n\t__u32 flags;\n#define I915_EXEC_FENCE_WAIT            (1<<0)\n#define I915_EXEC_FENCE_SIGNAL          (1<<1)\n#define __I915_EXEC_FENCE_UNKNOWN_FLAGS (-(I915_EXEC_FENCE_SIGNAL << 1))\n};\n\n/**\n * struct drm_i915_gem_execbuffer_ext_timeline_fences - Timeline fences\n * for execbuf ioctl.\n *\n * This structure describes an array of drm_syncobj and associated points for\n * timeline variants of drm_syncobj. It is invalid to append this structure to\n * the execbuf if I915_EXEC_FENCE_ARRAY is set.\n */\nstruct drm_i915_gem_execbuffer_ext_timeline_fences {\n#define DRM_I915_GEM_EXECBUFFER_EXT_TIMELINE_FENCES 0\n\t/** @base: Extension link. See struct i915_user_extension. */\n\tstruct i915_user_extension base;\n\n\t/**\n\t * @fence_count: Number of elements in the @handles_ptr & @value_ptr\n\t * arrays.\n\t */\n\t__u64 fence_count;\n\n\t/**\n\t * @handles_ptr: Pointer to an array of struct drm_i915_gem_exec_fence\n\t * of length @fence_count.\n\t */\n\t__u64 handles_ptr;\n\n\t/**\n\t * @values_ptr: Pointer to an array of u64 values of length\n\t * @fence_count.\n\t * Values must be 0 for a binary drm_syncobj. A Value of 0 for a\n\t * timeline drm_syncobj is invalid as it turns a drm_syncobj into a\n\t * binary one.\n\t */\n\t__u64 values_ptr;\n};\n\n/**\n * struct drm_i915_gem_execbuffer2 - Structure for DRM_I915_GEM_EXECBUFFER2\n * ioctl.\n */\nstruct drm_i915_gem_execbuffer2 {\n\t/** @buffers_ptr: Pointer to a list of gem_exec_object2 structs */\n\t__u64 buffers_ptr;\n\n\t/** @buffer_count: Number of elements in @buffers_ptr array */\n\t__u32 buffer_count;\n\n\t/**\n\t * @batch_start_offset: Offset in the batchbuffer to start execution\n\t * from.\n\t */\n\t__u32 batch_start_offset;\n\n\t/**\n\t * @batch_len: Length in bytes of the batch buffer, starting from the\n\t * @batch_start_offset. If 0, length is assumed to be the batch buffer\n\t * object size.\n\t */\n\t__u32 batch_len;\n\n\t/** @DR1: deprecated */\n\t__u32 DR1;\n\n\t/** @DR4: deprecated */\n\t__u32 DR4;\n\n\t/** @num_cliprects: See @cliprects_ptr */\n\t__u32 num_cliprects;\n\n\t/**\n\t * @cliprects_ptr: Kernel clipping was a DRI1 misfeature.\n\t *\n\t * It is invalid to use this field if I915_EXEC_FENCE_ARRAY or\n\t * I915_EXEC_USE_EXTENSIONS flags are not set.\n\t *\n\t * If I915_EXEC_FENCE_ARRAY is set, then this is a pointer to an array\n\t * of &drm_i915_gem_exec_fence and @num_cliprects is the length of the\n\t * array.\n\t *\n\t * If I915_EXEC_USE_EXTENSIONS is set, then this is a pointer to a\n\t * single &i915_user_extension and num_cliprects is 0.\n\t */\n\t__u64 cliprects_ptr;\n\n\t/** @flags: Execbuf flags */\n\t__u64 flags;\n#define I915_EXEC_RING_MASK              (0x3f)\n#define I915_EXEC_DEFAULT                (0<<0)\n#define I915_EXEC_RENDER                 (1<<0)\n#define I915_EXEC_BSD                    (2<<0)\n#define I915_EXEC_BLT                    (3<<0)\n#define I915_EXEC_VEBOX                  (4<<0)\n\n/* Used for switching the constants addressing mode on gen4+ RENDER ring.\n * Gen6+ only supports relative addressing to dynamic state (default) and\n * absolute addressing.\n *\n * These flags are ignored for the BSD and BLT rings.\n */\n#define I915_EXEC_CONSTANTS_MASK \t(3<<6)\n#define I915_EXEC_CONSTANTS_REL_GENERAL (0<<6) /* default */\n#define I915_EXEC_CONSTANTS_ABSOLUTE \t(1<<6)\n#define I915_EXEC_CONSTANTS_REL_SURFACE (2<<6) /* gen4/5 only */\n\n/** Resets the SO write offset registers for transform feedback on gen7. */\n#define I915_EXEC_GEN7_SOL_RESET\t(1<<8)\n\n/** Request a privileged (\"secure\") batch buffer. Note only available for\n * DRM_ROOT_ONLY | DRM_MASTER processes.\n */\n#define I915_EXEC_SECURE\t\t(1<<9)\n\n/** Inform the kernel that the batch is and will always be pinned. This\n * negates the requirement for a workaround to be performed to avoid\n * an incoherent CS (such as can be found on 830/845). If this flag is\n * not passed, the kernel will endeavour to make sure the batch is\n * coherent with the CS before execution. If this flag is passed,\n * userspace assumes the responsibility for ensuring the same.\n */\n#define I915_EXEC_IS_PINNED\t\t(1<<10)\n\n/** Provide a hint to the kernel that the command stream and auxiliary\n * state buffers already holds the correct presumed addresses and so the\n * relocation process may be skipped if no buffers need to be moved in\n * preparation for the execbuffer.\n */\n#define I915_EXEC_NO_RELOC\t\t(1<<11)\n\n/** Use the reloc.handle as an index into the exec object array rather\n * than as the per-file handle.\n */\n#define I915_EXEC_HANDLE_LUT\t\t(1<<12)\n\n/** Used for switching BSD rings on the platforms with two BSD rings */\n#define I915_EXEC_BSD_SHIFT\t (13)\n#define I915_EXEC_BSD_MASK\t (3 << I915_EXEC_BSD_SHIFT)\n/* default ping-pong mode */\n#define I915_EXEC_BSD_DEFAULT\t (0 << I915_EXEC_BSD_SHIFT)\n#define I915_EXEC_BSD_RING1\t (1 << I915_EXEC_BSD_SHIFT)\n#define I915_EXEC_BSD_RING2\t (2 << I915_EXEC_BSD_SHIFT)\n\n/** Tell the kernel that the batchbuffer is processed by\n *  the resource streamer.\n */\n#define I915_EXEC_RESOURCE_STREAMER     (1<<15)\n\n/* Setting I915_EXEC_FENCE_IN implies that lower_32_bits(rsvd2) represent\n * a sync_file fd to wait upon (in a nonblocking manner) prior to executing\n * the batch.\n *\n * Returns -EINVAL if the sync_file fd cannot be found.\n */\n#define I915_EXEC_FENCE_IN\t\t(1<<16)\n\n/* Setting I915_EXEC_FENCE_OUT causes the ioctl to return a sync_file fd\n * in the upper_32_bits(rsvd2) upon success. Ownership of the fd is given\n * to the caller, and it should be close() after use. (The fd is a regular\n * file descriptor and will be cleaned up on process termination. It holds\n * a reference to the request, but nothing else.)\n *\n * The sync_file fd can be combined with other sync_file and passed either\n * to execbuf using I915_EXEC_FENCE_IN, to atomic KMS ioctls (so that a flip\n * will only occur after this request completes), or to other devices.\n *\n * Using I915_EXEC_FENCE_OUT requires use of\n * DRM_IOCTL_I915_GEM_EXECBUFFER2_WR ioctl so that the result is written\n * back to userspace. Failure to do so will cause the out-fence to always\n * be reported as zero, and the real fence fd to be leaked.\n */\n#define I915_EXEC_FENCE_OUT\t\t(1<<17)\n\n/*\n * Traditionally the execbuf ioctl has only considered the final element in\n * the execobject[] to be the executable batch. Often though, the client\n * will known the batch object prior to construction and being able to place\n * it into the execobject[] array first can simplify the relocation tracking.\n * Setting I915_EXEC_BATCH_FIRST tells execbuf to use element 0 of the\n * execobject[] as the * batch instead (the default is to use the last\n * element).\n */\n#define I915_EXEC_BATCH_FIRST\t\t(1<<18)\n\n/* Setting I915_FENCE_ARRAY implies that num_cliprects and cliprects_ptr\n * define an array of i915_gem_exec_fence structures which specify a set of\n * dma fences to wait upon or signal.\n */\n#define I915_EXEC_FENCE_ARRAY   (1<<19)\n\n/*\n * Setting I915_EXEC_FENCE_SUBMIT implies that lower_32_bits(rsvd2) represent\n * a sync_file fd to wait upon (in a nonblocking manner) prior to executing\n * the batch.\n *\n * Returns -EINVAL if the sync_file fd cannot be found.\n */\n#define I915_EXEC_FENCE_SUBMIT\t\t(1 << 20)\n\n/*\n * Setting I915_EXEC_USE_EXTENSIONS implies that\n * drm_i915_gem_execbuffer2.cliprects_ptr is treated as a pointer to an linked\n * list of i915_user_extension. Each i915_user_extension node is the base of a\n * larger structure. The list of supported structures are listed in the\n * drm_i915_gem_execbuffer_ext enum.\n */\n#define I915_EXEC_USE_EXTENSIONS\t(1 << 21)\n#define __I915_EXEC_UNKNOWN_FLAGS (-(I915_EXEC_USE_EXTENSIONS << 1))\n\n\t/** @rsvd1: Context id */\n\t__u64 rsvd1;\n\n\t/**\n\t * @rsvd2: in and out sync_file file descriptors.\n\t *\n\t * When I915_EXEC_FENCE_IN or I915_EXEC_FENCE_SUBMIT flag is set, the\n\t * lower 32 bits of this field will have the in sync_file fd (input).\n\t *\n\t * When I915_EXEC_FENCE_OUT flag is set, the upper 32 bits of this\n\t * field will have the out sync_file fd (output).\n\t */\n\t__u64 rsvd2;\n};\n\n#define I915_EXEC_CONTEXT_ID_MASK\t(0xffffffff)\n#define i915_execbuffer2_set_context_id(eb2, context) \\\n\t(eb2).rsvd1 = context & I915_EXEC_CONTEXT_ID_MASK\n#define i915_execbuffer2_get_context_id(eb2) \\\n\t((eb2).rsvd1 & I915_EXEC_CONTEXT_ID_MASK)\n\nstruct drm_i915_gem_pin {\n\t/** Handle of the buffer to be pinned. */\n\t__u32 handle;\n\t__u32 pad;\n\n\t/** alignment required within the aperture */\n\t__u64 alignment;\n\n\t/** Returned GTT offset of the buffer. */\n\t__u64 offset;\n};\n\nstruct drm_i915_gem_unpin {\n\t/** Handle of the buffer to be unpinned. */\n\t__u32 handle;\n\t__u32 pad;\n};\n\nstruct drm_i915_gem_busy {\n\t/** Handle of the buffer to check for busy */\n\t__u32 handle;\n\n\t/** Return busy status\n\t *\n\t * A return of 0 implies that the object is idle (after\n\t * having flushed any pending activity), and a non-zero return that\n\t * the object is still in-flight on the GPU. (The GPU has not yet\n\t * signaled completion for all pending requests that reference the\n\t * object.) An object is guaranteed to become idle eventually (so\n\t * long as no new GPU commands are executed upon it). Due to the\n\t * asynchronous nature of the hardware, an object reported\n\t * as busy may become idle before the ioctl is completed.\n\t *\n\t * Furthermore, if the object is busy, which engine is busy is only\n\t * provided as a guide and only indirectly by reporting its class\n\t * (there may be more than one engine in each class). There are race\n\t * conditions which prevent the report of which engines are busy from\n\t * being always accurate.  However, the converse is not true. If the\n\t * object is idle, the result of the ioctl, that all engines are idle,\n\t * is accurate.\n\t *\n\t * The returned dword is split into two fields to indicate both\n\t * the engine classes on which the object is being read, and the\n\t * engine class on which it is currently being written (if any).\n\t *\n\t * The low word (bits 0:15) indicate if the object is being written\n\t * to by any engine (there can only be one, as the GEM implicit\n\t * synchronisation rules force writes to be serialised). Only the\n\t * engine class (offset by 1, I915_ENGINE_CLASS_RENDER is reported as\n\t * 1 not 0 etc) for the last write is reported.\n\t *\n\t * The high word (bits 16:31) are a bitmask of which engines classes\n\t * are currently reading from the object. Multiple engines may be\n\t * reading from the object simultaneously.\n\t *\n\t * The value of each engine class is the same as specified in the\n\t * I915_CONTEXT_PARAM_ENGINES context parameter and via perf, i.e.\n\t * I915_ENGINE_CLASS_RENDER, I915_ENGINE_CLASS_COPY, etc.\n\t * Some hardware may have parallel execution engines, e.g. multiple\n\t * media engines, which are mapped to the same class identifier and so\n\t * are not separately reported for busyness.\n\t *\n\t * Caveat emptor:\n\t * Only the boolean result of this query is reliable; that is whether\n\t * the object is idle or busy. The report of which engines are busy\n\t * should be only used as a heuristic.\n\t */\n\t__u32 busy;\n};\n\n/**\n * struct drm_i915_gem_caching - Set or get the caching for given object\n * handle.\n *\n * Allow userspace to control the GTT caching bits for a given object when the\n * object is later mapped through the ppGTT(or GGTT on older platforms lacking\n * ppGTT support, or if the object is used for scanout). Note that this might\n * require unbinding the object from the GTT first, if its current caching value\n * doesn't match.\n *\n * Note that this all changes on discrete platforms, starting from DG1, the\n * set/get caching is no longer supported, and is now rejected.  Instead the CPU\n * caching attributes(WB vs WC) will become an immutable creation time property\n * for the object, along with the GTT caching level. For now we don't expose any\n * new uAPI for this, instead on DG1 this is all implicit, although this largely\n * shouldn't matter since DG1 is coherent by default(without any way of\n * controlling it).\n *\n * Implicit caching rules, starting from DG1:\n *\n *     - If any of the object placements (see &drm_i915_gem_create_ext_memory_regions)\n *       contain I915_MEMORY_CLASS_DEVICE then the object will be allocated and\n *       mapped as write-combined only.\n *\n *     - Everything else is always allocated and mapped as write-back, with the\n *       guarantee that everything is also coherent with the GPU.\n *\n * Note that this is likely to change in the future again, where we might need\n * more flexibility on future devices, so making this all explicit as part of a\n * new &drm_i915_gem_create_ext extension is probable.\n *\n * Side note: Part of the reason for this is that changing the at-allocation-time CPU\n * caching attributes for the pages might be required(and is expensive) if we\n * need to then CPU map the pages later with different caching attributes. This\n * inconsistent caching behaviour, while supported on x86, is not universally\n * supported on other architectures. So for simplicity we opt for setting\n * everything at creation time, whilst also making it immutable, on discrete\n * platforms.\n */\nstruct drm_i915_gem_caching {\n\t/**\n\t * @handle: Handle of the buffer to set/get the caching level.\n\t */\n\t__u32 handle;\n\n\t/**\n\t * @caching: The GTT caching level to apply or possible return value.\n\t *\n\t * The supported @caching values:\n\t *\n\t * I915_CACHING_NONE:\n\t *\n\t * GPU access is not coherent with CPU caches.  Default for machines\n\t * without an LLC. This means manual flushing might be needed, if we\n\t * want GPU access to be coherent.\n\t *\n\t * I915_CACHING_CACHED:\n\t *\n\t * GPU access is coherent with CPU caches and furthermore the data is\n\t * cached in last-level caches shared between CPU cores and the GPU GT.\n\t *\n\t * I915_CACHING_DISPLAY:\n\t *\n\t * Special GPU caching mode which is coherent with the scanout engines.\n\t * Transparently falls back to I915_CACHING_NONE on platforms where no\n\t * special cache mode (like write-through or gfdt flushing) is\n\t * available. The kernel automatically sets this mode when using a\n\t * buffer as a scanout target.  Userspace can manually set this mode to\n\t * avoid a costly stall and clflush in the hotpath of drawing the first\n\t * frame.\n\t */\n#define I915_CACHING_NONE\t\t0\n#define I915_CACHING_CACHED\t\t1\n#define I915_CACHING_DISPLAY\t\t2\n\t__u32 caching;\n};\n\n#define I915_TILING_NONE\t0\n#define I915_TILING_X\t\t1\n#define I915_TILING_Y\t\t2\n/*\n * Do not add new tiling types here.  The I915_TILING_* values are for\n * de-tiling fence registers that no longer exist on modern platforms.  Although\n * the hardware may support new types of tiling in general (e.g., Tile4), we\n * do not need to add them to the uapi that is specific to now-defunct ioctls.\n */\n#define I915_TILING_LAST\tI915_TILING_Y\n\n#define I915_BIT_6_SWIZZLE_NONE\t\t0\n#define I915_BIT_6_SWIZZLE_9\t\t1\n#define I915_BIT_6_SWIZZLE_9_10\t\t2\n#define I915_BIT_6_SWIZZLE_9_11\t\t3\n#define I915_BIT_6_SWIZZLE_9_10_11\t4\n/* Not seen by userland */\n#define I915_BIT_6_SWIZZLE_UNKNOWN\t5\n/* Seen by userland. */\n#define I915_BIT_6_SWIZZLE_9_17\t\t6\n#define I915_BIT_6_SWIZZLE_9_10_17\t7\n\nstruct drm_i915_gem_set_tiling {\n\t/** Handle of the buffer to have its tiling state updated */\n\t__u32 handle;\n\n\t/**\n\t * Tiling mode for the object (I915_TILING_NONE, I915_TILING_X,\n\t * I915_TILING_Y).\n\t *\n\t * This value is to be set on request, and will be updated by the\n\t * kernel on successful return with the actual chosen tiling layout.\n\t *\n\t * The tiling mode may be demoted to I915_TILING_NONE when the system\n\t * has bit 6 swizzling that can't be managed correctly by GEM.\n\t *\n\t * Buffer contents become undefined when changing tiling_mode.\n\t */\n\t__u32 tiling_mode;\n\n\t/**\n\t * Stride in bytes for the object when in I915_TILING_X or\n\t * I915_TILING_Y.\n\t */\n\t__u32 stride;\n\n\t/**\n\t * Returned address bit 6 swizzling required for CPU access through\n\t * mmap mapping.\n\t */\n\t__u32 swizzle_mode;\n};\n\nstruct drm_i915_gem_get_tiling {\n\t/** Handle of the buffer to get tiling state for. */\n\t__u32 handle;\n\n\t/**\n\t * Current tiling mode for the object (I915_TILING_NONE, I915_TILING_X,\n\t * I915_TILING_Y).\n\t */\n\t__u32 tiling_mode;\n\n\t/**\n\t * Returned address bit 6 swizzling required for CPU access through\n\t * mmap mapping.\n\t */\n\t__u32 swizzle_mode;\n\n\t/**\n\t * Returned address bit 6 swizzling required for CPU access through\n\t * mmap mapping whilst bound.\n\t */\n\t__u32 phys_swizzle_mode;\n};\n\nstruct drm_i915_gem_get_aperture {\n\t/** Total size of the aperture used by i915_gem_execbuffer, in bytes */\n\t__u64 aper_size;\n\n\t/**\n\t * Available space in the aperture used by i915_gem_execbuffer, in\n\t * bytes\n\t */\n\t__u64 aper_available_size;\n};\n\nstruct drm_i915_get_pipe_from_crtc_id {\n\t/** ID of CRTC being requested **/\n\t__u32 crtc_id;\n\n\t/** pipe of requested CRTC **/\n\t__u32 pipe;\n};\n\n#define I915_MADV_WILLNEED 0\n#define I915_MADV_DONTNEED 1\n#define __I915_MADV_PURGED 2 /* internal state */\n\nstruct drm_i915_gem_madvise {\n\t/** Handle of the buffer to change the backing store advice */\n\t__u32 handle;\n\n\t/* Advice: either the buffer will be needed again in the near future,\n\t *         or won't be and could be discarded under memory pressure.\n\t */\n\t__u32 madv;\n\n\t/** Whether the backing store still exists. */\n\t__u32 retained;\n};\n\n/* flags */\n#define I915_OVERLAY_TYPE_MASK \t\t0xff\n#define I915_OVERLAY_YUV_PLANAR \t0x01\n#define I915_OVERLAY_YUV_PACKED \t0x02\n#define I915_OVERLAY_RGB\t\t0x03\n\n#define I915_OVERLAY_DEPTH_MASK\t\t0xff00\n#define I915_OVERLAY_RGB24\t\t0x1000\n#define I915_OVERLAY_RGB16\t\t0x2000\n#define I915_OVERLAY_RGB15\t\t0x3000\n#define I915_OVERLAY_YUV422\t\t0x0100\n#define I915_OVERLAY_YUV411\t\t0x0200\n#define I915_OVERLAY_YUV420\t\t0x0300\n#define I915_OVERLAY_YUV410\t\t0x0400\n\n#define I915_OVERLAY_SWAP_MASK\t\t0xff0000\n#define I915_OVERLAY_NO_SWAP\t\t0x000000\n#define I915_OVERLAY_UV_SWAP\t\t0x010000\n#define I915_OVERLAY_Y_SWAP\t\t0x020000\n#define I915_OVERLAY_Y_AND_UV_SWAP\t0x030000\n\n#define I915_OVERLAY_FLAGS_MASK\t\t0xff000000\n#define I915_OVERLAY_ENABLE\t\t0x01000000\n\nstruct drm_intel_overlay_put_image {\n\t/* various flags and src format description */\n\t__u32 flags;\n\t/* source picture description */\n\t__u32 bo_handle;\n\t/* stride values and offsets are in bytes, buffer relative */\n\t__u16 stride_Y; /* stride for packed formats */\n\t__u16 stride_UV;\n\t__u32 offset_Y; /* offset for packet formats */\n\t__u32 offset_U;\n\t__u32 offset_V;\n\t/* in pixels */\n\t__u16 src_width;\n\t__u16 src_height;\n\t/* to compensate the scaling factors for partially covered surfaces */\n\t__u16 src_scan_width;\n\t__u16 src_scan_height;\n\t/* output crtc description */\n\t__u32 crtc_id;\n\t__u16 dst_x;\n\t__u16 dst_y;\n\t__u16 dst_width;\n\t__u16 dst_height;\n};\n\n/* flags */\n#define I915_OVERLAY_UPDATE_ATTRS\t(1<<0)\n#define I915_OVERLAY_UPDATE_GAMMA\t(1<<1)\n#define I915_OVERLAY_DISABLE_DEST_COLORKEY\t(1<<2)\nstruct drm_intel_overlay_attrs {\n\t__u32 flags;\n\t__u32 color_key;\n\t__s32 brightness;\n\t__u32 contrast;\n\t__u32 saturation;\n\t__u32 gamma0;\n\t__u32 gamma1;\n\t__u32 gamma2;\n\t__u32 gamma3;\n\t__u32 gamma4;\n\t__u32 gamma5;\n};\n\n/*\n * Intel sprite handling\n *\n * Color keying works with a min/mask/max tuple.  Both source and destination\n * color keying is allowed.\n *\n * Source keying:\n * Sprite pixels within the min & max values, masked against the color channels\n * specified in the mask field, will be transparent.  All other pixels will\n * be displayed on top of the primary plane.  For RGB surfaces, only the min\n * and mask fields will be used; ranged compares are not allowed.\n *\n * Destination keying:\n * Primary plane pixels that match the min value, masked against the color\n * channels specified in the mask field, will be replaced by corresponding\n * pixels from the sprite plane.\n *\n * Note that source & destination keying are exclusive; only one can be\n * active on a given plane.\n */\n\n#define I915_SET_COLORKEY_NONE\t\t(1<<0) /* Deprecated. Instead set\n\t\t\t\t\t\t* flags==0 to disable colorkeying.\n\t\t\t\t\t\t*/\n#define I915_SET_COLORKEY_DESTINATION\t(1<<1)\n#define I915_SET_COLORKEY_SOURCE\t(1<<2)\nstruct drm_intel_sprite_colorkey {\n\t__u32 plane_id;\n\t__u32 min_value;\n\t__u32 channel_mask;\n\t__u32 max_value;\n\t__u32 flags;\n};\n\nstruct drm_i915_gem_wait {\n\t/** Handle of BO we shall wait on */\n\t__u32 bo_handle;\n\t__u32 flags;\n\t/** Number of nanoseconds to wait, Returns time remaining. */\n\t__s64 timeout_ns;\n};\n\nstruct drm_i915_gem_context_create {\n\t__u32 ctx_id; /* output: id of new context*/\n\t__u32 pad;\n};\n\n/**\n * struct drm_i915_gem_context_create_ext - Structure for creating contexts.\n */\nstruct drm_i915_gem_context_create_ext {\n\t/** @ctx_id: Id of the created context (output) */\n\t__u32 ctx_id;\n\n\t/**\n\t * @flags: Supported flags are:\n\t *\n\t * I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS:\n\t *\n\t * Extensions may be appended to this structure and driver must check\n\t * for those. See @extensions.\n\t *\n\t * I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE\n\t *\n\t * Created context will have single timeline.\n\t */\n\t__u32 flags;\n#define I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS\t(1u << 0)\n#define I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE\t(1u << 1)\n#define I915_CONTEXT_CREATE_FLAGS_UNKNOWN \\\n\t(-(I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE << 1))\n\n\t/**\n\t * @extensions: Zero-terminated chain of extensions.\n\t *\n\t * I915_CONTEXT_CREATE_EXT_SETPARAM:\n\t * Context parameter to set or query during context creation.\n\t * See struct drm_i915_gem_context_create_ext_setparam.\n\t *\n\t * I915_CONTEXT_CREATE_EXT_CLONE:\n\t * This extension has been removed. On the off chance someone somewhere\n\t * has attempted to use it, never re-use this extension number.\n\t */\n\t__u64 extensions;\n#define I915_CONTEXT_CREATE_EXT_SETPARAM 0\n#define I915_CONTEXT_CREATE_EXT_CLONE 1\n};\n\n/**\n * struct drm_i915_gem_context_param - Context parameter to set or query.\n */\nstruct drm_i915_gem_context_param {\n\t/** @ctx_id: Context id */\n\t__u32 ctx_id;\n\n\t/** @size: Size of the parameter @value */\n\t__u32 size;\n\n\t/** @param: Parameter to set or query */\n\t__u64 param;\n#define I915_CONTEXT_PARAM_BAN_PERIOD\t0x1\n/* I915_CONTEXT_PARAM_NO_ZEROMAP has been removed.  On the off chance\n * someone somewhere has attempted to use it, never re-use this context\n * param number.\n */\n#define I915_CONTEXT_PARAM_NO_ZEROMAP\t0x2\n#define I915_CONTEXT_PARAM_GTT_SIZE\t0x3\n#define I915_CONTEXT_PARAM_NO_ERROR_CAPTURE\t0x4\n#define I915_CONTEXT_PARAM_BANNABLE\t0x5\n#define I915_CONTEXT_PARAM_PRIORITY\t0x6\n#define   I915_CONTEXT_MAX_USER_PRIORITY\t1023 /* inclusive */\n#define   I915_CONTEXT_DEFAULT_PRIORITY\t\t0\n#define   I915_CONTEXT_MIN_USER_PRIORITY\t-1023 /* inclusive */\n\t/*\n\t * When using the following param, value should be a pointer to\n\t * drm_i915_gem_context_param_sseu.\n\t */\n#define I915_CONTEXT_PARAM_SSEU\t\t0x7\n\n/*\n * Not all clients may want to attempt automatic recover of a context after\n * a hang (for example, some clients may only submit very small incremental\n * batches relying on known logical state of previous batches which will never\n * recover correctly and each attempt will hang), and so would prefer that\n * the context is forever banned instead.\n *\n * If set to false (0), after a reset, subsequent (and in flight) rendering\n * from this context is discarded, and the client will need to create a new\n * context to use instead.\n *\n * If set to true (1), the kernel will automatically attempt to recover the\n * context by skipping the hanging batch and executing the next batch starting\n * from the default context state (discarding the incomplete logical context\n * state lost due to the reset).\n *\n * On creation, all new contexts are marked as recoverable.\n */\n#define I915_CONTEXT_PARAM_RECOVERABLE\t0x8\n\n\t/*\n\t * The id of the associated virtual memory address space (ppGTT) of\n\t * this context. Can be retrieved and passed to another context\n\t * (on the same fd) for both to use the same ppGTT and so share\n\t * address layouts, and avoid reloading the page tables on context\n\t * switches between themselves.\n\t *\n\t * See DRM_I915_GEM_VM_CREATE and DRM_I915_GEM_VM_DESTROY.\n\t */\n#define I915_CONTEXT_PARAM_VM\t\t0x9\n\n/*\n * I915_CONTEXT_PARAM_ENGINES:\n *\n * Bind this context to operate on this subset of available engines. Henceforth,\n * the I915_EXEC_RING selector for DRM_IOCTL_I915_GEM_EXECBUFFER2 operates as\n * an index into this array of engines; I915_EXEC_DEFAULT selecting engine[0]\n * and upwards. Slots 0...N are filled in using the specified (class, instance).\n * Use\n *\tengine_class: I915_ENGINE_CLASS_INVALID,\n *\tengine_instance: I915_ENGINE_CLASS_INVALID_NONE\n * to specify a gap in the array that can be filled in later, e.g. by a\n * virtual engine used for load balancing.\n *\n * Setting the number of engines bound to the context to 0, by passing a zero\n * sized argument, will revert back to default settings.\n *\n * See struct i915_context_param_engines.\n *\n * Extensions:\n *   i915_context_engines_load_balance (I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE)\n *   i915_context_engines_bond (I915_CONTEXT_ENGINES_EXT_BOND)\n *   i915_context_engines_parallel_submit (I915_CONTEXT_ENGINES_EXT_PARALLEL_SUBMIT)\n */\n#define I915_CONTEXT_PARAM_ENGINES\t0xa\n\n/*\n * I915_CONTEXT_PARAM_PERSISTENCE:\n *\n * Allow the context and active rendering to survive the process until\n * completion. Persistence allows fire-and-forget clients to queue up a\n * bunch of work, hand the output over to a display server and then quit.\n * If the context is marked as not persistent, upon closing (either via\n * an explicit DRM_I915_GEM_CONTEXT_DESTROY or implicitly from file closure\n * or process termination), the context and any outstanding requests will be\n * cancelled (and exported fences for cancelled requests marked as -EIO).\n *\n * By default, new contexts allow persistence.\n */\n#define I915_CONTEXT_PARAM_PERSISTENCE\t0xb\n\n/* This API has been removed.  On the off chance someone somewhere has\n * attempted to use it, never re-use this context param number.\n */\n#define I915_CONTEXT_PARAM_RINGSIZE\t0xc\n\n/*\n * I915_CONTEXT_PARAM_PROTECTED_CONTENT:\n *\n * Mark that the context makes use of protected content, which will result\n * in the context being invalidated when the protected content session is.\n * Given that the protected content session is killed on suspend, the device\n * is kept awake for the lifetime of a protected context, so the user should\n * make sure to dispose of them once done.\n * This flag can only be set at context creation time and, when set to true,\n * must be preceded by an explicit setting of I915_CONTEXT_PARAM_RECOVERABLE\n * to false. This flag can't be set to true in conjunction with setting the\n * I915_CONTEXT_PARAM_BANNABLE flag to false. Creation example:\n *\n * .. code-block:: C\n *\n *\tstruct drm_i915_gem_context_create_ext_setparam p_protected = {\n *\t\t.base = {\n *\t\t\t.name = I915_CONTEXT_CREATE_EXT_SETPARAM,\n *\t\t},\n *\t\t.param = {\n *\t\t\t.param = I915_CONTEXT_PARAM_PROTECTED_CONTENT,\n *\t\t\t.value = 1,\n *\t\t}\n *\t};\n *\tstruct drm_i915_gem_context_create_ext_setparam p_norecover = {\n *\t\t.base = {\n *\t\t\t.name = I915_CONTEXT_CREATE_EXT_SETPARAM,\n *\t\t\t.next_extension = to_user_pointer(&p_protected),\n *\t\t},\n *\t\t.param = {\n *\t\t\t.param = I915_CONTEXT_PARAM_RECOVERABLE,\n *\t\t\t.value = 0,\n *\t\t}\n *\t};\n *\tstruct drm_i915_gem_context_create_ext create = {\n *\t\t.flags = I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS,\n *\t\t.extensions = to_user_pointer(&p_norecover);\n *\t};\n *\n *\tctx_id = gem_context_create_ext(drm_fd, &create);\n *\n * In addition to the normal failure cases, setting this flag during context\n * creation can result in the following errors:\n *\n * -ENODEV: feature not available\n * -EPERM: trying to mark a recoverable or not bannable context as protected\n * -ENXIO: A dependency such as a component driver or firmware is not yet\n *         loaded so user space may need to attempt again. Depending on the\n *         device, this error may be reported if protected context creation is\n *         attempted very early after kernel start because the internal timeout\n *         waiting for such dependencies is not guaranteed to be larger than\n *         required (numbers differ depending on system and kernel config):\n *            - ADL/RPL: dependencies may take up to 3 seconds from kernel start\n *                       while context creation internal timeout is 250 milisecs\n *            - MTL: dependencies may take up to 8 seconds from kernel start\n *                   while context creation internal timeout is 250 milisecs\n *         NOTE: such dependencies happen once, so a subsequent call to create a\n *         protected context after a prior successful call will not experience\n *         such timeouts and will not return -ENXIO (unless the driver is reloaded,\n *         or, depending on the device, resumes from a suspended state).\n * -EIO: The firmware did not succeed in creating the protected context.\n */\n#define I915_CONTEXT_PARAM_PROTECTED_CONTENT    0xd\n/* Must be kept compact -- no holes and well documented */\n\n\t/** @value: Context parameter value to be set or queried */\n\t__u64 value;\n};\n\n/*\n * Context SSEU programming\n *\n * It may be necessary for either functional or performance reason to configure\n * a context to run with a reduced number of SSEU (where SSEU stands for Slice/\n * Sub-slice/EU).\n *\n * This is done by configuring SSEU configuration using the below\n * @struct drm_i915_gem_context_param_sseu for every supported engine which\n * userspace intends to use.\n *\n * Not all GPUs or engines support this functionality in which case an error\n * code -ENODEV will be returned.\n *\n * Also, flexibility of possible SSEU configuration permutations varies between\n * GPU generations and software imposed limitations. Requesting such a\n * combination will return an error code of -EINVAL.\n *\n * NOTE: When perf/OA is active the context's SSEU configuration is ignored in\n * favour of a single global setting.\n */\nstruct drm_i915_gem_context_param_sseu {\n\t/*\n\t * Engine class & instance to be configured or queried.\n\t */\n\tstruct i915_engine_class_instance engine;\n\n\t/*\n\t * Unknown flags must be cleared to zero.\n\t */\n\t__u32 flags;\n#define I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX (1u << 0)\n\n\t/*\n\t * Mask of slices to enable for the context. Valid values are a subset\n\t * of the bitmask value returned for I915_PARAM_SLICE_MASK.\n\t */\n\t__u64 slice_mask;\n\n\t/*\n\t * Mask of subslices to enable for the context. Valid values are a\n\t * subset of the bitmask value return by I915_PARAM_SUBSLICE_MASK.\n\t */\n\t__u64 subslice_mask;\n\n\t/*\n\t * Minimum/Maximum number of EUs to enable per subslice for the\n\t * context. min_eus_per_subslice must be inferior or equal to\n\t * max_eus_per_subslice.\n\t */\n\t__u16 min_eus_per_subslice;\n\t__u16 max_eus_per_subslice;\n\n\t/*\n\t * Unused for now. Must be cleared to zero.\n\t */\n\t__u32 rsvd;\n};\n\n/**\n * DOC: Virtual Engine uAPI\n *\n * Virtual engine is a concept where userspace is able to configure a set of\n * physical engines, submit a batch buffer, and let the driver execute it on any\n * engine from the set as it sees fit.\n *\n * This is primarily useful on parts which have multiple instances of a same\n * class engine, like for example GT3+ Skylake parts with their two VCS engines.\n *\n * For instance userspace can enumerate all engines of a certain class using the\n * previously described `Engine Discovery uAPI`_. After that userspace can\n * create a GEM context with a placeholder slot for the virtual engine (using\n * `I915_ENGINE_CLASS_INVALID` and `I915_ENGINE_CLASS_INVALID_NONE` for class\n * and instance respectively) and finally using the\n * `I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE` extension place a virtual engine in\n * the same reserved slot.\n *\n * Example of creating a virtual engine and submitting a batch buffer to it:\n *\n * .. code-block:: C\n *\n * \tI915_DEFINE_CONTEXT_ENGINES_LOAD_BALANCE(virtual, 2) = {\n * \t\t.base.name = I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE,\n * \t\t.engine_index = 0, // Place this virtual engine into engine map slot 0\n * \t\t.num_siblings = 2,\n * \t\t.engines = { { I915_ENGINE_CLASS_VIDEO, 0 },\n * \t\t\t     { I915_ENGINE_CLASS_VIDEO, 1 }, },\n * \t};\n * \tI915_DEFINE_CONTEXT_PARAM_ENGINES(engines, 1) = {\n * \t\t.engines = { { I915_ENGINE_CLASS_INVALID,\n * \t\t\t       I915_ENGINE_CLASS_INVALID_NONE } },\n * \t\t.extensions = to_user_pointer(&virtual), // Chains after load_balance extension\n * \t};\n * \tstruct drm_i915_gem_context_create_ext_setparam p_engines = {\n * \t\t.base = {\n * \t\t\t.name = I915_CONTEXT_CREATE_EXT_SETPARAM,\n * \t\t},\n * \t\t.param = {\n * \t\t\t.param = I915_CONTEXT_PARAM_ENGINES,\n * \t\t\t.value = to_user_pointer(&engines),\n * \t\t\t.size = sizeof(engines),\n * \t\t},\n * \t};\n * \tstruct drm_i915_gem_context_create_ext create = {\n * \t\t.flags = I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS,\n * \t\t.extensions = to_user_pointer(&p_engines);\n * \t};\n *\n * \tctx_id = gem_context_create_ext(drm_fd, &create);\n *\n * \t// Now we have created a GEM context with its engine map containing a\n * \t// single virtual engine. Submissions to this slot can go either to\n * \t// vcs0 or vcs1, depending on the load balancing algorithm used inside\n * \t// the driver. The load balancing is dynamic from one batch buffer to\n * \t// another and transparent to userspace.\n *\n * \t...\n * \texecbuf.rsvd1 = ctx_id;\n * \texecbuf.flags = 0; // Submits to index 0 which is the virtual engine\n * \tgem_execbuf(drm_fd, &execbuf);\n */\n\n/*\n * i915_context_engines_load_balance:\n *\n * Enable load balancing across this set of engines.\n *\n * Into the I915_EXEC_DEFAULT slot [0], a virtual engine is created that when\n * used will proxy the execbuffer request onto one of the set of engines\n * in such a way as to distribute the load evenly across the set.\n *\n * The set of engines must be compatible (e.g. the same HW class) as they\n * will share the same logical GPU context and ring.\n *\n * To intermix rendering with the virtual engine and direct rendering onto\n * the backing engines (bypassing the load balancing proxy), the context must\n * be defined to use a single timeline for all engines.\n */\nstruct i915_context_engines_load_balance {\n\tstruct i915_user_extension base;\n\n\t__u16 engine_index;\n\t__u16 num_siblings;\n\t__u32 flags; /* all undefined flags must be zero */\n\n\t__u64 mbz64; /* reserved for future use; must be zero */\n\n\tstruct i915_engine_class_instance engines[];\n} __attribute__((packed));\n\n#define I915_DEFINE_CONTEXT_ENGINES_LOAD_BALANCE(name__, N__) struct { \\\n\tstruct i915_user_extension base; \\\n\t__u16 engine_index; \\\n\t__u16 num_siblings; \\\n\t__u32 flags; \\\n\t__u64 mbz64; \\\n\tstruct i915_engine_class_instance engines[N__]; \\\n} __attribute__((packed)) name__\n\n/*\n * i915_context_engines_bond:\n *\n * Constructed bonded pairs for execution within a virtual engine.\n *\n * All engines are equal, but some are more equal than others. Given\n * the distribution of resources in the HW, it may be preferable to run\n * a request on a given subset of engines in parallel to a request on a\n * specific engine. We enable this selection of engines within a virtual\n * engine by specifying bonding pairs, for any given master engine we will\n * only execute on one of the corresponding siblings within the virtual engine.\n *\n * To execute a request in parallel on the master engine and a sibling requires\n * coordination with a I915_EXEC_FENCE_SUBMIT.\n */\nstruct i915_context_engines_bond {\n\tstruct i915_user_extension base;\n\n\tstruct i915_engine_class_instance master;\n\n\t__u16 virtual_index; /* index of virtual engine in ctx->engines[] */\n\t__u16 num_bonds;\n\n\t__u64 flags; /* all undefined flags must be zero */\n\t__u64 mbz64[4]; /* reserved for future use; must be zero */\n\n\tstruct i915_engine_class_instance engines[];\n} __attribute__((packed));\n\n#define I915_DEFINE_CONTEXT_ENGINES_BOND(name__, N__) struct { \\\n\tstruct i915_user_extension base; \\\n\tstruct i915_engine_class_instance master; \\\n\t__u16 virtual_index; \\\n\t__u16 num_bonds; \\\n\t__u64 flags; \\\n\t__u64 mbz64[4]; \\\n\tstruct i915_engine_class_instance engines[N__]; \\\n} __attribute__((packed)) name__\n\n/**\n * struct i915_context_engines_parallel_submit - Configure engine for\n * parallel submission.\n *\n * Setup a slot in the context engine map to allow multiple BBs to be submitted\n * in a single execbuf IOCTL. Those BBs will then be scheduled to run on the GPU\n * in parallel. Multiple hardware contexts are created internally in the i915 to\n * run these BBs. Once a slot is configured for N BBs only N BBs can be\n * submitted in each execbuf IOCTL and this is implicit behavior e.g. The user\n * doesn't tell the execbuf IOCTL there are N BBs, the execbuf IOCTL knows how\n * many BBs there are based on the slot's configuration. The N BBs are the last\n * N buffer objects or first N if I915_EXEC_BATCH_FIRST is set.\n *\n * The default placement behavior is to create implicit bonds between each\n * context if each context maps to more than 1 physical engine (e.g. context is\n * a virtual engine). Also we only allow contexts of same engine class and these\n * contexts must be in logically contiguous order. Examples of the placement\n * behavior are described below. Lastly, the default is to not allow BBs to be\n * preempted mid-batch. Rather insert coordinated preemption points on all\n * hardware contexts between each set of BBs. Flags could be added in the future\n * to change both of these default behaviors.\n *\n * Returns -EINVAL if hardware context placement configuration is invalid or if\n * the placement configuration isn't supported on the platform / submission\n * interface.\n * Returns -ENODEV if extension isn't supported on the platform / submission\n * interface.\n *\n * .. code-block:: none\n *\n *\tExamples syntax:\n *\tCS[X] = generic engine of same class, logical instance X\n *\tINVALID = I915_ENGINE_CLASS_INVALID, I915_ENGINE_CLASS_INVALID_NONE\n *\n *\tExample 1 pseudo code:\n *\tset_engines(INVALID)\n *\tset_parallel(engine_index=0, width=2, num_siblings=1,\n *\t\t     engines=CS[0],CS[1])\n *\n *\tResults in the following valid placement:\n *\tCS[0], CS[1]\n *\n *\tExample 2 pseudo code:\n *\tset_engines(INVALID)\n *\tset_parallel(engine_index=0, width=2, num_siblings=2,\n *\t\t     engines=CS[0],CS[2],CS[1],CS[3])\n *\n *\tResults in the following valid placements:\n *\tCS[0], CS[1]\n *\tCS[2], CS[3]\n *\n *\tThis can be thought of as two virtual engines, each containing two\n *\tengines thereby making a 2D array. However, there are bonds tying the\n *\tentries together and placing restrictions on how they can be scheduled.\n *\tSpecifically, the scheduler can choose only vertical columns from the 2D\n *\tarray. That is, CS[0] is bonded to CS[1] and CS[2] to CS[3]. So if the\n *\tscheduler wants to submit to CS[0], it must also choose CS[1] and vice\n *\tversa. Same for CS[2] requires also using CS[3].\n *\tVE[0] = CS[0], CS[2]\n *\tVE[1] = CS[1], CS[3]\n *\n *\tExample 3 pseudo code:\n *\tset_engines(INVALID)\n *\tset_parallel(engine_index=0, width=2, num_siblings=2,\n *\t\t     engines=CS[0],CS[1],CS[1],CS[3])\n *\n *\tResults in the following valid and invalid placements:\n *\tCS[0], CS[1]\n *\tCS[1], CS[3] - Not logically contiguous, return -EINVAL\n */\nstruct i915_context_engines_parallel_submit {\n\t/**\n\t * @base: base user extension.\n\t */\n\tstruct i915_user_extension base;\n\n\t/**\n\t * @engine_index: slot for parallel engine\n\t */\n\t__u16 engine_index;\n\n\t/**\n\t * @width: number of contexts per parallel engine or in other words the\n\t * number of batches in each submission\n\t */\n\t__u16 width;\n\n\t/**\n\t * @num_siblings: number of siblings per context or in other words the\n\t * number of possible placements for each submission\n\t */\n\t__u16 num_siblings;\n\n\t/**\n\t * @mbz16: reserved for future use; must be zero\n\t */\n\t__u16 mbz16;\n\n\t/**\n\t * @flags: all undefined flags must be zero, currently not defined flags\n\t */\n\t__u64 flags;\n\n\t/**\n\t * @mbz64: reserved for future use; must be zero\n\t */\n\t__u64 mbz64[3];\n\n\t/**\n\t * @engines: 2-d array of engine instances to configure parallel engine\n\t *\n\t * length = width (i) * num_siblings (j)\n\t * index = j + i * num_siblings\n\t */\n\tstruct i915_engine_class_instance engines[];\n\n} __attribute__((packed));\n\n#define I915_DEFINE_CONTEXT_ENGINES_PARALLEL_SUBMIT(name__, N__) struct { \\\n\tstruct i915_user_extension base; \\\n\t__u16 engine_index; \\\n\t__u16 width; \\\n\t__u16 num_siblings; \\\n\t__u16 mbz16; \\\n\t__u64 flags; \\\n\t__u64 mbz64[3]; \\\n\tstruct i915_engine_class_instance engines[N__]; \\\n} __attribute__((packed)) name__\n\n/**\n * DOC: Context Engine Map uAPI\n *\n * Context engine map is a new way of addressing engines when submitting batch-\n * buffers, replacing the existing way of using identifiers like `I915_EXEC_BLT`\n * inside the flags field of `struct drm_i915_gem_execbuffer2`.\n *\n * To use it created GEM contexts need to be configured with a list of engines\n * the user is intending to submit to. This is accomplished using the\n * `I915_CONTEXT_PARAM_ENGINES` parameter and `struct\n * i915_context_param_engines`.\n *\n * For such contexts the `I915_EXEC_RING_MASK` field becomes an index into the\n * configured map.\n *\n * Example of creating such context and submitting against it:\n *\n * .. code-block:: C\n *\n * \tI915_DEFINE_CONTEXT_PARAM_ENGINES(engines, 2) = {\n * \t\t.engines = { { I915_ENGINE_CLASS_RENDER, 0 },\n * \t\t\t     { I915_ENGINE_CLASS_COPY, 0 } }\n * \t};\n * \tstruct drm_i915_gem_context_create_ext_setparam p_engines = {\n * \t\t.base = {\n * \t\t\t.name = I915_CONTEXT_CREATE_EXT_SETPARAM,\n * \t\t},\n * \t\t.param = {\n * \t\t\t.param = I915_CONTEXT_PARAM_ENGINES,\n * \t\t\t.value = to_user_pointer(&engines),\n * \t\t\t.size = sizeof(engines),\n * \t\t},\n * \t};\n * \tstruct drm_i915_gem_context_create_ext create = {\n * \t\t.flags = I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS,\n * \t\t.extensions = to_user_pointer(&p_engines);\n * \t};\n *\n * \tctx_id = gem_context_create_ext(drm_fd, &create);\n *\n * \t// We have now created a GEM context with two engines in the map:\n * \t// Index 0 points to rcs0 while index 1 points to bcs0. Other engines\n * \t// will not be accessible from this context.\n *\n * \t...\n * \texecbuf.rsvd1 = ctx_id;\n * \texecbuf.flags = 0; // Submits to index 0, which is rcs0 for this context\n * \tgem_execbuf(drm_fd, &execbuf);\n *\n * \t...\n * \texecbuf.rsvd1 = ctx_id;\n * \texecbuf.flags = 1; // Submits to index 0, which is bcs0 for this context\n * \tgem_execbuf(drm_fd, &execbuf);\n */\n\nstruct i915_context_param_engines {\n\t__u64 extensions; /* linked chain of extension blocks, 0 terminates */\n#define I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE 0 /* see i915_context_engines_load_balance */\n#define I915_CONTEXT_ENGINES_EXT_BOND 1 /* see i915_context_engines_bond */\n#define I915_CONTEXT_ENGINES_EXT_PARALLEL_SUBMIT 2 /* see i915_context_engines_parallel_submit */\n\tstruct i915_engine_class_instance engines[];\n} __attribute__((packed));\n\n#define I915_DEFINE_CONTEXT_PARAM_ENGINES(name__, N__) struct { \\\n\t__u64 extensions; \\\n\tstruct i915_engine_class_instance engines[N__]; \\\n} __attribute__((packed)) name__\n\n/**\n * struct drm_i915_gem_context_create_ext_setparam - Context parameter\n * to set or query during context creation.\n */\nstruct drm_i915_gem_context_create_ext_setparam {\n\t/** @base: Extension link. See struct i915_user_extension. */\n\tstruct i915_user_extension base;\n\n\t/**\n\t * @param: Context parameter to set or query.\n\t * See struct drm_i915_gem_context_param.\n\t */\n\tstruct drm_i915_gem_context_param param;\n};\n\nstruct drm_i915_gem_context_destroy {\n\t__u32 ctx_id;\n\t__u32 pad;\n};\n\n/**\n * struct drm_i915_gem_vm_control - Structure to create or destroy VM.\n *\n * DRM_I915_GEM_VM_CREATE -\n *\n * Create a new virtual memory address space (ppGTT) for use within a context\n * on the same file. Extensions can be provided to configure exactly how the\n * address space is setup upon creation.\n *\n * The id of new VM (bound to the fd) for use with I915_CONTEXT_PARAM_VM is\n * returned in the outparam @id.\n *\n * An extension chain maybe provided, starting with @extensions, and terminated\n * by the @next_extension being 0. Currently, no extensions are defined.\n *\n * DRM_I915_GEM_VM_DESTROY -\n *\n * Destroys a previously created VM id, specified in @vm_id.\n *\n * No extensions or flags are allowed currently, and so must be zero.\n */\nstruct drm_i915_gem_vm_control {\n\t/** @extensions: Zero-terminated chain of extensions. */\n\t__u64 extensions;\n\n\t/** @flags: reserved for future usage, currently MBZ */\n\t__u32 flags;\n\n\t/** @vm_id: Id of the VM created or to be destroyed */\n\t__u32 vm_id;\n};\n\nstruct drm_i915_reg_read {\n\t/*\n\t * Register offset.\n\t * For 64bit wide registers where the upper 32bits don't immediately\n\t * follow the lower 32bits, the offset of the lower 32bits must\n\t * be specified\n\t */\n\t__u64 offset;\n#define I915_REG_READ_8B_WA (1ul << 0)\n\n\t__u64 val; /* Return value */\n};\n\n/* Known registers:\n *\n * Render engine timestamp - 0x2358 + 64bit - gen7+\n * - Note this register returns an invalid value if using the default\n *   single instruction 8byte read, in order to workaround that pass\n *   flag I915_REG_READ_8B_WA in offset field.\n *\n */\n\nstruct drm_i915_reset_stats {\n\t__u32 ctx_id;\n\t__u32 flags;\n\n\t/* All resets since boot/module reload, for all contexts */\n\t__u32 reset_count;\n\n\t/* Number of batches lost when active in GPU, for this context */\n\t__u32 batch_active;\n\n\t/* Number of batches lost pending for execution, for this context */\n\t__u32 batch_pending;\n\n\t__u32 pad;\n};\n\n/**\n * struct drm_i915_gem_userptr - Create GEM object from user allocated memory.\n *\n * Userptr objects have several restrictions on what ioctls can be used with the\n * object handle.\n */\nstruct drm_i915_gem_userptr {\n\t/**\n\t * @user_ptr: The pointer to the allocated memory.\n\t *\n\t * Needs to be aligned to PAGE_SIZE.\n\t */\n\t__u64 user_ptr;\n\n\t/**\n\t * @user_size:\n\t *\n\t * The size in bytes for the allocated memory. This will also become the\n\t * object size.\n\t *\n\t * Needs to be aligned to PAGE_SIZE, and should be at least PAGE_SIZE,\n\t * or larger.\n\t */\n\t__u64 user_size;\n\n\t/**\n\t * @flags:\n\t *\n\t * Supported flags:\n\t *\n\t * I915_USERPTR_READ_ONLY:\n\t *\n\t * Mark the object as readonly, this also means GPU access can only be\n\t * readonly. This is only supported on HW which supports readonly access\n\t * through the GTT. If the HW can't support readonly access, an error is\n\t * returned.\n\t *\n\t * I915_USERPTR_PROBE:\n\t *\n\t * Probe the provided @user_ptr range and validate that the @user_ptr is\n\t * indeed pointing to normal memory and that the range is also valid.\n\t * For example if some garbage address is given to the kernel, then this\n\t * should complain.\n\t *\n\t * Returns -EFAULT if the probe failed.\n\t *\n\t * Note that this doesn't populate the backing pages, and also doesn't\n\t * guarantee that the object will remain valid when the object is\n\t * eventually used.\n\t *\n\t * The kernel supports this feature if I915_PARAM_HAS_USERPTR_PROBE\n\t * returns a non-zero value.\n\t *\n\t * I915_USERPTR_UNSYNCHRONIZED:\n\t *\n\t * NOT USED. Setting this flag will result in an error.\n\t */\n\t__u32 flags;\n#define I915_USERPTR_READ_ONLY 0x1\n#define I915_USERPTR_PROBE 0x2\n#define I915_USERPTR_UNSYNCHRONIZED 0x80000000\n\t/**\n\t * @handle: Returned handle for the object.\n\t *\n\t * Object handles are nonzero.\n\t */\n\t__u32 handle;\n};\n\nenum drm_i915_oa_format {\n\tI915_OA_FORMAT_A13 = 1,\t    /* HSW only */\n\tI915_OA_FORMAT_A29,\t    /* HSW only */\n\tI915_OA_FORMAT_A13_B8_C8,   /* HSW only */\n\tI915_OA_FORMAT_B4_C8,\t    /* HSW only */\n\tI915_OA_FORMAT_A45_B8_C8,   /* HSW only */\n\tI915_OA_FORMAT_B4_C8_A16,   /* HSW only */\n\tI915_OA_FORMAT_C4_B8,\t    /* HSW+ */\n\n\t/* Gen8+ */\n\tI915_OA_FORMAT_A12,\n\tI915_OA_FORMAT_A12_B8_C8,\n\tI915_OA_FORMAT_A32u40_A4u32_B8_C8,\n\n\t/* DG2 */\n\tI915_OAR_FORMAT_A32u40_A4u32_B8_C8,\n\tI915_OA_FORMAT_A24u40_A14u32_B8_C8,\n\n\t/* MTL OAM */\n\tI915_OAM_FORMAT_MPEC8u64_B8_C8,\n\tI915_OAM_FORMAT_MPEC8u32_B8_C8,\n\n\tI915_OA_FORMAT_MAX\t    /* non-ABI */\n};\n\nenum drm_i915_perf_property_id {\n\t/**\n\t * Open the stream for a specific context handle (as used with\n\t * execbuffer2). A stream opened for a specific context this way\n\t * won't typically require root privileges.\n\t *\n\t * This property is available in perf revision 1.\n\t */\n\tDRM_I915_PERF_PROP_CTX_HANDLE = 1,\n\n\t/**\n\t * A value of 1 requests the inclusion of raw OA unit reports as\n\t * part of stream samples.\n\t *\n\t * This property is available in perf revision 1.\n\t */\n\tDRM_I915_PERF_PROP_SAMPLE_OA,\n\n\t/**\n\t * The value specifies which set of OA unit metrics should be\n\t * configured, defining the contents of any OA unit reports.\n\t *\n\t * This property is available in perf revision 1.\n\t */\n\tDRM_I915_PERF_PROP_OA_METRICS_SET,\n\n\t/**\n\t * The value specifies the size and layout of OA unit reports.\n\t *\n\t * This property is available in perf revision 1.\n\t */\n\tDRM_I915_PERF_PROP_OA_FORMAT,\n\n\t/**\n\t * Specifying this property implicitly requests periodic OA unit\n\t * sampling and (at least on Haswell) the sampling frequency is derived\n\t * from this exponent as follows:\n\t *\n\t *   80ns * 2^(period_exponent + 1)\n\t *\n\t * This property is available in perf revision 1.\n\t */\n\tDRM_I915_PERF_PROP_OA_EXPONENT,\n\n\t/**\n\t * Specifying this property is only valid when specify a context to\n\t * filter with DRM_I915_PERF_PROP_CTX_HANDLE. Specifying this property\n\t * will hold preemption of the particular context we want to gather\n\t * performance data about. The execbuf2 submissions must include a\n\t * drm_i915_gem_execbuffer_ext_perf parameter for this to apply.\n\t *\n\t * This property is available in perf revision 3.\n\t */\n\tDRM_I915_PERF_PROP_HOLD_PREEMPTION,\n\n\t/**\n\t * Specifying this pins all contexts to the specified SSEU power\n\t * configuration for the duration of the recording.\n\t *\n\t * This parameter's value is a pointer to a struct\n\t * drm_i915_gem_context_param_sseu.\n\t *\n\t * This property is available in perf revision 4.\n\t */\n\tDRM_I915_PERF_PROP_GLOBAL_SSEU,\n\n\t/**\n\t * This optional parameter specifies the timer interval in nanoseconds\n\t * at which the i915 driver will check the OA buffer for available data.\n\t * Minimum allowed value is 100 microseconds. A default value is used by\n\t * the driver if this parameter is not specified. Note that larger timer\n\t * values will reduce cpu consumption during OA perf captures. However,\n\t * excessively large values would potentially result in OA buffer\n\t * overwrites as captures reach end of the OA buffer.\n\t *\n\t * This property is available in perf revision 5.\n\t */\n\tDRM_I915_PERF_PROP_POLL_OA_PERIOD,\n\n\t/**\n\t * Multiple engines may be mapped to the same OA unit. The OA unit is\n\t * identified by class:instance of any engine mapped to it.\n\t *\n\t * This parameter specifies the engine class and must be passed along\n\t * with DRM_I915_PERF_PROP_OA_ENGINE_INSTANCE.\n\t *\n\t * This property is available in perf revision 6.\n\t */\n\tDRM_I915_PERF_PROP_OA_ENGINE_CLASS,\n\n\t/**\n\t * This parameter specifies the engine instance and must be passed along\n\t * with DRM_I915_PERF_PROP_OA_ENGINE_CLASS.\n\t *\n\t * This property is available in perf revision 6.\n\t */\n\tDRM_I915_PERF_PROP_OA_ENGINE_INSTANCE,\n\n\tDRM_I915_PERF_PROP_MAX /* non-ABI */\n};\n\nstruct drm_i915_perf_open_param {\n\t__u32 flags;\n#define I915_PERF_FLAG_FD_CLOEXEC\t(1<<0)\n#define I915_PERF_FLAG_FD_NONBLOCK\t(1<<1)\n#define I915_PERF_FLAG_DISABLED\t\t(1<<2)\n\n\t/** The number of u64 (id, value) pairs */\n\t__u32 num_properties;\n\n\t/**\n\t * Pointer to array of u64 (id, value) pairs configuring the stream\n\t * to open.\n\t */\n\t__u64 properties_ptr;\n};\n\n/*\n * Enable data capture for a stream that was either opened in a disabled state\n * via I915_PERF_FLAG_DISABLED or was later disabled via\n * I915_PERF_IOCTL_DISABLE.\n *\n * It is intended to be cheaper to disable and enable a stream than it may be\n * to close and re-open a stream with the same configuration.\n *\n * It's undefined whether any pending data for the stream will be lost.\n *\n * This ioctl is available in perf revision 1.\n */\n#define I915_PERF_IOCTL_ENABLE\t_IO('i', 0x0)\n\n/*\n * Disable data capture for a stream.\n *\n * It is an error to try and read a stream that is disabled.\n *\n * This ioctl is available in perf revision 1.\n */\n#define I915_PERF_IOCTL_DISABLE\t_IO('i', 0x1)\n\n/*\n * Change metrics_set captured by a stream.\n *\n * If the stream is bound to a specific context, the configuration change\n * will performed __inline__ with that context such that it takes effect before\n * the next execbuf submission.\n *\n * Returns the previously bound metrics set id, or a negative error code.\n *\n * This ioctl is available in perf revision 2.\n */\n#define I915_PERF_IOCTL_CONFIG\t_IO('i', 0x2)\n\n/*\n * Common to all i915 perf records\n */\nstruct drm_i915_perf_record_header {\n\t__u32 type;\n\t__u16 pad;\n\t__u16 size;\n};\n\nenum drm_i915_perf_record_type {\n\n\t/**\n\t * Samples are the work horse record type whose contents are extensible\n\t * and defined when opening an i915 perf stream based on the given\n\t * properties.\n\t *\n\t * Boolean properties following the naming convention\n\t * DRM_I915_PERF_SAMPLE_xyz_PROP request the inclusion of 'xyz' data in\n\t * every sample.\n\t *\n\t * The order of these sample properties given by userspace has no\n\t * affect on the ordering of data within a sample. The order is\n\t * documented here.\n\t *\n\t * struct {\n\t *     struct drm_i915_perf_record_header header;\n\t *\n\t *     { u32 oa_report[]; } && DRM_I915_PERF_PROP_SAMPLE_OA\n\t * };\n\t */\n\tDRM_I915_PERF_RECORD_SAMPLE = 1,\n\n\t/*\n\t * Indicates that one or more OA reports were not written by the\n\t * hardware. This can happen for example if an MI_REPORT_PERF_COUNT\n\t * command collides with periodic sampling - which would be more likely\n\t * at higher sampling frequencies.\n\t */\n\tDRM_I915_PERF_RECORD_OA_REPORT_LOST = 2,\n\n\t/**\n\t * An error occurred that resulted in all pending OA reports being lost.\n\t */\n\tDRM_I915_PERF_RECORD_OA_BUFFER_LOST = 3,\n\n\tDRM_I915_PERF_RECORD_MAX /* non-ABI */\n};\n\n/**\n * struct drm_i915_perf_oa_config\n *\n * Structure to upload perf dynamic configuration into the kernel.\n */\nstruct drm_i915_perf_oa_config {\n\t/**\n\t * @uuid:\n\t *\n\t * String formatted like \"%\\08x-%\\04x-%\\04x-%\\04x-%\\012x\"\n\t */\n\tchar uuid[36];\n\n\t/**\n\t * @n_mux_regs:\n\t *\n\t * Number of mux regs in &mux_regs_ptr.\n\t */\n\t__u32 n_mux_regs;\n\n\t/**\n\t * @n_boolean_regs:\n\t *\n\t * Number of boolean regs in &boolean_regs_ptr.\n\t */\n\t__u32 n_boolean_regs;\n\n\t/**\n\t * @n_flex_regs:\n\t *\n\t * Number of flex regs in &flex_regs_ptr.\n\t */\n\t__u32 n_flex_regs;\n\n\t/**\n\t * @mux_regs_ptr:\n\t *\n\t * Pointer to tuples of u32 values (register address, value) for mux\n\t * registers.  Expected length of buffer is (2 * sizeof(u32) *\n\t * &n_mux_regs).\n\t */\n\t__u64 mux_regs_ptr;\n\n\t/**\n\t * @boolean_regs_ptr:\n\t *\n\t * Pointer to tuples of u32 values (register address, value) for mux\n\t * registers.  Expected length of buffer is (2 * sizeof(u32) *\n\t * &n_boolean_regs).\n\t */\n\t__u64 boolean_regs_ptr;\n\n\t/**\n\t * @flex_regs_ptr:\n\t *\n\t * Pointer to tuples of u32 values (register address, value) for mux\n\t * registers.  Expected length of buffer is (2 * sizeof(u32) *\n\t * &n_flex_regs).\n\t */\n\t__u64 flex_regs_ptr;\n};\n\n/**\n * struct drm_i915_query_item - An individual query for the kernel to process.\n *\n * The behaviour is determined by the @query_id. Note that exactly what\n * @data_ptr is also depends on the specific @query_id.\n */\nstruct drm_i915_query_item {\n\t/**\n\t * @query_id:\n\t *\n\t * The id for this query.  Currently accepted query IDs are:\n\t *  - %DRM_I915_QUERY_TOPOLOGY_INFO (see struct drm_i915_query_topology_info)\n\t *  - %DRM_I915_QUERY_ENGINE_INFO (see struct drm_i915_engine_info)\n\t *  - %DRM_I915_QUERY_PERF_CONFIG (see struct drm_i915_query_perf_config)\n\t *  - %DRM_I915_QUERY_MEMORY_REGIONS (see struct drm_i915_query_memory_regions)\n\t *  - %DRM_I915_QUERY_HWCONFIG_BLOB (see `GuC HWCONFIG blob uAPI`)\n\t *  - %DRM_I915_QUERY_GEOMETRY_SUBSLICES (see struct drm_i915_query_topology_info)\n\t *  - %DRM_I915_QUERY_GUC_SUBMISSION_VERSION (see struct drm_i915_query_guc_submission_version)\n\t */\n\t__u64 query_id;\n#define DRM_I915_QUERY_TOPOLOGY_INFO\t\t1\n#define DRM_I915_QUERY_ENGINE_INFO\t\t2\n#define DRM_I915_QUERY_PERF_CONFIG\t\t3\n#define DRM_I915_QUERY_MEMORY_REGIONS\t\t4\n#define DRM_I915_QUERY_HWCONFIG_BLOB\t\t5\n#define DRM_I915_QUERY_GEOMETRY_SUBSLICES\t6\n#define DRM_I915_QUERY_GUC_SUBMISSION_VERSION\t7\n/* Must be kept compact -- no holes and well documented */\n\n\t/**\n\t * @length:\n\t *\n\t * When set to zero by userspace, this is filled with the size of the\n\t * data to be written at the @data_ptr pointer. The kernel sets this\n\t * value to a negative value to signal an error on a particular query\n\t * item.\n\t */\n\t__s32 length;\n\n\t/**\n\t * @flags:\n\t *\n\t * When &query_id == %DRM_I915_QUERY_TOPOLOGY_INFO, must be 0.\n\t *\n\t * When &query_id == %DRM_I915_QUERY_PERF_CONFIG, must be one of the\n\t * following:\n\t *\n\t *\t- %DRM_I915_QUERY_PERF_CONFIG_LIST\n\t *      - %DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID\n\t *      - %DRM_I915_QUERY_PERF_CONFIG_FOR_UUID\n\t *\n\t * When &query_id == %DRM_I915_QUERY_GEOMETRY_SUBSLICES must contain\n\t * a struct i915_engine_class_instance that references a render engine.\n\t */\n\t__u32 flags;\n#define DRM_I915_QUERY_PERF_CONFIG_LIST          1\n#define DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID 2\n#define DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_ID   3\n\n\t/**\n\t * @data_ptr:\n\t *\n\t * Data will be written at the location pointed by @data_ptr when the\n\t * value of @length matches the length of the data to be written by the\n\t * kernel.\n\t */\n\t__u64 data_ptr;\n};\n\n/**\n * struct drm_i915_query - Supply an array of struct drm_i915_query_item for the\n * kernel to fill out.\n *\n * Note that this is generally a two step process for each struct\n * drm_i915_query_item in the array:\n *\n * 1. Call the DRM_IOCTL_I915_QUERY, giving it our array of struct\n *    drm_i915_query_item, with &drm_i915_query_item.length set to zero. The\n *    kernel will then fill in the size, in bytes, which tells userspace how\n *    memory it needs to allocate for the blob(say for an array of properties).\n *\n * 2. Next we call DRM_IOCTL_I915_QUERY again, this time with the\n *    &drm_i915_query_item.data_ptr equal to our newly allocated blob. Note that\n *    the &drm_i915_query_item.length should still be the same as what the\n *    kernel previously set. At this point the kernel can fill in the blob.\n *\n * Note that for some query items it can make sense for userspace to just pass\n * in a buffer/blob equal to or larger than the required size. In this case only\n * a single ioctl call is needed. For some smaller query items this can work\n * quite well.\n *\n */\nstruct drm_i915_query {\n\t/** @num_items: The number of elements in the @items_ptr array */\n\t__u32 num_items;\n\n\t/**\n\t * @flags: Unused for now. Must be cleared to zero.\n\t */\n\t__u32 flags;\n\n\t/**\n\t * @items_ptr:\n\t *\n\t * Pointer to an array of struct drm_i915_query_item. The number of\n\t * array elements is @num_items.\n\t */\n\t__u64 items_ptr;\n};\n\n/**\n * struct drm_i915_query_topology_info\n *\n * Describes slice/subslice/EU information queried by\n * %DRM_I915_QUERY_TOPOLOGY_INFO\n */\nstruct drm_i915_query_topology_info {\n\t/**\n\t * @flags:\n\t *\n\t * Unused for now. Must be cleared to zero.\n\t */\n\t__u16 flags;\n\n\t/**\n\t * @max_slices:\n\t *\n\t * The number of bits used to express the slice mask.\n\t */\n\t__u16 max_slices;\n\n\t/**\n\t * @max_subslices:\n\t *\n\t * The number of bits used to express the subslice mask.\n\t */\n\t__u16 max_subslices;\n\n\t/**\n\t * @max_eus_per_subslice:\n\t *\n\t * The number of bits in the EU mask that correspond to a single\n\t * subslice's EUs.\n\t */\n\t__u16 max_eus_per_subslice;\n\n\t/**\n\t * @subslice_offset:\n\t *\n\t * Offset in data[] at which the subslice masks are stored.\n\t */\n\t__u16 subslice_offset;\n\n\t/**\n\t * @subslice_stride:\n\t *\n\t * Stride at which each of the subslice masks for each slice are\n\t * stored.\n\t */\n\t__u16 subslice_stride;\n\n\t/**\n\t * @eu_offset:\n\t *\n\t * Offset in data[] at which the EU masks are stored.\n\t */\n\t__u16 eu_offset;\n\n\t/**\n\t * @eu_stride:\n\t *\n\t * Stride at which each of the EU masks for each subslice are stored.\n\t */\n\t__u16 eu_stride;\n\n\t/**\n\t * @data:\n\t *\n\t * Contains 3 pieces of information :\n\t *\n\t * - The slice mask with one bit per slice telling whether a slice is\n\t *   available. The availability of slice X can be queried with the\n\t *   following formula :\n\t *\n\t *   .. code:: c\n\t *\n\t *      (data[X / 8] >> (X % 8)) & 1\n\t *\n\t *   Starting with Xe_HP platforms, Intel hardware no longer has\n\t *   traditional slices so i915 will always report a single slice\n\t *   (hardcoded slicemask = 0x1) which contains all of the platform's\n\t *   subslices.  I.e., the mask here does not reflect any of the newer\n\t *   hardware concepts such as \"gslices\" or \"cslices\" since userspace\n\t *   is capable of inferring those from the subslice mask.\n\t *\n\t * - The subslice mask for each slice with one bit per subslice telling\n\t *   whether a subslice is available.  Starting with Gen12 we use the\n\t *   term \"subslice\" to refer to what the hardware documentation\n\t *   describes as a \"dual-subslices.\"  The availability of subslice Y\n\t *   in slice X can be queried with the following formula :\n\t *\n\t *   .. code:: c\n\t *\n\t *      (data[subslice_offset + X * subslice_stride + Y / 8] >> (Y % 8)) & 1\n\t *\n\t * - The EU mask for each subslice in each slice, with one bit per EU\n\t *   telling whether an EU is available. The availability of EU Z in\n\t *   subslice Y in slice X can be queried with the following formula :\n\t *\n\t *   .. code:: c\n\t *\n\t *      (data[eu_offset +\n\t *            (X * max_subslices + Y) * eu_stride +\n\t *            Z / 8\n\t *       ] >> (Z % 8)) & 1\n\t */\n\t__u8 data[];\n};\n\n/**\n * DOC: Engine Discovery uAPI\n *\n * Engine discovery uAPI is a way of enumerating physical engines present in a\n * GPU associated with an open i915 DRM file descriptor. This supersedes the old\n * way of using `DRM_IOCTL_I915_GETPARAM` and engine identifiers like\n * `I915_PARAM_HAS_BLT`.\n *\n * The need for this interface came starting with Icelake and newer GPUs, which\n * started to establish a pattern of having multiple engines of a same class,\n * where not all instances were always completely functionally equivalent.\n *\n * Entry point for this uapi is `DRM_IOCTL_I915_QUERY` with the\n * `DRM_I915_QUERY_ENGINE_INFO` as the queried item id.\n *\n * Example for getting the list of engines:\n *\n * .. code-block:: C\n *\n * \tstruct drm_i915_query_engine_info *info;\n * \tstruct drm_i915_query_item item = {\n * \t\t.query_id = DRM_I915_QUERY_ENGINE_INFO;\n * \t};\n * \tstruct drm_i915_query query = {\n * \t\t.num_items = 1,\n * \t\t.items_ptr = (uintptr_t)&item,\n * \t};\n * \tint err, i;\n *\n * \t// First query the size of the blob we need, this needs to be large\n * \t// enough to hold our array of engines. The kernel will fill out the\n * \t// item.length for us, which is the number of bytes we need.\n * \t//\n *\t// Alternatively a large buffer can be allocated straightaway enabling\n * \t// querying in one pass, in which case item.length should contain the\n * \t// length of the provided buffer.\n * \terr = ioctl(fd, DRM_IOCTL_I915_QUERY, &query);\n * \tif (err) ...\n *\n * \tinfo = calloc(1, item.length);\n * \t// Now that we allocated the required number of bytes, we call the ioctl\n * \t// again, this time with the data_ptr pointing to our newly allocated\n * \t// blob, which the kernel can then populate with info on all engines.\n *\titem.data_ptr = (uintptr_t)&info;\n *\n * \terr = ioctl(fd, DRM_IOCTL_I915_QUERY, &query);\n * \tif (err) ...\n *\n * \t// We can now access each engine in the array\n * \tfor (i = 0; i < info->num_engines; i++) {\n * \t\tstruct drm_i915_engine_info einfo = info->engines[i];\n * \t\tu16 class = einfo.engine.class;\n * \t\tu16 instance = einfo.engine.instance;\n * \t\t....\n * \t}\n *\n * \tfree(info);\n *\n * Each of the enumerated engines, apart from being defined by its class and\n * instance (see `struct i915_engine_class_instance`), also can have flags and\n * capabilities defined as documented in i915_drm.h.\n *\n * For instance video engines which support HEVC encoding will have the\n * `I915_VIDEO_CLASS_CAPABILITY_HEVC` capability bit set.\n *\n * Engine discovery only fully comes to its own when combined with the new way\n * of addressing engines when submitting batch buffers using contexts with\n * engine maps configured.\n */\n\n/**\n * struct drm_i915_engine_info\n *\n * Describes one engine and its capabilities as known to the driver.\n */\nstruct drm_i915_engine_info {\n\t/** @engine: Engine class and instance. */\n\tstruct i915_engine_class_instance engine;\n\n\t/** @rsvd0: Reserved field. */\n\t__u32 rsvd0;\n\n\t/** @flags: Engine flags. */\n\t__u64 flags;\n#define I915_ENGINE_INFO_HAS_LOGICAL_INSTANCE\t\t(1 << 0)\n\n\t/** @capabilities: Capabilities of this engine. */\n\t__u64 capabilities;\n#define I915_VIDEO_CLASS_CAPABILITY_HEVC\t\t(1 << 0)\n#define I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC\t(1 << 1)\n\n\t/** @logical_instance: Logical instance of engine */\n\t__u16 logical_instance;\n\n\t/** @rsvd1: Reserved fields. */\n\t__u16 rsvd1[3];\n\t/** @rsvd2: Reserved fields. */\n\t__u64 rsvd2[3];\n};\n\n/**\n * struct drm_i915_query_engine_info\n *\n * Engine info query enumerates all engines known to the driver by filling in\n * an array of struct drm_i915_engine_info structures.\n */\nstruct drm_i915_query_engine_info {\n\t/** @num_engines: Number of struct drm_i915_engine_info structs following. */\n\t__u32 num_engines;\n\n\t/** @rsvd: MBZ */\n\t__u32 rsvd[3];\n\n\t/** @engines: Marker for drm_i915_engine_info structures. */\n\tstruct drm_i915_engine_info engines[];\n};\n\n/**\n * struct drm_i915_query_perf_config\n *\n * Data written by the kernel with query %DRM_I915_QUERY_PERF_CONFIG and\n * %DRM_I915_QUERY_GEOMETRY_SUBSLICES.\n */\nstruct drm_i915_query_perf_config {\n\tunion {\n\t\t/**\n\t\t * @n_configs:\n\t\t *\n\t\t * When &drm_i915_query_item.flags ==\n\t\t * %DRM_I915_QUERY_PERF_CONFIG_LIST, i915 sets this fields to\n\t\t * the number of configurations available.\n\t\t */\n\t\t__u64 n_configs;\n\n\t\t/**\n\t\t * @config:\n\t\t *\n\t\t * When &drm_i915_query_item.flags ==\n\t\t * %DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_ID, i915 will use the\n\t\t * value in this field as configuration identifier to decide\n\t\t * what data to write into config_ptr.\n\t\t */\n\t\t__u64 config;\n\n\t\t/**\n\t\t * @uuid:\n\t\t *\n\t\t * When &drm_i915_query_item.flags ==\n\t\t * %DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID, i915 will use the\n\t\t * value in this field as configuration identifier to decide\n\t\t * what data to write into config_ptr.\n\t\t *\n\t\t * String formatted like \"%08x-%04x-%04x-%04x-%012x\"\n\t\t */\n\t\tchar uuid[36];\n\t};\n\n\t/**\n\t * @flags:\n\t *\n\t * Unused for now. Must be cleared to zero.\n\t */\n\t__u32 flags;\n\n\t/**\n\t * @data:\n\t *\n\t * When &drm_i915_query_item.flags == %DRM_I915_QUERY_PERF_CONFIG_LIST,\n\t * i915 will write an array of __u64 of configuration identifiers.\n\t *\n\t * When &drm_i915_query_item.flags == %DRM_I915_QUERY_PERF_CONFIG_DATA,\n\t * i915 will write a struct drm_i915_perf_oa_config. If the following\n\t * fields of struct drm_i915_perf_oa_config are not set to 0, i915 will\n\t * write into the associated pointers the values of submitted when the\n\t * configuration was created :\n\t *\n\t *  - &drm_i915_perf_oa_config.n_mux_regs\n\t *  - &drm_i915_perf_oa_config.n_boolean_regs\n\t *  - &drm_i915_perf_oa_config.n_flex_regs\n\t */\n\t__u8 data[];\n};\n\n/**\n * enum drm_i915_gem_memory_class - Supported memory classes\n */\nenum drm_i915_gem_memory_class {\n\t/** @I915_MEMORY_CLASS_SYSTEM: System memory */\n\tI915_MEMORY_CLASS_SYSTEM = 0,\n\t/** @I915_MEMORY_CLASS_DEVICE: Device local-memory */\n\tI915_MEMORY_CLASS_DEVICE,\n};\n\n/**\n * struct drm_i915_gem_memory_class_instance - Identify particular memory region\n */\nstruct drm_i915_gem_memory_class_instance {\n\t/** @memory_class: See enum drm_i915_gem_memory_class */\n\t__u16 memory_class;\n\n\t/** @memory_instance: Which instance */\n\t__u16 memory_instance;\n};\n\n/**\n * struct drm_i915_memory_region_info - Describes one region as known to the\n * driver.\n *\n * Note this is using both struct drm_i915_query_item and struct drm_i915_query.\n * For this new query we are adding the new query id DRM_I915_QUERY_MEMORY_REGIONS\n * at &drm_i915_query_item.query_id.\n */\nstruct drm_i915_memory_region_info {\n\t/** @region: The class:instance pair encoding */\n\tstruct drm_i915_gem_memory_class_instance region;\n\n\t/** @rsvd0: MBZ */\n\t__u32 rsvd0;\n\n\t/**\n\t * @probed_size: Memory probed by the driver\n\t *\n\t * Note that it should not be possible to ever encounter a zero value\n\t * here, also note that no current region type will ever return -1 here.\n\t * Although for future region types, this might be a possibility. The\n\t * same applies to the other size fields.\n\t */\n\t__u64 probed_size;\n\n\t/**\n\t * @unallocated_size: Estimate of memory remaining\n\t *\n\t * Requires CAP_PERFMON or CAP_SYS_ADMIN to get reliable accounting.\n\t * Without this (or if this is an older kernel) the value here will\n\t * always equal the @probed_size. Note this is only currently tracked\n\t * for I915_MEMORY_CLASS_DEVICE regions (for other types the value here\n\t * will always equal the @probed_size).\n\t */\n\t__u64 unallocated_size;\n\n\tunion {\n\t\t/** @rsvd1: MBZ */\n\t\t__u64 rsvd1[8];\n\t\tstruct {\n\t\t\t/**\n\t\t\t * @probed_cpu_visible_size: Memory probed by the driver\n\t\t\t * that is CPU accessible.\n\t\t\t *\n\t\t\t * This will be always be <= @probed_size, and the\n\t\t\t * remainder (if there is any) will not be CPU\n\t\t\t * accessible.\n\t\t\t *\n\t\t\t * On systems without small BAR, the @probed_size will\n\t\t\t * always equal the @probed_cpu_visible_size, since all\n\t\t\t * of it will be CPU accessible.\n\t\t\t *\n\t\t\t * Note this is only tracked for\n\t\t\t * I915_MEMORY_CLASS_DEVICE regions (for other types the\n\t\t\t * value here will always equal the @probed_size).\n\t\t\t *\n\t\t\t * Note that if the value returned here is zero, then\n\t\t\t * this must be an old kernel which lacks the relevant\n\t\t\t * small-bar uAPI support (including\n\t\t\t * I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS), but on\n\t\t\t * such systems we should never actually end up with a\n\t\t\t * small BAR configuration, assuming we are able to load\n\t\t\t * the kernel module. Hence it should be safe to treat\n\t\t\t * this the same as when @probed_cpu_visible_size ==\n\t\t\t * @probed_size.\n\t\t\t */\n\t\t\t__u64 probed_cpu_visible_size;\n\n\t\t\t/**\n\t\t\t * @unallocated_cpu_visible_size: Estimate of CPU\n\t\t\t * visible memory remaining.\n\t\t\t *\n\t\t\t * Note this is only tracked for\n\t\t\t * I915_MEMORY_CLASS_DEVICE regions (for other types the\n\t\t\t * value here will always equal the\n\t\t\t * @probed_cpu_visible_size).\n\t\t\t *\n\t\t\t * Requires CAP_PERFMON or CAP_SYS_ADMIN to get reliable\n\t\t\t * accounting.  Without this the value here will always\n\t\t\t * equal the @probed_cpu_visible_size. Note this is only\n\t\t\t * currently tracked for I915_MEMORY_CLASS_DEVICE\n\t\t\t * regions (for other types the value here will also\n\t\t\t * always equal the @probed_cpu_visible_size).\n\t\t\t *\n\t\t\t * If this is an older kernel the value here will be\n\t\t\t * zero, see also @probed_cpu_visible_size.\n\t\t\t */\n\t\t\t__u64 unallocated_cpu_visible_size;\n\t\t};\n\t};\n};\n\n/**\n * struct drm_i915_query_memory_regions\n *\n * The region info query enumerates all regions known to the driver by filling\n * in an array of struct drm_i915_memory_region_info structures.\n *\n * Example for getting the list of supported regions:\n *\n * .. code-block:: C\n *\n *\tstruct drm_i915_query_memory_regions *info;\n *\tstruct drm_i915_query_item item = {\n *\t\t.query_id = DRM_I915_QUERY_MEMORY_REGIONS;\n *\t};\n *\tstruct drm_i915_query query = {\n *\t\t.num_items = 1,\n *\t\t.items_ptr = (uintptr_t)&item,\n *\t};\n *\tint err, i;\n *\n *\t// First query the size of the blob we need, this needs to be large\n *\t// enough to hold our array of regions. The kernel will fill out the\n *\t// item.length for us, which is the number of bytes we need.\n *\terr = ioctl(fd, DRM_IOCTL_I915_QUERY, &query);\n *\tif (err) ...\n *\n *\tinfo = calloc(1, item.length);\n *\t// Now that we allocated the required number of bytes, we call the ioctl\n *\t// again, this time with the data_ptr pointing to our newly allocated\n *\t// blob, which the kernel can then populate with the all the region info.\n *\titem.data_ptr = (uintptr_t)&info,\n *\n *\terr = ioctl(fd, DRM_IOCTL_I915_QUERY, &query);\n *\tif (err) ...\n *\n *\t// We can now access each region in the array\n *\tfor (i = 0; i < info->num_regions; i++) {\n *\t\tstruct drm_i915_memory_region_info mr = info->regions[i];\n *\t\tu16 class = mr.region.class;\n *\t\tu16 instance = mr.region.instance;\n *\n *\t\t....\n *\t}\n *\n *\tfree(info);\n */\nstruct drm_i915_query_memory_regions {\n\t/** @num_regions: Number of supported regions */\n\t__u32 num_regions;\n\n\t/** @rsvd: MBZ */\n\t__u32 rsvd[3];\n\n\t/** @regions: Info about each supported region */\n\tstruct drm_i915_memory_region_info regions[];\n};\n\n/**\n * struct drm_i915_query_guc_submission_version - query GuC submission interface version\n */\nstruct drm_i915_query_guc_submission_version {\n\t__u32 branch;\n\t__u32 major;\n\t__u32 minor;\n\t__u32 patch;\n};\n\n/**\n * DOC: GuC HWCONFIG blob uAPI\n *\n * The GuC produces a blob with information about the current device.\n * i915 reads this blob from GuC and makes it available via this uAPI.\n *\n * The format and meaning of the blob content are documented in the\n * Programmer's Reference Manual.\n */\n\n/**\n * struct drm_i915_gem_create_ext - Existing gem_create behaviour, with added\n * extension support using struct i915_user_extension.\n *\n * Note that new buffer flags should be added here, at least for the stuff that\n * is immutable. Previously we would have two ioctls, one to create the object\n * with gem_create, and another to apply various parameters, however this\n * creates some ambiguity for the params which are considered immutable. Also in\n * general we're phasing out the various SET/GET ioctls.\n */\nstruct drm_i915_gem_create_ext {\n\t/**\n\t * @size: Requested size for the object.\n\t *\n\t * The (page-aligned) allocated size for the object will be returned.\n\t *\n\t * On platforms like DG2/ATS the kernel will always use 64K or larger\n\t * pages for I915_MEMORY_CLASS_DEVICE. The kernel also requires a\n\t * minimum of 64K GTT alignment for such objects.\n\t *\n\t * NOTE: Previously the ABI here required a minimum GTT alignment of 2M\n\t * on DG2/ATS, due to how the hardware implemented 64K GTT page support,\n\t * where we had the following complications:\n\t *\n\t *   1) The entire PDE (which covers a 2MB virtual address range), must\n\t *   contain only 64K PTEs, i.e mixing 4K and 64K PTEs in the same\n\t *   PDE is forbidden by the hardware.\n\t *\n\t *   2) We still need to support 4K PTEs for I915_MEMORY_CLASS_SYSTEM\n\t *   objects.\n\t *\n\t * However on actual production HW this was completely changed to now\n\t * allow setting a TLB hint at the PTE level (see PS64), which is a lot\n\t * more flexible than the above. With this the 2M restriction was\n\t * dropped where we now only require 64K.\n\t */\n\t__u64 size;\n\n\t/**\n\t * @handle: Returned handle for the object.\n\t *\n\t * Object handles are nonzero.\n\t */\n\t__u32 handle;\n\n\t/**\n\t * @flags: Optional flags.\n\t *\n\t * Supported values:\n\t *\n\t * I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS - Signal to the kernel that\n\t * the object will need to be accessed via the CPU.\n\t *\n\t * Only valid when placing objects in I915_MEMORY_CLASS_DEVICE, and only\n\t * strictly required on configurations where some subset of the device\n\t * memory is directly visible/mappable through the CPU (which we also\n\t * call small BAR), like on some DG2+ systems. Note that this is quite\n\t * undesirable, but due to various factors like the client CPU, BIOS etc\n\t * it's something we can expect to see in the wild. See\n\t * &drm_i915_memory_region_info.probed_cpu_visible_size for how to\n\t * determine if this system applies.\n\t *\n\t * Note that one of the placements MUST be I915_MEMORY_CLASS_SYSTEM, to\n\t * ensure the kernel can always spill the allocation to system memory,\n\t * if the object can't be allocated in the mappable part of\n\t * I915_MEMORY_CLASS_DEVICE.\n\t *\n\t * Also note that since the kernel only supports flat-CCS on objects\n\t * that can *only* be placed in I915_MEMORY_CLASS_DEVICE, we therefore\n\t * don't support I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS together with\n\t * flat-CCS.\n\t *\n\t * Without this hint, the kernel will assume that non-mappable\n\t * I915_MEMORY_CLASS_DEVICE is preferred for this object. Note that the\n\t * kernel can still migrate the object to the mappable part, as a last\n\t * resort, if userspace ever CPU faults this object, but this might be\n\t * expensive, and so ideally should be avoided.\n\t *\n\t * On older kernels which lack the relevant small-bar uAPI support (see\n\t * also &drm_i915_memory_region_info.probed_cpu_visible_size),\n\t * usage of the flag will result in an error, but it should NEVER be\n\t * possible to end up with a small BAR configuration, assuming we can\n\t * also successfully load the i915 kernel module. In such cases the\n\t * entire I915_MEMORY_CLASS_DEVICE region will be CPU accessible, and as\n\t * such there are zero restrictions on where the object can be placed.\n\t */\n#define I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS (1 << 0)\n\t__u32 flags;\n\n\t/**\n\t * @extensions: The chain of extensions to apply to this object.\n\t *\n\t * This will be useful in the future when we need to support several\n\t * different extensions, and we need to apply more than one when\n\t * creating the object. See struct i915_user_extension.\n\t *\n\t * If we don't supply any extensions then we get the same old gem_create\n\t * behaviour.\n\t *\n\t * For I915_GEM_CREATE_EXT_MEMORY_REGIONS usage see\n\t * struct drm_i915_gem_create_ext_memory_regions.\n\t *\n\t * For I915_GEM_CREATE_EXT_PROTECTED_CONTENT usage see\n\t * struct drm_i915_gem_create_ext_protected_content.\n\t *\n\t * For I915_GEM_CREATE_EXT_SET_PAT usage see\n\t * struct drm_i915_gem_create_ext_set_pat.\n\t */\n#define I915_GEM_CREATE_EXT_MEMORY_REGIONS 0\n#define I915_GEM_CREATE_EXT_PROTECTED_CONTENT 1\n#define I915_GEM_CREATE_EXT_SET_PAT 2\n\t__u64 extensions;\n};\n\n/**\n * struct drm_i915_gem_create_ext_memory_regions - The\n * I915_GEM_CREATE_EXT_MEMORY_REGIONS extension.\n *\n * Set the object with the desired set of placements/regions in priority\n * order. Each entry must be unique and supported by the device.\n *\n * This is provided as an array of struct drm_i915_gem_memory_class_instance, or\n * an equivalent layout of class:instance pair encodings. See struct\n * drm_i915_query_memory_regions and DRM_I915_QUERY_MEMORY_REGIONS for how to\n * query the supported regions for a device.\n *\n * As an example, on discrete devices, if we wish to set the placement as\n * device local-memory we can do something like:\n *\n * .. code-block:: C\n *\n *\tstruct drm_i915_gem_memory_class_instance region_lmem = {\n *              .memory_class = I915_MEMORY_CLASS_DEVICE,\n *              .memory_instance = 0,\n *      };\n *      struct drm_i915_gem_create_ext_memory_regions regions = {\n *              .base = { .name = I915_GEM_CREATE_EXT_MEMORY_REGIONS },\n *              .regions = (uintptr_t)&region_lmem,\n *              .num_regions = 1,\n *      };\n *      struct drm_i915_gem_create_ext create_ext = {\n *              .size = 16 * PAGE_SIZE,\n *              .extensions = (uintptr_t)&regions,\n *      };\n *\n *      int err = ioctl(fd, DRM_IOCTL_I915_GEM_CREATE_EXT, &create_ext);\n *      if (err) ...\n *\n * At which point we get the object handle in &drm_i915_gem_create_ext.handle,\n * along with the final object size in &drm_i915_gem_create_ext.size, which\n * should account for any rounding up, if required.\n *\n * Note that userspace has no means of knowing the current backing region\n * for objects where @num_regions is larger than one. The kernel will only\n * ensure that the priority order of the @regions array is honoured, either\n * when initially placing the object, or when moving memory around due to\n * memory pressure\n *\n * On Flat-CCS capable HW, compression is supported for the objects residing\n * in I915_MEMORY_CLASS_DEVICE. When such objects (compressed) have other\n * memory class in @regions and migrated (by i915, due to memory\n * constraints) to the non I915_MEMORY_CLASS_DEVICE region, then i915 needs to\n * decompress the content. But i915 doesn't have the required information to\n * decompress the userspace compressed objects.\n *\n * So i915 supports Flat-CCS, on the objects which can reside only on\n * I915_MEMORY_CLASS_DEVICE regions.\n */\nstruct drm_i915_gem_create_ext_memory_regions {\n\t/** @base: Extension link. See struct i915_user_extension. */\n\tstruct i915_user_extension base;\n\n\t/** @pad: MBZ */\n\t__u32 pad;\n\t/** @num_regions: Number of elements in the @regions array. */\n\t__u32 num_regions;\n\t/**\n\t * @regions: The regions/placements array.\n\t *\n\t * An array of struct drm_i915_gem_memory_class_instance.\n\t */\n\t__u64 regions;\n};\n\n/**\n * struct drm_i915_gem_create_ext_protected_content - The\n * I915_OBJECT_PARAM_PROTECTED_CONTENT extension.\n *\n * If this extension is provided, buffer contents are expected to be protected\n * by PXP encryption and require decryption for scan out and processing. This\n * is only possible on platforms that have PXP enabled, on all other scenarios\n * using this extension will cause the ioctl to fail and return -ENODEV. The\n * flags parameter is reserved for future expansion and must currently be set\n * to zero.\n *\n * The buffer contents are considered invalid after a PXP session teardown.\n *\n * The encryption is guaranteed to be processed correctly only if the object\n * is submitted with a context created using the\n * I915_CONTEXT_PARAM_PROTECTED_CONTENT flag. This will also enable extra checks\n * at submission time on the validity of the objects involved.\n *\n * Below is an example on how to create a protected object:\n *\n * .. code-block:: C\n *\n *      struct drm_i915_gem_create_ext_protected_content protected_ext = {\n *              .base = { .name = I915_GEM_CREATE_EXT_PROTECTED_CONTENT },\n *              .flags = 0,\n *      };\n *      struct drm_i915_gem_create_ext create_ext = {\n *              .size = PAGE_SIZE,\n *              .extensions = (uintptr_t)&protected_ext,\n *      };\n *\n *      int err = ioctl(fd, DRM_IOCTL_I915_GEM_CREATE_EXT, &create_ext);\n *      if (err) ...\n */\nstruct drm_i915_gem_create_ext_protected_content {\n\t/** @base: Extension link. See struct i915_user_extension. */\n\tstruct i915_user_extension base;\n\t/** @flags: reserved for future usage, currently MBZ */\n\t__u32 flags;\n};\n\n/**\n * struct drm_i915_gem_create_ext_set_pat - The\n * I915_GEM_CREATE_EXT_SET_PAT extension.\n *\n * If this extension is provided, the specified caching policy (PAT index) is\n * applied to the buffer object.\n *\n * Below is an example on how to create an object with specific caching policy:\n *\n * .. code-block:: C\n *\n *      struct drm_i915_gem_create_ext_set_pat set_pat_ext = {\n *              .base = { .name = I915_GEM_CREATE_EXT_SET_PAT },\n *              .pat_index = 0,\n *      };\n *      struct drm_i915_gem_create_ext create_ext = {\n *              .size = PAGE_SIZE,\n *              .extensions = (uintptr_t)&set_pat_ext,\n *      };\n *\n *      int err = ioctl(fd, DRM_IOCTL_I915_GEM_CREATE_EXT, &create_ext);\n *      if (err) ...\n */\nstruct drm_i915_gem_create_ext_set_pat {\n\t/** @base: Extension link. See struct i915_user_extension. */\n\tstruct i915_user_extension base;\n\t/**\n\t * @pat_index: PAT index to be set\n\t * PAT index is a bit field in Page Table Entry to control caching\n\t * behaviors for GPU accesses. The definition of PAT index is\n\t * platform dependent and can be found in hardware specifications,\n\t */\n\t__u32 pat_index;\n\t/** @rsvd: reserved for future use */\n\t__u32 rsvd;\n};\n\n/* ID of the protected content session managed by i915 when PXP is active */\n#define I915_PROTECTED_CONTENT_DEFAULT_SESSION 0xf\n\n#if defined(__cplusplus)\n}\n#endif\n\n#endif /* _I915_DRM_H_ */\n"
  },
  {
    "path": "src/linux/intel_gpu_top/i915_pciids.h",
    "content": "/*\n * Copyright 2013 Intel Corporation\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sub license, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice (including the\n * next paragraph) shall be included in all copies or substantial portions\n * of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n#ifndef _I915_PCIIDS_H\n#define _I915_PCIIDS_H\n\n/*\n * A pci_device_id struct {\n *\t__u32 vendor, device;\n *      __u32 subvendor, subdevice;\n *\t__u32 class, class_mask;\n *\tkernel_ulong_t driver_data;\n * };\n * Don't use C99 here because \"class\" is reserved and we want to\n * give userspace flexibility.\n */\n#define INTEL_VGA_DEVICE(id, info) { \\\n\t0x8086,\tid, \\\n\t~0, ~0, \\\n\t0x030000, 0xff0000, \\\n\t(unsigned long) info }\n\n#define INTEL_QUANTA_VGA_DEVICE(info) { \\\n\t0x8086,\t0x16a, \\\n\t0x152d,\t0x8990, \\\n\t0x030000, 0xff0000, \\\n\t(unsigned long) info }\n\n#define INTEL_I810_IDS(MACRO__, ...) \\\n\tMACRO__(0x7121, ## __VA_ARGS__), /* I810 */ \\\n\tMACRO__(0x7123, ## __VA_ARGS__), /* I810_DC100 */ \\\n\tMACRO__(0x7125, ## __VA_ARGS__)  /* I810_E */\n\n#define INTEL_I815_IDS(MACRO__, ...) \\\n\tMACRO__(0x1132, ## __VA_ARGS__)  /* I815*/\n\n#define INTEL_I830_IDS(MACRO__, ...) \\\n\tMACRO__(0x3577, ## __VA_ARGS__)\n\n#define INTEL_I845G_IDS(MACRO__, ...) \\\n\tMACRO__(0x2562, ## __VA_ARGS__)\n\n#define INTEL_I85X_IDS(MACRO__, ...) \\\n\tMACRO__(0x3582, ## __VA_ARGS__), /* I855_GM */ \\\n\tMACRO__(0x358e, ## __VA_ARGS__)\n\n#define INTEL_I865G_IDS(MACRO__, ...) \\\n\tMACRO__(0x2572, ## __VA_ARGS__) /* I865_G */\n\n#define INTEL_I915G_IDS(MACRO__, ...) \\\n\tMACRO__(0x2582, ## __VA_ARGS__), /* I915_G */ \\\n\tMACRO__(0x258a, ## __VA_ARGS__)  /* E7221_G */\n\n#define INTEL_I915GM_IDS(MACRO__, ...) \\\n\tMACRO__(0x2592, ## __VA_ARGS__) /* I915_GM */\n\n#define INTEL_I945G_IDS(MACRO__, ...) \\\n\tMACRO__(0x2772, ## __VA_ARGS__) /* I945_G */\n\n#define INTEL_I945GM_IDS(MACRO__, ...) \\\n\tMACRO__(0x27a2, ## __VA_ARGS__), /* I945_GM */ \\\n\tMACRO__(0x27ae, ## __VA_ARGS__)  /* I945_GME */\n\n#define INTEL_I965G_IDS(MACRO__, ...) \\\n\tMACRO__(0x2972, ## __VA_ARGS__), /* I946_GZ */ \\\n\tMACRO__(0x2982, ## __VA_ARGS__),\t/* G35_G */ \\\n\tMACRO__(0x2992, ## __VA_ARGS__),\t/* I965_Q */ \\\n\tMACRO__(0x29a2, ## __VA_ARGS__)\t/* I965_G */\n\n#define INTEL_G33_IDS(MACRO__, ...) \\\n\tMACRO__(0x29b2, ## __VA_ARGS__), /* Q35_G */ \\\n\tMACRO__(0x29c2, ## __VA_ARGS__),\t/* G33_G */ \\\n\tMACRO__(0x29d2, ## __VA_ARGS__)\t/* Q33_G */\n\n#define INTEL_I965GM_IDS(MACRO__, ...) \\\n\tMACRO__(0x2a02, ## __VA_ARGS__),\t/* I965_GM */ \\\n\tMACRO__(0x2a12, ## __VA_ARGS__)  /* I965_GME */\n\n#define INTEL_GM45_IDS(MACRO__, ...) \\\n\tMACRO__(0x2a42, ## __VA_ARGS__) /* GM45_G */\n\n#define INTEL_G45_IDS(MACRO__, ...) \\\n\tMACRO__(0x2e02, ## __VA_ARGS__), /* IGD_E_G */ \\\n\tMACRO__(0x2e12, ## __VA_ARGS__), /* Q45_G */ \\\n\tMACRO__(0x2e22, ## __VA_ARGS__), /* G45_G */ \\\n\tMACRO__(0x2e32, ## __VA_ARGS__), /* G41_G */ \\\n\tMACRO__(0x2e42, ## __VA_ARGS__), /* B43_G */ \\\n\tMACRO__(0x2e92, ## __VA_ARGS__)\t/* B43_G.1 */\n\n#define INTEL_PNV_G_IDS(MACRO__, ...) \\\n\tMACRO__(0xa001, ## __VA_ARGS__)\n\n#define INTEL_PNV_M_IDS(MACRO__, ...) \\\n\tMACRO__(0xa011, ## __VA_ARGS__)\n\n#define INTEL_PNV_IDS(MACRO__, ...) \\\n\tINTEL_PNV_G_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_PNV_M_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_ILK_D_IDS(MACRO__, ...) \\\n\tMACRO__(0x0042, ## __VA_ARGS__)\n\n#define INTEL_ILK_M_IDS(MACRO__, ...) \\\n\tMACRO__(0x0046, ## __VA_ARGS__)\n\n#define INTEL_ILK_IDS(MACRO__, ...) \\\n\tINTEL_ILK_D_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_ILK_M_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_SNB_D_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x0102, ## __VA_ARGS__), \\\n\tMACRO__(0x010A, ## __VA_ARGS__)\n\n#define INTEL_SNB_D_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x0112, ## __VA_ARGS__), \\\n\tMACRO__(0x0122, ## __VA_ARGS__)\n\n#define INTEL_SNB_D_IDS(MACRO__, ...) \\\n\tINTEL_SNB_D_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_SNB_D_GT2_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_SNB_M_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x0106, ## __VA_ARGS__)\n\n#define INTEL_SNB_M_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x0116, ## __VA_ARGS__), \\\n\tMACRO__(0x0126, ## __VA_ARGS__)\n\n#define INTEL_SNB_M_IDS(MACRO__, ...) \\\n\tINTEL_SNB_M_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_SNB_M_GT2_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_SNB_IDS(MACRO__, ...) \\\n\tINTEL_SNB_D_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_SNB_M_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_IVB_M_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x0156, ## __VA_ARGS__) /* GT1 mobile */\n\n#define INTEL_IVB_M_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x0166, ## __VA_ARGS__) /* GT2 mobile */\n\n#define INTEL_IVB_M_IDS(MACRO__, ...) \\\n\tINTEL_IVB_M_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_IVB_M_GT2_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_IVB_D_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x0152, ## __VA_ARGS__), /* GT1 desktop */ \\\n\tMACRO__(0x015a, ## __VA_ARGS__)  /* GT1 server */\n\n#define INTEL_IVB_D_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x0162, ## __VA_ARGS__), /* GT2 desktop */ \\\n\tMACRO__(0x016a, ## __VA_ARGS__)  /* GT2 server */\n\n#define INTEL_IVB_D_IDS(MACRO__, ...) \\\n\tINTEL_IVB_D_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_IVB_D_GT2_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_IVB_IDS(MACRO__, ...) \\\n\tINTEL_IVB_M_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_IVB_D_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_IVB_Q_IDS(MACRO__, ...) \\\n\tINTEL_QUANTA_VGA_DEVICE(__VA_ARGS__) /* Quanta transcode */\n\n#define INTEL_HSW_ULT_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x0A02, ## __VA_ARGS__), /* ULT GT1 desktop */ \\\n\tMACRO__(0x0A06, ## __VA_ARGS__), /* ULT GT1 mobile */ \\\n\tMACRO__(0x0A0A, ## __VA_ARGS__), /* ULT GT1 server */ \\\n\tMACRO__(0x0A0B, ## __VA_ARGS__)  /* ULT GT1 reserved */\n\n#define INTEL_HSW_ULX_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x0A0E, ## __VA_ARGS__) /* ULX GT1 mobile */\n\n#define INTEL_HSW_GT1_IDS(MACRO__, ...) \\\n\tINTEL_HSW_ULT_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_HSW_ULX_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x0402, ## __VA_ARGS__), /* GT1 desktop */ \\\n\tMACRO__(0x0406, ## __VA_ARGS__), /* GT1 mobile */ \\\n\tMACRO__(0x040A, ## __VA_ARGS__), /* GT1 server */ \\\n\tMACRO__(0x040B, ## __VA_ARGS__), /* GT1 reserved */ \\\n\tMACRO__(0x040E, ## __VA_ARGS__), /* GT1 reserved */ \\\n\tMACRO__(0x0C02, ## __VA_ARGS__), /* SDV GT1 desktop */ \\\n\tMACRO__(0x0C06, ## __VA_ARGS__), /* SDV GT1 mobile */ \\\n\tMACRO__(0x0C0A, ## __VA_ARGS__), /* SDV GT1 server */ \\\n\tMACRO__(0x0C0B, ## __VA_ARGS__), /* SDV GT1 reserved */ \\\n\tMACRO__(0x0C0E, ## __VA_ARGS__), /* SDV GT1 reserved */ \\\n\tMACRO__(0x0D02, ## __VA_ARGS__), /* CRW GT1 desktop */ \\\n\tMACRO__(0x0D06, ## __VA_ARGS__), /* CRW GT1 mobile */ \\\n\tMACRO__(0x0D0A, ## __VA_ARGS__), /* CRW GT1 server */ \\\n\tMACRO__(0x0D0B, ## __VA_ARGS__), /* CRW GT1 reserved */ \\\n\tMACRO__(0x0D0E, ## __VA_ARGS__)  /* CRW GT1 reserved */\n\n#define INTEL_HSW_ULT_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x0A12, ## __VA_ARGS__), /* ULT GT2 desktop */ \\\n\tMACRO__(0x0A16, ## __VA_ARGS__), /* ULT GT2 mobile */ \\\n\tMACRO__(0x0A1A, ## __VA_ARGS__), /* ULT GT2 server */ \\\n\tMACRO__(0x0A1B, ## __VA_ARGS__)  /* ULT GT2 reserved */ \\\n\n#define INTEL_HSW_ULX_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x0A1E, ## __VA_ARGS__) /* ULX GT2 mobile */ \\\n\n#define INTEL_HSW_GT2_IDS(MACRO__, ...) \\\n\tINTEL_HSW_ULT_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_HSW_ULX_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x0412, ## __VA_ARGS__), /* GT2 desktop */ \\\n\tMACRO__(0x0416, ## __VA_ARGS__), /* GT2 mobile */ \\\n\tMACRO__(0x041A, ## __VA_ARGS__), /* GT2 server */ \\\n\tMACRO__(0x041B, ## __VA_ARGS__), /* GT2 reserved */ \\\n\tMACRO__(0x041E, ## __VA_ARGS__), /* GT2 reserved */ \\\n\tMACRO__(0x0C12, ## __VA_ARGS__), /* SDV GT2 desktop */ \\\n\tMACRO__(0x0C16, ## __VA_ARGS__), /* SDV GT2 mobile */ \\\n\tMACRO__(0x0C1A, ## __VA_ARGS__), /* SDV GT2 server */ \\\n\tMACRO__(0x0C1B, ## __VA_ARGS__), /* SDV GT2 reserved */ \\\n\tMACRO__(0x0C1E, ## __VA_ARGS__), /* SDV GT2 reserved */ \\\n\tMACRO__(0x0D12, ## __VA_ARGS__), /* CRW GT2 desktop */ \\\n\tMACRO__(0x0D16, ## __VA_ARGS__), /* CRW GT2 mobile */ \\\n\tMACRO__(0x0D1A, ## __VA_ARGS__), /* CRW GT2 server */ \\\n\tMACRO__(0x0D1B, ## __VA_ARGS__), /* CRW GT2 reserved */ \\\n\tMACRO__(0x0D1E, ## __VA_ARGS__)  /* CRW GT2 reserved */\n\n#define INTEL_HSW_ULT_GT3_IDS(MACRO__, ...) \\\n\tMACRO__(0x0A22, ## __VA_ARGS__), /* ULT GT3 desktop */ \\\n\tMACRO__(0x0A26, ## __VA_ARGS__), /* ULT GT3 mobile */ \\\n\tMACRO__(0x0A2A, ## __VA_ARGS__), /* ULT GT3 server */ \\\n\tMACRO__(0x0A2B, ## __VA_ARGS__), /* ULT GT3 reserved */ \\\n\tMACRO__(0x0A2E, ## __VA_ARGS__)  /* ULT GT3 reserved */\n\n#define INTEL_HSW_GT3_IDS(MACRO__, ...) \\\n\tINTEL_HSW_ULT_GT3_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x0422, ## __VA_ARGS__), /* GT3 desktop */ \\\n\tMACRO__(0x0426, ## __VA_ARGS__), /* GT3 mobile */ \\\n\tMACRO__(0x042A, ## __VA_ARGS__), /* GT3 server */ \\\n\tMACRO__(0x042B, ## __VA_ARGS__), /* GT3 reserved */ \\\n\tMACRO__(0x042E, ## __VA_ARGS__), /* GT3 reserved */ \\\n\tMACRO__(0x0C22, ## __VA_ARGS__), /* SDV GT3 desktop */ \\\n\tMACRO__(0x0C26, ## __VA_ARGS__), /* SDV GT3 mobile */ \\\n\tMACRO__(0x0C2A, ## __VA_ARGS__), /* SDV GT3 server */ \\\n\tMACRO__(0x0C2B, ## __VA_ARGS__), /* SDV GT3 reserved */ \\\n\tMACRO__(0x0C2E, ## __VA_ARGS__), /* SDV GT3 reserved */ \\\n\tMACRO__(0x0D22, ## __VA_ARGS__), /* CRW GT3 desktop */ \\\n\tMACRO__(0x0D26, ## __VA_ARGS__), /* CRW GT3 mobile */ \\\n\tMACRO__(0x0D2A, ## __VA_ARGS__), /* CRW GT3 server */ \\\n\tMACRO__(0x0D2B, ## __VA_ARGS__), /* CRW GT3 reserved */ \\\n\tMACRO__(0x0D2E, ## __VA_ARGS__)  /* CRW GT3 reserved */\n\n#define INTEL_HSW_IDS(MACRO__, ...) \\\n\tINTEL_HSW_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_HSW_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_HSW_GT3_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_VLV_IDS(MACRO__, ...) \\\n\tMACRO__(0x0f30, ## __VA_ARGS__), \\\n\tMACRO__(0x0f31, ## __VA_ARGS__), \\\n\tMACRO__(0x0f32, ## __VA_ARGS__), \\\n\tMACRO__(0x0f33, ## __VA_ARGS__)\n\n#define INTEL_BDW_ULT_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x1606, ## __VA_ARGS__), /* GT1 ULT */ \\\n\tMACRO__(0x160B, ## __VA_ARGS__)  /* GT1 Iris */\n\n#define INTEL_BDW_ULX_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x160E, ## __VA_ARGS__) /* GT1 ULX */\n\n#define INTEL_BDW_GT1_IDS(MACRO__, ...) \\\n\tINTEL_BDW_ULT_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_BDW_ULX_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x1602, ## __VA_ARGS__), /* GT1 ULT */ \\\n\tMACRO__(0x160A, ## __VA_ARGS__), /* GT1 Server */ \\\n\tMACRO__(0x160D, ## __VA_ARGS__)  /* GT1 Workstation */\n\n#define INTEL_BDW_ULT_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x1616, ## __VA_ARGS__), /* GT2 ULT */ \\\n\tMACRO__(0x161B, ## __VA_ARGS__)  /* GT2 ULT */\n\n#define INTEL_BDW_ULX_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x161E, ## __VA_ARGS__) /* GT2 ULX */\n\n#define INTEL_BDW_GT2_IDS(MACRO__, ...) \\\n\tINTEL_BDW_ULT_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_BDW_ULX_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x1612, ## __VA_ARGS__), /* GT2 Halo */ \\\n\tMACRO__(0x161A, ## __VA_ARGS__), /* GT2 Server */ \\\n\tMACRO__(0x161D, ## __VA_ARGS__)  /* GT2 Workstation */\n\n#define INTEL_BDW_ULT_GT3_IDS(MACRO__, ...) \\\n\tMACRO__(0x1626, ## __VA_ARGS__), /* ULT */ \\\n\tMACRO__(0x162B, ## __VA_ARGS__)  /* Iris */ \\\n\n#define INTEL_BDW_ULX_GT3_IDS(MACRO__, ...) \\\n\tMACRO__(0x162E, ## __VA_ARGS__)  /* ULX */\n\n#define INTEL_BDW_GT3_IDS(MACRO__, ...) \\\n\tINTEL_BDW_ULT_GT3_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_BDW_ULX_GT3_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x1622, ## __VA_ARGS__), /* ULT */ \\\n\tMACRO__(0x162A, ## __VA_ARGS__), /* Server */ \\\n\tMACRO__(0x162D, ## __VA_ARGS__)  /* Workstation */\n\n#define INTEL_BDW_ULT_RSVD_IDS(MACRO__, ...) \\\n\tMACRO__(0x1636, ## __VA_ARGS__), /* ULT */ \\\n\tMACRO__(0x163B, ## __VA_ARGS__)  /* Iris */\n\n#define INTEL_BDW_ULX_RSVD_IDS(MACRO__, ...) \\\n\tMACRO__(0x163E, ## __VA_ARGS__) /* ULX */\n\n#define INTEL_BDW_RSVD_IDS(MACRO__, ...) \\\n\tINTEL_BDW_ULT_RSVD_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_BDW_ULX_RSVD_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x1632, ## __VA_ARGS__), /* ULT */ \\\n\tMACRO__(0x163A, ## __VA_ARGS__), /* Server */ \\\n\tMACRO__(0x163D, ## __VA_ARGS__)  /* Workstation */\n\n#define INTEL_BDW_IDS(MACRO__, ...) \\\n\tINTEL_BDW_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_BDW_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_BDW_GT3_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_BDW_RSVD_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_CHV_IDS(MACRO__, ...) \\\n\tMACRO__(0x22b0, ## __VA_ARGS__), \\\n\tMACRO__(0x22b1, ## __VA_ARGS__), \\\n\tMACRO__(0x22b2, ## __VA_ARGS__), \\\n\tMACRO__(0x22b3, ## __VA_ARGS__)\n\n#define INTEL_SKL_ULT_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x1906, ## __VA_ARGS__), /* ULT GT1 */ \\\n\tMACRO__(0x1913, ## __VA_ARGS__)  /* ULT GT1.5 */\n\n#define INTEL_SKL_ULX_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x190E, ## __VA_ARGS__), /* ULX GT1 */ \\\n\tMACRO__(0x1915, ## __VA_ARGS__)  /* ULX GT1.5 */\n\n#define INTEL_SKL_GT1_IDS(MACRO__, ...) \\\n\tINTEL_SKL_ULT_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_SKL_ULX_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x1902, ## __VA_ARGS__), /* DT  GT1 */ \\\n\tMACRO__(0x190A, ## __VA_ARGS__), /* SRV GT1 */ \\\n\tMACRO__(0x190B, ## __VA_ARGS__), /* Halo GT1 */ \\\n\tMACRO__(0x1917, ## __VA_ARGS__)  /* DT  GT1.5 */\n\n#define INTEL_SKL_ULT_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x1916, ## __VA_ARGS__), /* ULT GT2 */ \\\n\tMACRO__(0x1921, ## __VA_ARGS__)  /* ULT GT2F */\n\n#define INTEL_SKL_ULX_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x191E, ## __VA_ARGS__) /* ULX GT2 */\n\n#define INTEL_SKL_GT2_IDS(MACRO__, ...) \\\n\tINTEL_SKL_ULT_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_SKL_ULX_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x1912, ## __VA_ARGS__), /* DT  GT2 */ \\\n\tMACRO__(0x191A, ## __VA_ARGS__), /* SRV GT2 */ \\\n\tMACRO__(0x191B, ## __VA_ARGS__), /* Halo GT2 */ \\\n\tMACRO__(0x191D, ## __VA_ARGS__)  /* WKS GT2 */\n\n#define INTEL_SKL_ULT_GT3_IDS(MACRO__, ...) \\\n\tMACRO__(0x1923, ## __VA_ARGS__), /* ULT GT3 */ \\\n\tMACRO__(0x1926, ## __VA_ARGS__), /* ULT GT3e */ \\\n\tMACRO__(0x1927, ## __VA_ARGS__)  /* ULT GT3e */\n\n#define INTEL_SKL_GT3_IDS(MACRO__, ...) \\\n\tINTEL_SKL_ULT_GT3_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x192A, ## __VA_ARGS__), /* SRV GT3 */ \\\n\tMACRO__(0x192B, ## __VA_ARGS__), /* Halo GT3e */ \\\n\tMACRO__(0x192D, ## __VA_ARGS__)  /* SRV GT3e */\n\n#define INTEL_SKL_GT4_IDS(MACRO__, ...) \\\n\tMACRO__(0x1932, ## __VA_ARGS__), /* DT GT4 */ \\\n\tMACRO__(0x193A, ## __VA_ARGS__), /* SRV GT4e */ \\\n\tMACRO__(0x193B, ## __VA_ARGS__), /* Halo GT4e */ \\\n\tMACRO__(0x193D, ## __VA_ARGS__) /* WKS GT4e */\n\n#define INTEL_SKL_IDS(MACRO__, ...) \\\n\tINTEL_SKL_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_SKL_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_SKL_GT3_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_SKL_GT4_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_BXT_IDS(MACRO__, ...) \\\n\tMACRO__(0x0A84, ## __VA_ARGS__), \\\n\tMACRO__(0x1A84, ## __VA_ARGS__), \\\n\tMACRO__(0x1A85, ## __VA_ARGS__), \\\n\tMACRO__(0x5A84, ## __VA_ARGS__), /* APL HD Graphics 505 */ \\\n\tMACRO__(0x5A85, ## __VA_ARGS__)  /* APL HD Graphics 500 */\n\n#define INTEL_GLK_IDS(MACRO__, ...) \\\n\tMACRO__(0x3184, ## __VA_ARGS__), \\\n\tMACRO__(0x3185, ## __VA_ARGS__)\n\n#define INTEL_KBL_ULT_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x5906, ## __VA_ARGS__), /* ULT GT1 */ \\\n\tMACRO__(0x5913, ## __VA_ARGS__)  /* ULT GT1.5 */\n\n#define INTEL_KBL_ULX_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x590E, ## __VA_ARGS__), /* ULX GT1 */ \\\n\tMACRO__(0x5915, ## __VA_ARGS__)  /* ULX GT1.5 */\n\n#define INTEL_KBL_GT1_IDS(MACRO__, ...) \\\n\tINTEL_KBL_ULT_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_KBL_ULX_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x5902, ## __VA_ARGS__), /* DT  GT1 */ \\\n\tMACRO__(0x5908, ## __VA_ARGS__), /* Halo GT1 */ \\\n\tMACRO__(0x590A, ## __VA_ARGS__), /* SRV GT1 */ \\\n\tMACRO__(0x590B, ## __VA_ARGS__) /* Halo GT1 */\n\n#define INTEL_KBL_ULT_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x5916, ## __VA_ARGS__), /* ULT GT2 */ \\\n\tMACRO__(0x5921, ## __VA_ARGS__)  /* ULT GT2F */\n\n#define INTEL_KBL_ULX_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x591E, ## __VA_ARGS__)  /* ULX GT2 */\n\n#define INTEL_KBL_GT2_IDS(MACRO__, ...) \\\n\tINTEL_KBL_ULT_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_KBL_ULX_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x5912, ## __VA_ARGS__), /* DT  GT2 */ \\\n\tMACRO__(0x5917, ## __VA_ARGS__), /* Mobile GT2 */ \\\n\tMACRO__(0x591A, ## __VA_ARGS__), /* SRV GT2 */ \\\n\tMACRO__(0x591B, ## __VA_ARGS__), /* Halo GT2 */ \\\n\tMACRO__(0x591D, ## __VA_ARGS__) /* WKS GT2 */\n\n#define INTEL_KBL_ULT_GT3_IDS(MACRO__, ...) \\\n\tMACRO__(0x5926, ## __VA_ARGS__) /* ULT GT3 */\n\n#define INTEL_KBL_GT3_IDS(MACRO__, ...) \\\n\tINTEL_KBL_ULT_GT3_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x5923, ## __VA_ARGS__), /* ULT GT3 */ \\\n\tMACRO__(0x5927, ## __VA_ARGS__) /* ULT GT3 */\n\n#define INTEL_KBL_GT4_IDS(MACRO__, ...) \\\n\tMACRO__(0x593B, ## __VA_ARGS__) /* Halo GT4 */\n\n/* AML/KBL Y GT2 */\n#define INTEL_AML_KBL_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x591C, ## __VA_ARGS__),  /* ULX GT2 */ \\\n\tMACRO__(0x87C0, ## __VA_ARGS__) /* ULX GT2 */\n\n/* AML/CFL Y GT2 */\n#define INTEL_AML_CFL_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x87CA, ## __VA_ARGS__)\n\n/* CML GT1 */\n#define INTEL_CML_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x9BA2, ## __VA_ARGS__), \\\n\tMACRO__(0x9BA4, ## __VA_ARGS__), \\\n\tMACRO__(0x9BA5, ## __VA_ARGS__), \\\n\tMACRO__(0x9BA8, ## __VA_ARGS__)\n\n#define INTEL_CML_U_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x9B21, ## __VA_ARGS__), \\\n\tMACRO__(0x9BAA, ## __VA_ARGS__), \\\n\tMACRO__(0x9BAC, ## __VA_ARGS__)\n\n/* CML GT2 */\n#define INTEL_CML_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x9BC2, ## __VA_ARGS__), \\\n\tMACRO__(0x9BC4, ## __VA_ARGS__), \\\n\tMACRO__(0x9BC5, ## __VA_ARGS__), \\\n\tMACRO__(0x9BC6, ## __VA_ARGS__), \\\n\tMACRO__(0x9BC8, ## __VA_ARGS__), \\\n\tMACRO__(0x9BE6, ## __VA_ARGS__), \\\n\tMACRO__(0x9BF6, ## __VA_ARGS__)\n\n#define INTEL_CML_U_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x9B41, ## __VA_ARGS__), \\\n\tMACRO__(0x9BCA, ## __VA_ARGS__), \\\n\tMACRO__(0x9BCC, ## __VA_ARGS__)\n\n#define INTEL_CML_IDS(MACRO__, ...) \\\n\tINTEL_CML_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_CML_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_CML_U_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_CML_U_GT2_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_KBL_IDS(MACRO__, ...) \\\n\tINTEL_KBL_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_KBL_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_KBL_GT3_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_KBL_GT4_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_AML_KBL_GT2_IDS(MACRO__, ## __VA_ARGS__)\n\n/* CFL S */\n#define INTEL_CFL_S_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x3E90, ## __VA_ARGS__), /* SRV GT1 */ \\\n\tMACRO__(0x3E93, ## __VA_ARGS__), /* SRV GT1 */ \\\n\tMACRO__(0x3E99, ## __VA_ARGS__)  /* SRV GT1 */\n\n#define INTEL_CFL_S_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x3E91, ## __VA_ARGS__), /* SRV GT2 */ \\\n\tMACRO__(0x3E92, ## __VA_ARGS__), /* SRV GT2 */ \\\n\tMACRO__(0x3E96, ## __VA_ARGS__), /* SRV GT2 */ \\\n\tMACRO__(0x3E98, ## __VA_ARGS__), /* SRV GT2 */ \\\n\tMACRO__(0x3E9A, ## __VA_ARGS__)  /* SRV GT2 */\n\n/* CFL H */\n#define INTEL_CFL_H_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x3E9C, ## __VA_ARGS__)\n\n#define INTEL_CFL_H_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x3E94, ## __VA_ARGS__),  /* Halo GT2 */ \\\n\tMACRO__(0x3E9B, ## __VA_ARGS__) /* Halo GT2 */\n\n/* CFL U GT2 */\n#define INTEL_CFL_U_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x3EA9, ## __VA_ARGS__)\n\n/* CFL U GT3 */\n#define INTEL_CFL_U_GT3_IDS(MACRO__, ...) \\\n\tMACRO__(0x3EA5, ## __VA_ARGS__), /* ULT GT3 */ \\\n\tMACRO__(0x3EA6, ## __VA_ARGS__), /* ULT GT3 */ \\\n\tMACRO__(0x3EA7, ## __VA_ARGS__), /* ULT GT3 */ \\\n\tMACRO__(0x3EA8, ## __VA_ARGS__)  /* ULT GT3 */\n\n#define INTEL_CFL_IDS(MACRO__, ...) \\\n\tINTEL_CFL_S_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_CFL_S_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_CFL_H_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_CFL_H_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_CFL_U_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_CFL_U_GT3_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_AML_CFL_GT2_IDS(MACRO__, ## __VA_ARGS__)\n\n/* WHL/CFL U GT1 */\n#define INTEL_WHL_U_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x3EA1, ## __VA_ARGS__), \\\n\tMACRO__(0x3EA4, ## __VA_ARGS__)\n\n/* WHL/CFL U GT2 */\n#define INTEL_WHL_U_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x3EA0, ## __VA_ARGS__), \\\n\tMACRO__(0x3EA3, ## __VA_ARGS__)\n\n/* WHL/CFL U GT3 */\n#define INTEL_WHL_U_GT3_IDS(MACRO__, ...) \\\n\tMACRO__(0x3EA2, ## __VA_ARGS__)\n\n#define INTEL_WHL_IDS(MACRO__, ...) \\\n\tINTEL_WHL_U_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_WHL_U_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_WHL_U_GT3_IDS(MACRO__, ## __VA_ARGS__)\n\n/* CNL */\n#define INTEL_CNL_PORT_F_IDS(MACRO__, ...) \\\n\tMACRO__(0x5A44, ## __VA_ARGS__), \\\n\tMACRO__(0x5A4C, ## __VA_ARGS__), \\\n\tMACRO__(0x5A54, ## __VA_ARGS__), \\\n\tMACRO__(0x5A5C, ## __VA_ARGS__)\n\n#define INTEL_CNL_IDS(MACRO__, ...) \\\n\tINTEL_CNL_PORT_F_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x5A40, ## __VA_ARGS__), \\\n\tMACRO__(0x5A41, ## __VA_ARGS__), \\\n\tMACRO__(0x5A42, ## __VA_ARGS__), \\\n\tMACRO__(0x5A49, ## __VA_ARGS__), \\\n\tMACRO__(0x5A4A, ## __VA_ARGS__), \\\n\tMACRO__(0x5A50, ## __VA_ARGS__), \\\n\tMACRO__(0x5A51, ## __VA_ARGS__), \\\n\tMACRO__(0x5A52, ## __VA_ARGS__), \\\n\tMACRO__(0x5A59, ## __VA_ARGS__), \\\n\tMACRO__(0x5A5A, ## __VA_ARGS__)\n\n/* ICL */\n#define INTEL_ICL_PORT_F_IDS(MACRO__, ...) \\\n\tMACRO__(0x8A50, ## __VA_ARGS__), \\\n\tMACRO__(0x8A52, ## __VA_ARGS__), \\\n\tMACRO__(0x8A53, ## __VA_ARGS__), \\\n\tMACRO__(0x8A54, ## __VA_ARGS__), \\\n\tMACRO__(0x8A56, ## __VA_ARGS__), \\\n\tMACRO__(0x8A57, ## __VA_ARGS__), \\\n\tMACRO__(0x8A58, ## __VA_ARGS__), \\\n\tMACRO__(0x8A59, ## __VA_ARGS__), \\\n\tMACRO__(0x8A5A, ## __VA_ARGS__), \\\n\tMACRO__(0x8A5B, ## __VA_ARGS__), \\\n\tMACRO__(0x8A5C, ## __VA_ARGS__), \\\n\tMACRO__(0x8A70, ## __VA_ARGS__), \\\n\tMACRO__(0x8A71, ## __VA_ARGS__)\n\n#define INTEL_ICL_IDS(MACRO__, ...) \\\n\tINTEL_ICL_PORT_F_IDS(MACRO__, ## __VA_ARGS__), \\\n\tMACRO__(0x8A51, ## __VA_ARGS__), \\\n\tMACRO__(0x8A5D, ## __VA_ARGS__)\n\n/* EHL */\n#define INTEL_EHL_IDS(MACRO__, ...) \\\n\tMACRO__(0x4541, ## __VA_ARGS__), \\\n\tMACRO__(0x4551, ## __VA_ARGS__), \\\n\tMACRO__(0x4555, ## __VA_ARGS__), \\\n\tMACRO__(0x4557, ## __VA_ARGS__), \\\n\tMACRO__(0x4570, ## __VA_ARGS__), \\\n\tMACRO__(0x4571, ## __VA_ARGS__)\n\n/* JSL */\n#define INTEL_JSL_IDS(MACRO__, ...) \\\n\tMACRO__(0x4E51, ## __VA_ARGS__), \\\n\tMACRO__(0x4E55, ## __VA_ARGS__), \\\n\tMACRO__(0x4E57, ## __VA_ARGS__), \\\n\tMACRO__(0x4E61, ## __VA_ARGS__), \\\n\tMACRO__(0x4E71, ## __VA_ARGS__)\n\n/* TGL */\n#define INTEL_TGL_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x9A60, ## __VA_ARGS__), \\\n\tMACRO__(0x9A68, ## __VA_ARGS__), \\\n\tMACRO__(0x9A70, ## __VA_ARGS__)\n\n#define INTEL_TGL_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x9A40, ## __VA_ARGS__), \\\n\tMACRO__(0x9A49, ## __VA_ARGS__), \\\n\tMACRO__(0x9A59, ## __VA_ARGS__), \\\n\tMACRO__(0x9A78, ## __VA_ARGS__), \\\n\tMACRO__(0x9AC0, ## __VA_ARGS__), \\\n\tMACRO__(0x9AC9, ## __VA_ARGS__), \\\n\tMACRO__(0x9AD9, ## __VA_ARGS__), \\\n\tMACRO__(0x9AF8, ## __VA_ARGS__)\n\n#define INTEL_TGL_IDS(MACRO__, ...) \\\n\tINTEL_TGL_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_TGL_GT2_IDS(MACRO__, ## __VA_ARGS__)\n\n/* RKL */\n#define INTEL_RKL_IDS(MACRO__, ...) \\\n\tMACRO__(0x4C80, ## __VA_ARGS__), \\\n\tMACRO__(0x4C8A, ## __VA_ARGS__), \\\n\tMACRO__(0x4C8B, ## __VA_ARGS__), \\\n\tMACRO__(0x4C8C, ## __VA_ARGS__), \\\n\tMACRO__(0x4C90, ## __VA_ARGS__), \\\n\tMACRO__(0x4C9A, ## __VA_ARGS__)\n\n/* DG1 */\n#define INTEL_DG1_IDS(MACRO__, ...) \\\n\tMACRO__(0x4905, ## __VA_ARGS__), \\\n\tMACRO__(0x4906, ## __VA_ARGS__), \\\n\tMACRO__(0x4907, ## __VA_ARGS__), \\\n\tMACRO__(0x4908, ## __VA_ARGS__), \\\n\tMACRO__(0x4909, ## __VA_ARGS__)\n\n/* ADL-S */\n#define INTEL_ADLS_IDS(MACRO__, ...) \\\n\tMACRO__(0x4680, ## __VA_ARGS__), \\\n\tMACRO__(0x4682, ## __VA_ARGS__), \\\n\tMACRO__(0x4688, ## __VA_ARGS__), \\\n\tMACRO__(0x468A, ## __VA_ARGS__), \\\n\tMACRO__(0x468B, ## __VA_ARGS__), \\\n\tMACRO__(0x4690, ## __VA_ARGS__), \\\n\tMACRO__(0x4692, ## __VA_ARGS__), \\\n\tMACRO__(0x4693, ## __VA_ARGS__)\n\n/* ADL-P */\n#define INTEL_ADLP_IDS(MACRO__, ...) \\\n\tMACRO__(0x46A0, ## __VA_ARGS__), \\\n\tMACRO__(0x46A1, ## __VA_ARGS__), \\\n\tMACRO__(0x46A2, ## __VA_ARGS__), \\\n\tMACRO__(0x46A3, ## __VA_ARGS__), \\\n\tMACRO__(0x46A6, ## __VA_ARGS__), \\\n\tMACRO__(0x46A8, ## __VA_ARGS__), \\\n\tMACRO__(0x46AA, ## __VA_ARGS__), \\\n\tMACRO__(0x462A, ## __VA_ARGS__), \\\n\tMACRO__(0x4626, ## __VA_ARGS__), \\\n\tMACRO__(0x4628, ## __VA_ARGS__), \\\n\tMACRO__(0x46B0, ## __VA_ARGS__), \\\n\tMACRO__(0x46B1, ## __VA_ARGS__), \\\n\tMACRO__(0x46B2, ## __VA_ARGS__), \\\n\tMACRO__(0x46B3, ## __VA_ARGS__), \\\n\tMACRO__(0x46C0, ## __VA_ARGS__), \\\n\tMACRO__(0x46C1, ## __VA_ARGS__), \\\n\tMACRO__(0x46C2, ## __VA_ARGS__), \\\n\tMACRO__(0x46C3, ## __VA_ARGS__)\n\n/* ADL-N */\n#define INTEL_ADLN_IDS(MACRO__, ...) \\\n\tMACRO__(0x46D0, ## __VA_ARGS__), \\\n\tMACRO__(0x46D1, ## __VA_ARGS__), \\\n\tMACRO__(0x46D2, ## __VA_ARGS__), \\\n\tMACRO__(0x46D3, ## __VA_ARGS__), \\\n\tMACRO__(0x46D4, ## __VA_ARGS__)\n\n/* RPL-S */\n#define INTEL_RPLS_IDS(MACRO__, ...) \\\n\tMACRO__(0xA780, ## __VA_ARGS__), \\\n\tMACRO__(0xA781, ## __VA_ARGS__), \\\n\tMACRO__(0xA782, ## __VA_ARGS__), \\\n\tMACRO__(0xA783, ## __VA_ARGS__), \\\n\tMACRO__(0xA788, ## __VA_ARGS__), \\\n\tMACRO__(0xA789, ## __VA_ARGS__), \\\n\tMACRO__(0xA78A, ## __VA_ARGS__), \\\n\tMACRO__(0xA78B, ## __VA_ARGS__)\n\n/* RPL-U */\n#define INTEL_RPLU_IDS(MACRO__, ...) \\\n\tMACRO__(0xA721, ## __VA_ARGS__), \\\n\tMACRO__(0xA7A1, ## __VA_ARGS__), \\\n\tMACRO__(0xA7A9, ## __VA_ARGS__), \\\n\tMACRO__(0xA7AC, ## __VA_ARGS__), \\\n\tMACRO__(0xA7AD, ## __VA_ARGS__)\n\n/* RPL-P */\n#define INTEL_RPLP_IDS(MACRO__, ...) \\\n\tMACRO__(0xA720, ## __VA_ARGS__), \\\n\tMACRO__(0xA7A0, ## __VA_ARGS__), \\\n\tMACRO__(0xA7A8, ## __VA_ARGS__), \\\n\tMACRO__(0xA7AA, ## __VA_ARGS__), \\\n\tMACRO__(0xA7AB, ## __VA_ARGS__)\n\n/* DG2 */\n#define INTEL_DG2_G10_IDS(MACRO__, ...) \\\n\tMACRO__(0x5690, ## __VA_ARGS__), \\\n\tMACRO__(0x5691, ## __VA_ARGS__), \\\n\tMACRO__(0x5692, ## __VA_ARGS__), \\\n\tMACRO__(0x56A0, ## __VA_ARGS__), \\\n\tMACRO__(0x56A1, ## __VA_ARGS__), \\\n\tMACRO__(0x56A2, ## __VA_ARGS__), \\\n\tMACRO__(0x56BE, ## __VA_ARGS__), \\\n\tMACRO__(0x56BF, ## __VA_ARGS__)\n\n#define INTEL_DG2_G11_IDS(MACRO__, ...) \\\n\tMACRO__(0x5693, ## __VA_ARGS__), \\\n\tMACRO__(0x5694, ## __VA_ARGS__), \\\n\tMACRO__(0x5695, ## __VA_ARGS__), \\\n\tMACRO__(0x56A5, ## __VA_ARGS__), \\\n\tMACRO__(0x56A6, ## __VA_ARGS__), \\\n\tMACRO__(0x56B0, ## __VA_ARGS__), \\\n\tMACRO__(0x56B1, ## __VA_ARGS__), \\\n\tMACRO__(0x56BA, ## __VA_ARGS__), \\\n\tMACRO__(0x56BB, ## __VA_ARGS__), \\\n\tMACRO__(0x56BC, ## __VA_ARGS__), \\\n\tMACRO__(0x56BD, ## __VA_ARGS__)\n\n#define INTEL_DG2_G12_IDS(MACRO__, ...) \\\n\tMACRO__(0x5696, ## __VA_ARGS__), \\\n\tMACRO__(0x5697, ## __VA_ARGS__), \\\n\tMACRO__(0x56A3, ## __VA_ARGS__), \\\n\tMACRO__(0x56A4, ## __VA_ARGS__), \\\n\tMACRO__(0x56B2, ## __VA_ARGS__), \\\n\tMACRO__(0x56B3, ## __VA_ARGS__)\n\n#define INTEL_DG2_IDS(MACRO__, ...) \\\n\tINTEL_DG2_G10_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_DG2_G11_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_DG2_G12_IDS(MACRO__, ## __VA_ARGS__)\n\n#define INTEL_ATS_M150_IDS(MACRO__, ...) \\\n\tMACRO__(0x56C0, ## __VA_ARGS__), \\\n\tMACRO__(0x56C2, ## __VA_ARGS__)\n\n#define INTEL_ATS_M75_IDS(MACRO__, ...) \\\n\tMACRO__(0x56C1, ## __VA_ARGS__)\n\n#define INTEL_ATS_M_IDS(MACRO__, ...) \\\n\tINTEL_ATS_M150_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_ATS_M75_IDS(MACRO__, ## __VA_ARGS__)\n\n/* MTL */\n#define INTEL_MTL_IDS(MACRO__, ...) \\\n\tMACRO__(0x7D40, ## __VA_ARGS__), \\\n\tMACRO__(0x7D41, ## __VA_ARGS__), \\\n\tMACRO__(0x7D45, ## __VA_ARGS__), \\\n\tMACRO__(0x7D51, ## __VA_ARGS__), \\\n\tMACRO__(0x7D55, ## __VA_ARGS__), \\\n\tMACRO__(0x7D60, ## __VA_ARGS__), \\\n\tMACRO__(0x7D67, ## __VA_ARGS__), \\\n\tMACRO__(0x7DD1, ## __VA_ARGS__), \\\n\tMACRO__(0x7DD5, ## __VA_ARGS__)\n\n#endif /* _I915_PCIIDS_H */\n"
  },
  {
    "path": "src/linux/intel_gpu_top/i915_pciids_local.h",
    "content": "/* SPDX-License-Identifier: MIT */\n/*\n * Copyright © 2022 Intel Corporation\n */\n#ifndef _I915_PCIIDS_LOCAL_H_\n#define _I915_PCIIDS_LOCAL_H_\n\n#include \"i915_pciids.h\"\n\n/* MTL perf */\n#ifndef INTEL_MTL_M_IDS\n#define INTEL_MTL_M_IDS(MACRO__, ...) \\\n\tMACRO__(0x7D60, ## __VA_ARGS__), \\\n\tMACRO__(0x7D67, ## __VA_ARGS__)\n#endif\n\n#ifndef INTEL_MTL_P_GT2_IDS\n#define INTEL_MTL_P_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x7D45, ## __VA_ARGS__)\n#endif\n\n#ifndef INTEL_MTL_P_GT3_IDS\n#define INTEL_MTL_P_GT3_IDS(MACRO__, ...) \\\n\tMACRO__(0x7D55, ## __VA_ARGS__), \\\n\tMACRO__(0x7DD5, ## __VA_ARGS__)\n#endif\n\n#ifndef INTEL_MTL_P_IDS\n#define INTEL_MTL_P_IDS(MACRO__, ...) \\\n\tINTEL_MTL_P_GT2_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_MTL_P_GT3_IDS(MACRO__, ## __VA_ARGS__)\n#endif\n\n#ifndef INTEL_ARL_GT1_IDS\n#define INTEL_ARL_GT1_IDS(MACRO__, ...) \\\n\tMACRO__(0x7D41, ## __VA_ARGS__), \\\n\tMACRO__(0x7D67, ## __VA_ARGS__)\n#endif\n\n#ifndef INTEL_ARL_GT2_IDS\n#define INTEL_ARL_GT2_IDS(MACRO__, ...) \\\n\tMACRO__(0x7D51, ## __VA_ARGS__), \\\n\tMACRO__(0x7DD1, ## __VA_ARGS__)\n#endif\n\n#ifndef INTEL_ARL_IDS\n#define INTEL_ARL_IDS(MACRO__, ...) \\\n\tINTEL_ARL_GT1_IDS(MACRO__, ## __VA_ARGS__), \\\n\tINTEL_ARL_GT2_IDS(MACRO__, ## __VA_ARGS__)\n#endif\n\n/* PVC */\n#ifndef INTEL_PVC_IDS\n#define INTEL_PVC_IDS(MACRO__, ...) \\\n\tMACRO__(0x0BD0, ## __VA_ARGS__), \\\n\tMACRO__(0x0BD1, ## __VA_ARGS__), \\\n\tMACRO__(0x0BD2, ## __VA_ARGS__), \\\n\tMACRO__(0x0BD5, ## __VA_ARGS__), \\\n\tMACRO__(0x0BD6, ## __VA_ARGS__), \\\n\tMACRO__(0x0BD7, ## __VA_ARGS__), \\\n\tMACRO__(0x0BD8, ## __VA_ARGS__), \\\n\tMACRO__(0x0BD9, ## __VA_ARGS__), \\\n\tMACRO__(0x0BDA, ## __VA_ARGS__), \\\n\tMACRO__(0x0BDB, ## __VA_ARGS__)\n#endif\n\n#endif /* _I915_PCIIDS_LOCAL_H */\n"
  },
  {
    "path": "src/linux/intel_gpu_top/igt_perf.c",
    "content": "#include <errno.h>\n#include <fcntl.h>\n#include <limits.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#ifdef __linux__\n#include <sys/sysinfo.h>\n#include <sys/sysmacros.h>\n#include <linux/limits.h>\n#endif\n#include <time.h>\n#include <unistd.h>\n#include <stdio.h>\n\n#include \"igt_perf.h\"\n\nstatic char *bus_address(int i915, char *path, int pathlen)\n{\n\tstruct stat st;\n\tint len = -1;\n\tint dir;\n\tchar *s;\n\n\tif (fstat(i915, &st) || !S_ISCHR(st.st_mode))\n\t\treturn NULL;\n\n\tsnprintf(path, pathlen, \"/sys/dev/char/%d:%d\",\n\t\t major(st.st_rdev), minor(st.st_rdev));\n\n\tdir = open(path, O_RDONLY);\n\tif (dir != -1) {\n\t\tlen = readlinkat(dir, \"device\", path, pathlen - 1);\n\t\tclose(dir);\n\t}\n\tif (len < 0)\n\t\treturn NULL;\n\n\tpath[len] = '\\0';\n\n\t/* strip off the relative path */\n\ts = strrchr(path, '/');\n\tif (s)\n\t\tmemmove(path, s + 1, len - (s - path) + 1);\n\n\treturn path;\n}\n\nconst char *i915_perf_device(int i915, char *buf, int buflen)\n{\n\tchar *s;\n\n#define prefix \"i915_\"\n#define plen strlen(prefix)\n\n\tif (!buf || buflen < plen)\n\t\treturn \"i915\";\n\n\tmemcpy(buf, prefix, plen);\n\n\tif (!bus_address(i915, buf + plen, buflen - plen) ||\n\t    strcmp(buf + plen, \"0000:00:02.0\") == 0) /* legacy name for igfx */\n\t\tbuf[plen - 1] = '\\0';\n\n\t/* Convert all colons in the address to '_', thanks perf! */\n\tfor (s = buf; *s; s++)\n\t\tif (*s == ':')\n\t\t\t*s = '_';\n\n\treturn buf;\n}\n\nconst char *xe_perf_device(int xe, char *buf, int buflen)\n{\n\tchar *s;\n\tchar pref[] = \"xe_\";\n\tint len = strlen(pref);\n\n\n\tif (!buf || buflen < len)\n\t\treturn \"xe\";\n\n\tmemcpy(buf, pref, len);\n\n\tif (!bus_address(xe, buf + len, buflen - len))\n\t\tbuf[len - 1] = '\\0';\n\n\t/* Convert all colons in the address to '_', thanks perf! */\n\tfor (s = buf; *s; s++)\n\t\tif (*s == ':')\n\t\t\t*s = '_';\n\n\treturn buf;\n}\n\nuint64_t xe_perf_type_id(int xe)\n{\n\tchar buf[80];\n\n\treturn igt_perf_type_id(xe_perf_device(xe, buf, sizeof(buf)));\n}\n\nuint64_t i915_perf_type_id(int i915)\n{\n\tchar buf[80];\n\n\treturn igt_perf_type_id(i915_perf_device(i915, buf, sizeof(buf)));\n}\n\nuint64_t igt_perf_type_id(const char *device)\n{\n\tchar buf[64];\n\tssize_t ret;\n\tint fd;\n\n\tsnprintf(buf, sizeof(buf),\n\t\t \"/sys/bus/event_source/devices/%s/type\", device);\n\n\tfd = open(buf, O_RDONLY);\n\tif (fd < 0)\n\t\treturn 0;\n\n\tret = read(fd, buf, sizeof(buf) - 1);\n\tclose(fd);\n\tif (ret < 1)\n\t\treturn 0;\n\n\tbuf[ret] = '\\0';\n\n\treturn strtoull(buf, NULL, 0);\n}\n\nint igt_perf_events_dir(int i915)\n{\n\tchar buf[80];\n\tchar path[PATH_MAX];\n\n\ti915_perf_device(i915, buf, sizeof(buf));\n\tsnprintf(path, sizeof(path), \"/sys/bus/event_source/devices/%s/events\", buf);\n\treturn open(path, O_RDONLY);\n}\n\nstatic int\n_perf_open(uint64_t type, uint64_t config, int group, uint64_t format)\n{\n\tstruct perf_event_attr attr = { };\n\tint nr_cpus = get_nprocs_conf();\n\tint cpu = 0, ret;\n\n\tattr.type = type;\n\tif (attr.type == 0)\n\t\treturn -ENOENT;\n\n\tif (group >= 0)\n\t\tformat &= ~PERF_FORMAT_GROUP;\n\n\tattr.read_format = format;\n\tattr.config = config;\n\tattr.use_clockid = 1;\n\tattr.clockid = CLOCK_MONOTONIC;\n\n\tdo {\n\t\tret = perf_event_open(&attr, -1, cpu++, group, 0);\n\t} while ((ret < 0 && errno == EINVAL) && (cpu < nr_cpus));\n\n\treturn ret;\n}\n\nint perf_igfx_open(uint64_t config)\n{\n\treturn _perf_open(igt_perf_type_id(\"i915\"), config, -1,\n\t\t\t  PERF_FORMAT_TOTAL_TIME_ENABLED);\n}\n\nint perf_igfx_open_group(uint64_t config, int group)\n{\n\treturn _perf_open(igt_perf_type_id(\"i915\"), config, group,\n\t\t\t  PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_GROUP);\n}\n\nint perf_xe_open(int xe, uint64_t config)\n{\n\treturn _perf_open(xe_perf_type_id(xe), config, -1,\n\t\t\tPERF_FORMAT_TOTAL_TIME_ENABLED);\n}\n\nint perf_i915_open(int i915, uint64_t config)\n{\n\treturn _perf_open(i915_perf_type_id(i915), config, -1,\n\t\t\t  PERF_FORMAT_TOTAL_TIME_ENABLED);\n}\n\nint perf_i915_open_group(int i915, uint64_t config, int group)\n{\n\treturn _perf_open(i915_perf_type_id(i915), config, group,\n\t\t\t  PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_GROUP);\n}\n\nint igt_perf_open(uint64_t type, uint64_t config)\n{\n\treturn _perf_open(type, config, -1,\n\t\t\t  PERF_FORMAT_TOTAL_TIME_ENABLED);\n}\n\nint igt_perf_open_group(uint64_t type, uint64_t config, int group)\n{\n\treturn _perf_open(type, config, group,\n\t\t\t  PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_GROUP);\n}\n"
  },
  {
    "path": "src/linux/intel_gpu_top/igt_perf.h",
    "content": "/*\n * Copyright © 2017 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\n */\n\n#ifndef I915_PERF_H\n#define I915_PERF_H\n\n#include <stdint.h>\n\n#ifdef __linux__\n#include <linux/perf_event.h>\n#endif\n\n//#include \"igt_gt.h\"\n\nstatic inline int\nperf_event_open(struct perf_event_attr *attr,\n\t\tpid_t pid,\n\t\tint cpu,\n\t\tint group_fd,\n\t\tunsigned long flags)\n{\n#ifndef __NR_perf_event_open\n#if defined(__i386__)\n#define __NR_perf_event_open 336\n#elif defined(__x86_64__)\n#define __NR_perf_event_open 298\n#else\n#define __NR_perf_event_open 0\n#endif\n#endif\n    attr->size = sizeof(*attr);\n    return syscall(__NR_perf_event_open, attr, pid, cpu, group_fd, flags);\n}\n\nuint64_t igt_perf_type_id(const char *device);\nint igt_perf_events_dir(int i915);\nint igt_perf_open(uint64_t type, uint64_t config);\nint igt_perf_open_group(uint64_t type, uint64_t config, int group);\n\nconst char *i915_perf_device(int i915, char *buf, int buflen);\nuint64_t i915_perf_type_id(int i915);\n\nconst char *xe_perf_device(int xe, char *buf, int buflen);\nuint64_t xe_perf_type_id(int);\n\nint perf_igfx_open(uint64_t config);\nint perf_igfx_open_group(uint64_t config, int group);\n\nint perf_i915_open(int i915, uint64_t config);\nint perf_i915_open_group(int i915, uint64_t config, int group);\n\nint perf_xe_open(int xe, uint64_t config);\n\n#endif /* I915_PERF_H */\n"
  },
  {
    "path": "src/linux/intel_gpu_top/intel_chipset.h",
    "content": "/*\n * Copyright © 2007 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\n * Authors:\n *    Eric Anholt <eric@anholt.net>\n *\n */\n\n#ifndef _INTEL_CHIPSET_H\n#define _INTEL_CHIPSET_H\n\n#include <stdbool.h>\n#include <stdint.h>\n\n#define BIT(x) (1ul <<(x))\n\nstruct intel_device_info {\n\tunsigned graphics_ver;\n\tunsigned graphics_rel;\n\tunsigned display_ver;\n\tunsigned gt; /* 0 if unknown */\n\tbool has_4tile : 1;\n\tbool has_flatccs : 1;\n\tbool has_oam : 1;\n\tbool is_mobile : 1;\n\tbool is_whitney : 1;\n\tbool is_almador : 1;\n\tbool is_brookdale : 1;\n\tbool is_montara : 1;\n\tbool is_springdale : 1;\n\tbool is_grantsdale : 1;\n\tbool is_alviso : 1;\n\tbool is_lakeport : 1;\n\tbool is_calistoga : 1;\n\tbool is_bearlake : 1;\n\tbool is_pineview : 1;\n\tbool is_broadwater : 1;\n\tbool is_crestline : 1;\n\tbool is_eaglelake : 1;\n\tbool is_cantiga : 1;\n\tbool is_ironlake : 1;\n\tbool is_arrandale : 1;\n\tbool is_sandybridge : 1;\n\tbool is_ivybridge : 1;\n\tbool is_valleyview : 1;\n\tbool is_haswell : 1;\n\tbool is_broadwell : 1;\n\tbool is_cherryview : 1;\n\tbool is_skylake : 1;\n\tbool is_broxton : 1;\n\tbool is_kabylake : 1;\n\tbool is_geminilake : 1;\n\tbool is_coffeelake : 1;\n\tbool is_cometlake : 1;\n\tbool is_cannonlake : 1;\n\tbool is_icelake : 1;\n\tbool is_elkhartlake : 1;\n\tbool is_jasperlake : 1;\n\tbool is_tigerlake : 1;\n\tbool is_rocketlake : 1;\n\tbool is_dg1 : 1;\n\tbool is_dg2 : 1;\n\tbool is_alderlake_s : 1;\n\tbool is_raptorlake_s : 1;\n\tbool is_alderlake_p : 1;\n\tbool is_alderlake_n : 1;\n\tbool is_meteorlake : 1;\n\tbool is_pontevecchio : 1;\n\tbool is_lunarlake : 1;\n\tbool is_battlemage : 1;\n\tconst char *codename;\n};\n\nconst struct intel_device_info *intel_get_device_info(uint16_t devid) __attribute__((pure));\n\nextern enum pch_type intel_pch;\n\nenum pch_type {\n\tPCH_NONE,\n\tPCH_IBX,\n\tPCH_CPT,\n\tPCH_LPT,\n};\n\nvoid intel_check_pch(void);\n\n#define HAS_IBX (intel_pch == PCH_IBX)\n#define HAS_CPT (intel_pch == PCH_CPT)\n#define HAS_LPT (intel_pch == PCH_LPT)\n\n#define IP_VER(ver, rel)\t\t((ver) << 8 | (rel))\n\n/* Exclude chipset #defines, they just add noise */\n#ifndef __GTK_DOC_IGNORE__\n\n#define PCI_CHIP_I810\t\t\t0x7121\n#define PCI_CHIP_I810_DC100\t\t0x7123\n#define PCI_CHIP_I810_E\t\t\t0x7125\n#define PCI_CHIP_I815\t\t\t0x1132\n\n#define PCI_CHIP_I830_M\t\t\t0x3577\n#define PCI_CHIP_845_G\t\t\t0x2562\n#define PCI_CHIP_I854_G\t\t\t0x358e\n#define PCI_CHIP_I855_GM\t\t0x3582\n#define PCI_CHIP_I865_G\t\t\t0x2572\n\n#define PCI_CHIP_I915_G\t\t\t0x2582\n#define PCI_CHIP_E7221_G\t\t0x258A\n#define PCI_CHIP_I915_GM\t\t0x2592\n#define PCI_CHIP_I945_G\t\t\t0x2772\n#define PCI_CHIP_I945_GM\t\t0x27A2\n#define PCI_CHIP_I945_GME\t\t0x27AE\n\n#define PCI_CHIP_I965_G\t\t\t0x29A2\n#define PCI_CHIP_I965_Q\t\t\t0x2992\n#define PCI_CHIP_I965_G_1\t\t0x2982\n#define PCI_CHIP_I946_GZ\t\t0x2972\n#define PCI_CHIP_I965_GM\t\t0x2A02\n#define PCI_CHIP_I965_GME\t\t0x2A12\n\n#define PCI_CHIP_GM45_GM\t\t0x2A42\n\n#define PCI_CHIP_Q45_G\t\t\t0x2E12\n#define PCI_CHIP_G45_G\t\t\t0x2E22\n#define PCI_CHIP_G41_G\t\t\t0x2E32\n\n#endif /* __GTK_DOC_IGNORE__ */\n\n#define IS_915G(devid)\t\t(intel_get_device_info(devid)->is_grantsdale)\n#define IS_915GM(devid)\t\t(intel_get_device_info(devid)->is_alviso)\n\n#define IS_915(devid)\t\t(IS_915G(devid) || IS_915GM(devid))\n\n#define IS_945G(devid)\t\t(intel_get_device_info(devid)->is_lakeport)\n#define IS_945GM(devid)\t\t(intel_get_device_info(devid)->is_calistoga)\n\n#define IS_945(devid)\t\t(IS_945G(devid) || \\\n\t\t\t\t IS_945GM(devid) || \\\n\t\t\t\t IS_G33(devid))\n\n#define IS_PINEVIEW(devid)\t(intel_get_device_info(devid)->is_pineview)\n#define IS_G33(devid)\t\t(intel_get_device_info(devid)->is_bearlake || \\\n\t\t\t\t intel_get_device_info(devid)->is_pineview)\n\n#define IS_BROADWATER(devid)\t(intel_get_device_info(devid)->is_broadwater)\n#define IS_CRESTLINE(devid)\t(intel_get_device_info(devid)->is_crestline)\n\n#define IS_GM45(devid)\t\t(intel_get_device_info(devid)->is_cantiga)\n#define IS_G45(devid)\t\t(intel_get_device_info(devid)->is_eaglelake)\n#define IS_G4X(devid)\t\t(IS_G45(devid) || IS_GM45(devid))\n\n#define IS_IRONLAKE(devid)\t(intel_get_device_info(devid)->is_ironlake)\n#define IS_ARRANDALE(devid)\t(intel_get_device_info(devid)->is_arrandale)\n#define IS_SANDYBRIDGE(devid)\t(intel_get_device_info(devid)->is_sandybridge)\n#define IS_IVYBRIDGE(devid)\t(intel_get_device_info(devid)->is_ivybridge)\n#define IS_VALLEYVIEW(devid)\t(intel_get_device_info(devid)->is_valleyview)\n#define IS_HASWELL(devid)\t(intel_get_device_info(devid)->is_haswell)\n#define IS_BROADWELL(devid)\t(intel_get_device_info(devid)->is_broadwell)\n#define IS_CHERRYVIEW(devid)\t(intel_get_device_info(devid)->is_cherryview)\n#define IS_SKYLAKE(devid)\t(intel_get_device_info(devid)->is_skylake)\n#define IS_BROXTON(devid)\t(intel_get_device_info(devid)->is_broxton)\n#define IS_KABYLAKE(devid)\t(intel_get_device_info(devid)->is_kabylake)\n#define IS_GEMINILAKE(devid)\t(intel_get_device_info(devid)->is_geminilake)\n#define IS_COFFEELAKE(devid)\t(intel_get_device_info(devid)->is_coffeelake)\n#define IS_COMETLAKE(devid)\t(intel_get_device_info(devid)->is_cometlake)\n#define IS_CANNONLAKE(devid)\t(intel_get_device_info(devid)->is_cannonlake)\n#define IS_ICELAKE(devid)\t(intel_get_device_info(devid)->is_icelake)\n#define IS_TIGERLAKE(devid)\t(intel_get_device_info(devid)->is_tigerlake)\n#define IS_ROCKETLAKE(devid)\t(intel_get_device_info(devid)->is_rocketlake)\n#define IS_DG1(devid)\t\t(intel_get_device_info(devid)->is_dg1)\n#define IS_DG2(devid)\t\t(intel_get_device_info(devid)->is_dg2)\n#define IS_ALDERLAKE_S(devid)\t(intel_get_device_info(devid)->is_alderlake_s)\n#define IS_RAPTORLAKE_S(devid)\t(intel_get_device_info(devid)->is_raptorlake_s)\n#define IS_ALDERLAKE_P(devid)\t(intel_get_device_info(devid)->is_alderlake_p)\n#define IS_ALDERLAKE_N(devid)\t(intel_get_device_info(devid)->is_alderlake_n)\n#define IS_METEORLAKE(devid)\t(intel_get_device_info(devid)->is_meteorlake)\n#define IS_PONTEVECCHIO(devid)\t(intel_get_device_info(devid)->is_pontevecchio)\n#define IS_LUNARLAKE(devid)\t(intel_get_device_info(devid)->is_lunarlake)\n#define IS_BATTLEMAGE(devid)\t(intel_get_device_info(devid)->is_battlemage)\n\n#define IS_GEN(devid, x)\t(intel_get_device_info(devid)->graphics_ver == x)\n#define AT_LEAST_GEN(devid, x)\t(intel_get_device_info(devid)->graphics_ver >= x)\n#define AT_LEAST_DISPLAY(devid, x) (intel_get_device_info(devid)->display_ver >= x)\n\n#define IS_GEN2(devid)\t\tIS_GEN(devid, 2)\n#define IS_GEN3(devid)\t\tIS_GEN(devid, 3)\n#define IS_GEN4(devid)\t\tIS_GEN(devid, 4)\n#define IS_GEN5(devid)\t\tIS_GEN(devid, 5)\n#define IS_GEN6(devid)\t\tIS_GEN(devid, 6)\n#define IS_GEN7(devid)\t\tIS_GEN(devid, 7)\n#define IS_GEN8(devid)\t\tIS_GEN(devid, 8)\n#define IS_GEN9(devid)\t\tIS_GEN(devid, 9)\n#define IS_GEN10(devid)\t\tIS_GEN(devid, 10)\n#define IS_GEN11(devid)\t\tIS_GEN(devid, 11)\n#define IS_GEN12(devid)\t\tIS_GEN(devid, 12)\n\n#define IS_MOBILE(devid)\t(intel_get_device_info(devid)->is_mobile)\n#define IS_965(devid)\t\tAT_LEAST_GEN(devid, 4)\n\n#define HAS_BSD_RING(devid)\tAT_LEAST_GEN(devid, 5)\n#define HAS_BLT_RING(devid)\tAT_LEAST_GEN(devid, 6)\n\n#define HAS_PCH_SPLIT(devid)\t(AT_LEAST_GEN(devid, 5) && \\\n\t\t\t\t !(IS_VALLEYVIEW(devid) || \\\n\t\t\t\t   IS_CHERRYVIEW(devid) || \\\n\t\t\t\t   IS_BROXTON(devid)))\n\n#define HAS_4TILE(devid)\t(intel_get_device_info(devid)->has_4tile)\n\n#define HAS_FLATCCS(devid)\t(intel_get_device_info(devid)->has_flatccs)\n\n#define HAS_OAM(devid)\t\t(intel_get_device_info(devid)->has_oam)\n\n#endif /* _INTEL_CHIPSET_H */\n"
  },
  {
    "path": "src/linux/intel_gpu_top/intel_device_info.c",
    "content": "#include \"intel_chipset.h\"\n#include \"i915_pciids.h\"\n#include \"i915_pciids_local.h\"\n#include \"xe_pciids.h\"\n\n#include <strings.h> /* ffs() */\n\n// from pciaccess.h\n#define PCI_MATCH_ANY  (~0U)\n\n// from pciaccess.h\nstruct pci_id_match {\n    /**\n     * \\name Device / vendor matching controls\n     *\n     * Control the search based on the device, vendor, subdevice, or subvendor\n     * IDs.  Setting any of these fields to \\c PCI_MATCH_ANY will cause the\n     * field to not be used in the comparison.\n     */\n    /*@{*/\n    uint32_t    vendor_id;\n    uint32_t    device_id;\n    uint32_t    subvendor_id;\n    uint32_t    subdevice_id;\n    /*@}*/\n\n\n    /**\n     * \\name Device class matching controls\n     *\n     */\n    /*@{*/\n    uint32_t    device_class;\n    uint32_t    device_class_mask;\n    /*@}*/\n\n    intptr_t    match_data;\n};\n\nstatic const struct intel_device_info intel_generic_info = {\n\t.graphics_ver = 0,\n\t.display_ver = 0,\n};\n\nstatic const struct intel_device_info intel_i810_info = {\n\t.graphics_ver = 1,\n\t.display_ver = 1,\n\t.is_whitney = true,\n\t.codename = \"solano\" /* 815 == \"whitney\" ? or vice versa? */\n};\n\nstatic const struct intel_device_info intel_i815_info = {\n\t.graphics_ver = 1,\n\t.display_ver = 1,\n\t.is_whitney = true,\n\t.codename = \"whitney\"\n};\n\nstatic const struct intel_device_info intel_i830_info = {\n\t.graphics_ver = 2,\n\t.display_ver = 2,\n\t.is_almador = true,\n\t.codename = \"almador\"\n};\nstatic const struct intel_device_info intel_i845_info = {\n\t.graphics_ver = 2,\n\t.display_ver = 2,\n\t.is_brookdale = true,\n\t.codename = \"brookdale\"\n};\nstatic const struct intel_device_info intel_i855_info = {\n\t.graphics_ver = 2,\n\t.display_ver = 2,\n\t.is_mobile = true,\n\t.is_montara = true,\n\t.codename = \"montara\"\n};\nstatic const struct intel_device_info intel_i865_info = {\n\t.graphics_ver = 2,\n\t.display_ver = 2,\n\t.is_springdale = true,\n\t.codename = \"spingdale\"\n};\n\nstatic const struct intel_device_info intel_i915_info = {\n\t.graphics_ver = 3,\n\t.display_ver = 3,\n\t.is_grantsdale = true,\n\t.codename = \"grantsdale\"\n};\nstatic const struct intel_device_info intel_i915m_info = {\n\t.graphics_ver = 3,\n\t.display_ver = 3,\n\t.is_mobile = true,\n\t.is_alviso = true,\n\t.codename = \"alviso\"\n};\nstatic const struct intel_device_info intel_i945_info = {\n\t.graphics_ver = 3,\n\t.display_ver = 3,\n\t.is_lakeport = true,\n\t.codename = \"lakeport\"\n};\nstatic const struct intel_device_info intel_i945m_info = {\n\t.graphics_ver = 3,\n\t.display_ver = 3,\n\t.is_mobile = true,\n\t.is_calistoga = true,\n\t.codename = \"calistoga\"\n};\n\nstatic const struct intel_device_info intel_g33_info = {\n\t.graphics_ver = 3,\n\t.display_ver = 3,\n\t.is_bearlake = true,\n\t.codename = \"bearlake\"\n};\n\nstatic const struct intel_device_info intel_pineview_g_info = {\n\t.graphics_ver = 3,\n\t.display_ver = 3,\n\t.is_pineview = true,\n\t.codename = \"pineview\"\n};\n\nstatic const struct intel_device_info intel_pineview_m_info = {\n\t.graphics_ver = 3,\n\t.display_ver = 3,\n\t.is_mobile = true,\n\t.is_pineview = true,\n\t.codename = \"pineview\"\n};\n\nstatic const struct intel_device_info intel_i965_info = {\n\t.graphics_ver = 4,\n\t.display_ver = 4,\n\t.is_broadwater = true,\n\t.codename = \"broadwater\"\n};\n\nstatic const struct intel_device_info intel_i965m_info = {\n\t.graphics_ver = 4,\n\t.display_ver = 4,\n\t.is_mobile = true,\n\t.is_crestline = true,\n\t.codename = \"crestline\"\n};\n\nstatic const struct intel_device_info intel_g45_info = {\n\t.graphics_ver = 4,\n\t.display_ver = 4,\n\t.is_eaglelake = true,\n\t.codename = \"eaglelake\"\n};\nstatic const struct intel_device_info intel_gm45_info = {\n\t.graphics_ver = 4,\n\t.display_ver = 4,\n\t.is_mobile = true,\n\t.is_cantiga = true,\n\t.codename = \"cantiga\"\n};\n\nstatic const struct intel_device_info intel_ironlake_info = {\n\t.graphics_ver = 5,\n\t.display_ver = 5,\n\t.is_ironlake = true,\n\t.codename = \"ironlake\" /* clarkdale? */\n};\nstatic const struct intel_device_info intel_ironlake_m_info = {\n\t.graphics_ver = 5,\n\t.display_ver = 5,\n\t.is_mobile = true,\n\t.is_arrandale = true,\n\t.codename = \"arrandale\"\n};\n\nstatic const struct intel_device_info intel_sandybridge_info = {\n\t.graphics_ver = 6,\n\t.display_ver = 6,\n\t.is_sandybridge = true,\n\t.codename = \"sandybridge\"\n};\nstatic const struct intel_device_info intel_sandybridge_m_info = {\n\t.graphics_ver = 6,\n\t.display_ver = 6,\n\t.is_mobile = true,\n\t.is_sandybridge = true,\n\t.codename = \"sandybridge\"\n};\n\nstatic const struct intel_device_info intel_ivybridge_info = {\n\t.graphics_ver = 7,\n\t.display_ver = 7,\n\t.is_ivybridge = true,\n\t.codename = \"ivybridge\"\n};\nstatic const struct intel_device_info intel_ivybridge_m_info = {\n\t.graphics_ver = 7,\n\t.display_ver = 7,\n\t.is_mobile = true,\n\t.is_ivybridge = true,\n\t.codename = \"ivybridge\"\n};\n\nstatic const struct intel_device_info intel_valleyview_info = {\n\t.graphics_ver = 7,\n\t.display_ver = 7,\n\t.is_valleyview = true,\n\t.codename = \"valleyview\"\n};\n\n#define HASWELL_FIELDS \\\n\t.graphics_ver = 7, \\\n\t.display_ver = 7, \\\n\t.is_haswell = true, \\\n\t.codename = \"haswell\"\n\nstatic const struct intel_device_info intel_haswell_gt1_info = {\n\tHASWELL_FIELDS,\n\t.gt = 1,\n};\n\nstatic const struct intel_device_info intel_haswell_gt2_info = {\n\tHASWELL_FIELDS,\n\t.gt = 2,\n};\n\nstatic const struct intel_device_info intel_haswell_gt3_info = {\n\tHASWELL_FIELDS,\n\t.gt = 3,\n};\n\n#define BROADWELL_FIELDS \\\n\t.graphics_ver = 8, \\\n\t.display_ver = 8, \\\n\t.is_broadwell = true, \\\n\t.codename = \"broadwell\"\n\nstatic const struct intel_device_info intel_broadwell_gt1_info = {\n\tBROADWELL_FIELDS,\n\t.gt = 1,\n};\n\nstatic const struct intel_device_info intel_broadwell_gt2_info = {\n\tBROADWELL_FIELDS,\n\t.gt = 2,\n};\n\nstatic const struct intel_device_info intel_broadwell_gt3_info = {\n\tBROADWELL_FIELDS,\n\t.gt = 3,\n};\n\nstatic const struct intel_device_info intel_broadwell_unknown_info = {\n\tBROADWELL_FIELDS,\n};\n\nstatic const struct intel_device_info intel_cherryview_info = {\n\t.graphics_ver = 8,\n\t.display_ver = 8,\n\t.is_cherryview = true,\n\t.codename = \"cherryview\"\n};\n\n#define SKYLAKE_FIELDS \\\n\t.graphics_ver = 9, \\\n\t.display_ver = 9, \\\n\t.codename = \"skylake\", \\\n\t.is_skylake = true\n\nstatic const struct intel_device_info intel_skylake_gt1_info = {\n\tSKYLAKE_FIELDS,\n\t.gt = 1,\n};\n\nstatic const struct intel_device_info intel_skylake_gt2_info = {\n\tSKYLAKE_FIELDS,\n\t.gt = 2,\n};\n\nstatic const struct intel_device_info intel_skylake_gt3_info = {\n\tSKYLAKE_FIELDS,\n\t.gt = 3,\n};\n\nstatic const struct intel_device_info intel_skylake_gt4_info = {\n\tSKYLAKE_FIELDS,\n\t.gt = 4,\n};\n\nstatic const struct intel_device_info intel_broxton_info = {\n\t.graphics_ver = 9,\n\t.display_ver = 9,\n\t.is_broxton = true,\n\t.codename = \"broxton\"\n};\n\n#define KABYLAKE_FIELDS \\\n\t.graphics_ver = 9, \\\n\t.display_ver = 9, \\\n\t.is_kabylake = true, \\\n\t.codename = \"kabylake\"\n\nstatic const struct intel_device_info intel_kabylake_gt1_info = {\n\tKABYLAKE_FIELDS,\n\t.gt = 1,\n};\n\nstatic const struct intel_device_info intel_kabylake_gt2_info = {\n\tKABYLAKE_FIELDS,\n\t.gt = 2,\n};\n\nstatic const struct intel_device_info intel_kabylake_gt3_info = {\n\tKABYLAKE_FIELDS,\n\t.gt = 3,\n};\n\nstatic const struct intel_device_info intel_kabylake_gt4_info = {\n\tKABYLAKE_FIELDS,\n\t.gt = 4,\n};\n\nstatic const struct intel_device_info intel_geminilake_info = {\n\t.graphics_ver = 9,\n\t.display_ver = 9,\n\t.is_geminilake = true,\n\t.codename = \"geminilake\"\n};\n\n#define COFFEELAKE_FIELDS \\\n\t.graphics_ver = 9, \\\n\t.display_ver = 9, \\\n\t.is_coffeelake = true, \\\n\t.codename = \"coffeelake\"\n\nstatic const struct intel_device_info intel_coffeelake_gt1_info = {\n\tCOFFEELAKE_FIELDS,\n\t.gt = 1,\n};\n\nstatic const struct intel_device_info intel_coffeelake_gt2_info = {\n\tCOFFEELAKE_FIELDS,\n\t.gt = 2,\n};\n\nstatic const struct intel_device_info intel_coffeelake_gt3_info = {\n\tCOFFEELAKE_FIELDS,\n\t.gt = 3,\n};\n\n#define COMETLAKE_FIELDS \\\n\t.graphics_ver = 9, \\\n\t.display_ver = 9, \\\n\t.is_cometlake = true, \\\n\t.codename = \"cometlake\"\n\nstatic const struct intel_device_info intel_cometlake_gt1_info = {\n\tCOMETLAKE_FIELDS,\n\t.gt = 1,\n};\n\nstatic const struct intel_device_info intel_cometlake_gt2_info = {\n\tCOMETLAKE_FIELDS,\n\t.gt = 2,\n};\n\nstatic const struct intel_device_info intel_cannonlake_info = {\n\t.graphics_ver = 10,\n\t.display_ver = 10,\n\t.is_cannonlake = true,\n\t.codename = \"cannonlake\"\n};\n\nstatic const struct intel_device_info intel_icelake_info = {\n\t.graphics_ver = 11,\n\t.display_ver = 11,\n\t.is_icelake = true,\n\t.codename = \"icelake\"\n};\n\nstatic const struct intel_device_info intel_elkhartlake_info = {\n\t.graphics_ver = 11,\n\t.display_ver = 11,\n\t.is_elkhartlake = true,\n\t.codename = \"elkhartlake\"\n};\n\nstatic const struct intel_device_info intel_jasperlake_info = {\n\t.graphics_ver = 11,\n\t.display_ver = 11,\n\t.is_jasperlake = true,\n\t.codename = \"jasperlake\"\n};\n\nstatic const struct intel_device_info intel_tigerlake_gt1_info = {\n\t.graphics_ver = 12,\n\t.display_ver = 12,\n\t.is_tigerlake = true,\n\t.codename = \"tigerlake\",\n\t.gt = 1,\n};\n\nstatic const struct intel_device_info intel_tigerlake_gt2_info = {\n\t.graphics_ver = 12,\n\t.display_ver = 12,\n\t.is_tigerlake = true,\n\t.codename = \"tigerlake\",\n\t.gt = 2,\n};\n\nstatic const struct intel_device_info intel_rocketlake_info = {\n\t.graphics_ver = 12,\n\t.display_ver = 12,\n\t.is_rocketlake = true,\n\t.codename = \"rocketlake\"\n};\n\nstatic const struct intel_device_info intel_dg1_info = {\n\t.graphics_ver = 12,\n\t.graphics_rel = 10,\n\t.display_ver = 12,\n\t.is_dg1 = true,\n\t.codename = \"dg1\"\n};\n\nstatic const struct intel_device_info intel_dg2_info = {\n\t.graphics_ver = 12,\n\t.graphics_rel = 55,\n\t.display_ver = 13,\n\t.has_4tile = true,\n\t.is_dg2 = true,\n\t.codename = \"dg2\",\n\t.has_flatccs = true,\n};\n\nstatic const struct intel_device_info intel_alderlake_s_info = {\n\t.graphics_ver = 12,\n\t.display_ver = 12,\n\t.is_alderlake_s = true,\n\t.codename = \"alderlake_s\"\n};\n\nstatic const struct intel_device_info intel_raptorlake_s_info = {\n\t.graphics_ver = 12,\n\t.display_ver = 12,\n\t.is_raptorlake_s = true,\n\t.codename = \"raptorlake_s\"\n};\n\nstatic const struct intel_device_info intel_alderlake_p_info = {\n\t.graphics_ver = 12,\n\t.display_ver = 13,\n\t.is_alderlake_p = true,\n\t.codename = \"alderlake_p\"\n};\n\nstatic const struct intel_device_info intel_alderlake_n_info = {\n\t.graphics_ver = 12,\n\t.display_ver = 13,\n\t.is_alderlake_n = true,\n\t.codename = \"alderlake_n\"\n};\n\nstatic const struct intel_device_info intel_ats_m_info = {\n\t.graphics_ver = 12,\n\t.graphics_rel = 55,\n\t.display_ver = 0, /* no display support */\n\t.is_dg2 = true,\n\t.has_4tile = true,\n\t.codename = \"ats_m\",\n\t.has_flatccs = true,\n};\n\nstatic const struct intel_device_info intel_meteorlake_info = {\n\t.graphics_ver = 12,\n\t.graphics_rel = 70,\n\t.display_ver = 14,\n\t.has_4tile = true,\n\t.has_oam = true,\n\t.is_meteorlake = true,\n\t.codename = \"meteorlake\",\n};\n\nstatic const struct intel_device_info intel_pontevecchio_info = {\n\t.graphics_ver = 12,\n\t.graphics_rel = 60,\n\t.is_pontevecchio = true,\n\t.codename = \"pontevecchio\",\n};\n\nstatic const struct intel_device_info intel_lunarlake_info = {\n\t.graphics_ver = 20,\n\t.graphics_rel = 4,\n\t.display_ver = 20,\n\t.has_4tile = true,\n\t.has_flatccs = true,\n\t.has_oam = true,\n\t.is_lunarlake = true,\n\t.codename = \"lunarlake\",\n};\n\nstatic const struct intel_device_info intel_battlemage_info = {\n\t.graphics_ver = 20,\n\t.graphics_rel = 1,\n\t.display_ver = 14,\n\t.has_4tile = true,\n\t.has_flatccs = true,\n\t.is_battlemage = true,\n\t.codename = \"battlemage\",\n};\n\nstatic const struct pci_id_match intel_device_match[] = {\n\tINTEL_I810_IDS(INTEL_VGA_DEVICE, &intel_i810_info),\n\tINTEL_I815_IDS(INTEL_VGA_DEVICE, &intel_i815_info),\n\n\tINTEL_I830_IDS(INTEL_VGA_DEVICE, &intel_i830_info),\n\tINTEL_I845G_IDS(INTEL_VGA_DEVICE, &intel_i845_info),\n\tINTEL_I85X_IDS(INTEL_VGA_DEVICE, &intel_i855_info),\n\tINTEL_I865G_IDS(INTEL_VGA_DEVICE, &intel_i865_info),\n\n\tINTEL_I915G_IDS(INTEL_VGA_DEVICE, &intel_i915_info),\n\tINTEL_I915GM_IDS(INTEL_VGA_DEVICE, &intel_i915m_info),\n\tINTEL_I945G_IDS(INTEL_VGA_DEVICE, &intel_i945_info),\n\tINTEL_I945GM_IDS(INTEL_VGA_DEVICE, &intel_i945m_info),\n\n\tINTEL_G33_IDS(INTEL_VGA_DEVICE, &intel_g33_info),\n\tINTEL_PNV_G_IDS(INTEL_VGA_DEVICE, &intel_pineview_g_info),\n\tINTEL_PNV_M_IDS(INTEL_VGA_DEVICE, &intel_pineview_m_info),\n\n\tINTEL_I965G_IDS(INTEL_VGA_DEVICE, &intel_i965_info),\n\tINTEL_I965GM_IDS(INTEL_VGA_DEVICE, &intel_i965m_info),\n\n\tINTEL_G45_IDS(INTEL_VGA_DEVICE, &intel_g45_info),\n\tINTEL_GM45_IDS(INTEL_VGA_DEVICE, &intel_gm45_info),\n\n\tINTEL_ILK_D_IDS(INTEL_VGA_DEVICE, &intel_ironlake_info),\n\tINTEL_ILK_M_IDS(INTEL_VGA_DEVICE, &intel_ironlake_m_info),\n\n\tINTEL_SNB_D_IDS(INTEL_VGA_DEVICE, &intel_sandybridge_info),\n\tINTEL_SNB_M_IDS(INTEL_VGA_DEVICE, &intel_sandybridge_m_info),\n\n\tINTEL_IVB_D_IDS(INTEL_VGA_DEVICE, &intel_ivybridge_info),\n\tINTEL_IVB_M_IDS(INTEL_VGA_DEVICE, &intel_ivybridge_m_info),\n\n\tINTEL_HSW_GT1_IDS(INTEL_VGA_DEVICE, &intel_haswell_gt1_info),\n\tINTEL_HSW_GT2_IDS(INTEL_VGA_DEVICE, &intel_haswell_gt2_info),\n\tINTEL_HSW_GT3_IDS(INTEL_VGA_DEVICE, &intel_haswell_gt3_info),\n\n\tINTEL_VLV_IDS(INTEL_VGA_DEVICE, &intel_valleyview_info),\n\n\tINTEL_BDW_GT1_IDS(INTEL_VGA_DEVICE, &intel_broadwell_gt1_info),\n\tINTEL_BDW_GT2_IDS(INTEL_VGA_DEVICE, &intel_broadwell_gt2_info),\n\tINTEL_BDW_GT3_IDS(INTEL_VGA_DEVICE, &intel_broadwell_gt3_info),\n\tINTEL_BDW_RSVD_IDS(INTEL_VGA_DEVICE, &intel_broadwell_unknown_info),\n\n\tINTEL_CHV_IDS(INTEL_VGA_DEVICE, &intel_cherryview_info),\n\n\tINTEL_SKL_GT1_IDS(INTEL_VGA_DEVICE, &intel_skylake_gt1_info),\n\tINTEL_SKL_GT2_IDS(INTEL_VGA_DEVICE, &intel_skylake_gt2_info),\n\tINTEL_SKL_GT3_IDS(INTEL_VGA_DEVICE, &intel_skylake_gt3_info),\n\tINTEL_SKL_GT4_IDS(INTEL_VGA_DEVICE, &intel_skylake_gt4_info),\n\n\tINTEL_BXT_IDS(INTEL_VGA_DEVICE, &intel_broxton_info),\n\n\tINTEL_KBL_GT1_IDS(INTEL_VGA_DEVICE, &intel_kabylake_gt1_info),\n\tINTEL_KBL_GT2_IDS(INTEL_VGA_DEVICE, &intel_kabylake_gt2_info),\n\tINTEL_KBL_GT3_IDS(INTEL_VGA_DEVICE, &intel_kabylake_gt3_info),\n\tINTEL_KBL_GT4_IDS(INTEL_VGA_DEVICE, &intel_kabylake_gt4_info),\n\tINTEL_AML_KBL_GT2_IDS(INTEL_VGA_DEVICE, &intel_kabylake_gt2_info),\n\n\tINTEL_GLK_IDS(INTEL_VGA_DEVICE, &intel_geminilake_info),\n\n\tINTEL_CFL_S_GT1_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt1_info),\n\tINTEL_CFL_S_GT2_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt2_info),\n\tINTEL_CFL_H_GT1_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt1_info),\n\tINTEL_CFL_H_GT2_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt2_info),\n\tINTEL_CFL_U_GT2_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt2_info),\n\tINTEL_CFL_U_GT3_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt3_info),\n\tINTEL_WHL_U_GT1_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt1_info),\n\tINTEL_WHL_U_GT2_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt2_info),\n\tINTEL_WHL_U_GT3_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt3_info),\n\tINTEL_AML_CFL_GT2_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt2_info),\n\n\tINTEL_CML_GT1_IDS(INTEL_VGA_DEVICE, &intel_cometlake_gt1_info),\n\tINTEL_CML_GT2_IDS(INTEL_VGA_DEVICE, &intel_cometlake_gt2_info),\n\tINTEL_CML_U_GT1_IDS(INTEL_VGA_DEVICE, &intel_cometlake_gt1_info),\n\tINTEL_CML_U_GT2_IDS(INTEL_VGA_DEVICE, &intel_cometlake_gt2_info),\n\n\tINTEL_CNL_IDS(INTEL_VGA_DEVICE, &intel_cannonlake_info),\n\n\tINTEL_ICL_IDS(INTEL_VGA_DEVICE, &intel_icelake_info),\n\n\tINTEL_EHL_IDS(INTEL_VGA_DEVICE, &intel_elkhartlake_info),\n\tINTEL_JSL_IDS(INTEL_VGA_DEVICE, &intel_jasperlake_info),\n\n\tINTEL_TGL_GT1_IDS(INTEL_VGA_DEVICE, &intel_tigerlake_gt1_info),\n\tINTEL_TGL_GT2_IDS(INTEL_VGA_DEVICE, &intel_tigerlake_gt2_info),\n\tINTEL_RKL_IDS(INTEL_VGA_DEVICE, &intel_rocketlake_info),\n\n\tINTEL_DG1_IDS(INTEL_VGA_DEVICE, &intel_dg1_info),\n\tINTEL_DG2_IDS(INTEL_VGA_DEVICE, &intel_dg2_info),\n\n\tINTEL_ADLS_IDS(INTEL_VGA_DEVICE, &intel_alderlake_s_info),\n\tINTEL_RPLS_IDS(INTEL_VGA_DEVICE, &intel_raptorlake_s_info),\n\tINTEL_ADLP_IDS(INTEL_VGA_DEVICE, &intel_alderlake_p_info),\n\tINTEL_RPLU_IDS(INTEL_VGA_DEVICE, &intel_alderlake_p_info),\n\tINTEL_RPLP_IDS(INTEL_VGA_DEVICE, &intel_alderlake_p_info),\n\tINTEL_ADLN_IDS(INTEL_VGA_DEVICE, &intel_alderlake_n_info),\n\n\tINTEL_ATS_M_IDS(INTEL_VGA_DEVICE, &intel_ats_m_info),\n\n\tINTEL_MTL_IDS(INTEL_VGA_DEVICE, &intel_meteorlake_info),\n\n\tINTEL_PVC_IDS(INTEL_VGA_DEVICE, &intel_pontevecchio_info),\n\n\tXE_LNL_IDS(INTEL_VGA_DEVICE, &intel_lunarlake_info),\n\n\tXE_BMG_IDS(INTEL_VGA_DEVICE, &intel_battlemage_info),\n\n\tINTEL_VGA_DEVICE(PCI_MATCH_ANY, &intel_generic_info),\n};\n\n/**\n * intel_get_device_info:\n * @devid: pci device id\n *\n * Looks up the Intel GFX device info for the given device id.\n *\n * Returns:\n * The associated intel_get_device_info\n */\nconst struct intel_device_info *intel_get_device_info(uint16_t devid)\n{\n\tstatic const struct intel_device_info *cache = &intel_generic_info;\n\tstatic uint16_t cached_devid;\n\tint i;\n\n\tif (cached_devid == devid)\n\t\tgoto out;\n\n\t/* XXX Presort table and bsearch! */\n\tfor (i = 0; intel_device_match[i].device_id != PCI_MATCH_ANY; i++) {\n\t\tif (devid == intel_device_match[i].device_id)\n\t\t\tbreak;\n\t}\n\n\tcached_devid = devid;\n\tcache = (void *)intel_device_match[i].match_data;\n\nout:\n\treturn cache;\n}"
  },
  {
    "path": "src/linux/intel_gpu_top/intel_gpu_top.c",
    "content": "/*\n * Copyright © 2007-2023 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\n#include <assert.h>\n#include <ctype.h>\n#include <dirent.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <inttypes.h>\n#include <limits.h>\n#include <locale.h>\n#include <math.h>\n#include <poll.h>\n#include <signal.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/ioctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <termios.h>\n#include <time.h>\n#include <sys/sysmacros.h>\n\n#include <stdarg.h>\n\n#include \"intel_gpu_top.h\"\n#include \"i915_drm.h\"\n#include \"igt_perf.h\"\n\n__attribute__((format(scanf,3,4)))\nstatic int igt_sysfs_scanf(int dir, const char *attr, const char *fmt, ...)\n{\n\tFILE *file;\n\tint fd;\n\tint ret = -1;\n\n\tfd = openat(dir, attr, O_RDONLY);\n\tif (fd < 0)\n\t\treturn -1;\n\n\tfile = fdopen(fd, \"r\");\n\tif (file) {\n\t\tva_list ap;\n\n\t\tva_start(ap, fmt);\n\t\tret = vfscanf(file, fmt, ap);\n\t\tva_end(ap);\n\n\t\tfclose(file);\n\t} else {\n\t\tclose(fd);\n\t}\n\n\treturn ret;\n}\n\nstatic int pmu_parse(struct pmu_counter *pmu, const char *path, const char *str)\n{\n\tlocale_t locale, oldlocale;\n\tbool result = true;\n\tchar buf[128] = {};\n\tint dir;\n\n\tdir = open(path, O_RDONLY);\n\tif (dir < 0)\n\t\treturn -errno;\n\n\t/* Replace user environment with plain C to match kernel format */\n\tlocale = newlocale(LC_ALL, \"C\", 0);\n\toldlocale = uselocale(locale);\n\n\tresult &= igt_sysfs_scanf(dir, \"type\", \"%\"PRIu64, &pmu->type) == 1;\n\n\tsnprintf(buf, sizeof(buf) - 1, \"events/%s\", str);\n\tresult &= igt_sysfs_scanf(dir, buf, \"event=%\"PRIx64, &pmu->config) == 1;\n\n\tsnprintf(buf, sizeof(buf) - 1, \"events/%s.scale\", str);\n\tresult &= igt_sysfs_scanf(dir, buf, \"%lf\", &pmu->scale) == 1;\n\n\tsnprintf(buf, sizeof(buf) - 1, \"events/%s.unit\", str);\n\tresult &= igt_sysfs_scanf(dir, buf, \"%127s\", buf) == 1;\n\tpmu->units = strdup(buf);\n\n\tuselocale(oldlocale);\n\tfreelocale(locale);\n\n\tclose(dir);\n\n\tif (!result)\n\t\treturn -EINVAL;\n\n\tif (isnan(pmu->scale) || !pmu->scale)\n\t\treturn -ERANGE;\n\n\treturn 0;\n}\n\nstatic int rapl_parse(struct pmu_counter *pmu, const char *str)\n{\n\tconst char *expected_units = \"Joules\";\n\tint err;\n\n\terr = pmu_parse(pmu, \"/sys/devices/power\", str);\n\tif (err < 0)\n\t\treturn err;\n\n\tif (!pmu->units || strcmp(pmu->units, expected_units)) {\n\t\tfprintf(stderr,\n\t\t\t\"Unexpected units for RAPL %s: found '%s', expected '%s'\\n\",\n\t\t\tstr, pmu->units, expected_units);\n\t}\n\n\treturn 0;\n}\n\nstatic void\nrapl_open(struct pmu_counter *pmu,\n\t  const char *domain,\n\t  struct engines *engines)\n{\n\tint fd;\n\n\tif (rapl_parse(pmu, domain) < 0)\n\t\treturn;\n\n\tfd = igt_perf_open_group(pmu->type, pmu->config, engines->rapl_fd);\n\tif (fd < 0)\n\t\treturn;\n\n\tif (engines->rapl_fd == -1)\n\t\tengines->rapl_fd = fd;\n\n\tpmu->idx = engines->num_rapl++;\n\tpmu->present = true;\n}\n\nstatic void gpu_power_open(struct pmu_counter *pmu,\n\t\t\t   struct engines *engines)\n{\n\trapl_open(pmu, \"energy-gpu\", engines);\n}\n\nstatic void pkg_power_open(struct pmu_counter *pmu,\n\t\t\t   struct engines *engines)\n{\n\trapl_open(pmu, \"energy-pkg\", engines);\n}\n\nstatic uint64_t\nget_pmu_config(int dirfd, const char *name, const char *counter)\n{\n\tchar buf[128], *p;\n\tint fd, ret;\n\n\tret = snprintf(buf, sizeof(buf), \"%s-%s\", name, counter);\n\tif (ret < 0 || ret == sizeof(buf))\n\t\treturn -1;\n\n\tfd = openat(dirfd, buf, O_RDONLY);\n\tif (fd < 0)\n\t\treturn -1;\n\n\tret = read(fd, buf, sizeof(buf));\n\tclose(fd);\n\tif (ret <= 0)\n\t\treturn -1;\n\n\tp = index(buf, '0');\n\tif (!p)\n\t\treturn -1;\n\n\treturn strtoul(p, NULL, 0);\n}\n\n#define engine_ptr(engines, n) (&engines->engine + (n))\n\nstatic const char *class_display_name(unsigned int class)\n{\n\tswitch (class) {\n\tcase I915_ENGINE_CLASS_RENDER:\n\t\treturn \"Render/3D\";\n\tcase I915_ENGINE_CLASS_COPY:\n\t\treturn \"Blitter\";\n\tcase I915_ENGINE_CLASS_VIDEO:\n\t\treturn \"Video\";\n\tcase I915_ENGINE_CLASS_VIDEO_ENHANCE:\n\t\treturn \"VideoEnhance\";\n\tcase I915_ENGINE_CLASS_COMPUTE:\n\t\treturn \"Compute\";\n\tdefault:\n\t\treturn \"[unknown]\";\n\t}\n}\n\nstatic const char *class_short_name(unsigned int class)\n{\n\tswitch (class) {\n\tcase I915_ENGINE_CLASS_RENDER:\n\t\treturn \"RCS\";\n\tcase I915_ENGINE_CLASS_COPY:\n\t\treturn \"BCS\";\n\tcase I915_ENGINE_CLASS_VIDEO:\n\t\treturn \"VCS\";\n\tcase I915_ENGINE_CLASS_VIDEO_ENHANCE:\n\t\treturn \"VECS\";\n\tcase I915_ENGINE_CLASS_COMPUTE:\n\t\treturn \"CCS\";\n\tdefault:\n\t\treturn \"UNKN\";\n\t}\n}\n\nstatic int engine_cmp(const void *__a, const void *__b)\n{\n\tconst struct engine *a = (struct engine *)__a;\n\tconst struct engine *b = (struct engine *)__b;\n\n\tif (a->class != b->class)\n\t\treturn a->class - b->class;\n\telse\n\t\treturn a->instance - b->instance;\n}\n\n#define is_igpu(x) (strcmp(x, \"i915\") == 0)\n\nstruct engines *discover_engines(const char *device)\n{\n\tchar sysfs_root[PATH_MAX];\n\tstruct engines *engines;\n\tstruct dirent *dent;\n\tint ret = 0;\n\tDIR *d;\n\n\tsnprintf(sysfs_root, sizeof(sysfs_root),\n\t\t \"/sys/devices/%s/events\", device);\n\n\tengines = malloc(sizeof(struct engines));\n\tif (!engines)\n\t\treturn NULL;\n\n\tmemset(engines, 0, sizeof(*engines));\n\n\tengines->num_engines = 0;\n\tengines->device = device;\n\tengines->discrete = !is_igpu(device);\n\n\td = opendir(sysfs_root);\n\tif (!d)\n\t\tgoto err;\n\n\twhile ((dent = readdir(d)) != NULL) {\n\t\tconst char *endswith = \"-busy\";\n\t\tconst unsigned int endlen = strlen(endswith);\n\t\tstruct engine *engine =\n\t\t\t\tengine_ptr(engines, engines->num_engines);\n\t\tchar buf[256];\n\n\t\tif (dent->d_type != DT_REG)\n\t\t\tcontinue;\n\n\t\tif (strlen(dent->d_name) >= sizeof(buf)) {\n\t\t\tret = ENAMETOOLONG;\n\t\t\tbreak;\n\t\t}\n\n\t\tstrcpy(buf, dent->d_name);\n\n\t\t/* xxxN-busy */\n\t\tif (strlen(buf) < (endlen + 4))\n\t\t\tcontinue;\n\t\tif (strcmp(&buf[strlen(buf) - endlen], endswith))\n\t\t\tcontinue;\n\n\t\tmemset(engine, 0, sizeof(*engine));\n\n\t\tbuf[strlen(buf) - endlen] = 0;\n\t\tengine->name = strdup(buf);\n\t\tif (!engine->name) {\n\t\t\tret = errno;\n\t\t\tbreak;\n\t\t}\n\n\t\tengine->busy.config = get_pmu_config(dirfd(d), engine->name,\n\t\t\t\t\t\t     \"busy\");\n\t\tif (engine->busy.config == -1) {\n\t\t\tret = ENOENT;\n\t\t\tbreak;\n\t\t}\n\n\t\t/* Double check config is an engine config. */\n\t\tif (engine->busy.config >= __I915_PMU_OTHER(0)) {\n\t\t\tfree((void *)engine->name);\n\t\t\tcontinue;\n\t\t}\n\n\t\tengine->class = (engine->busy.config &\n\t\t\t\t (__I915_PMU_OTHER(0) - 1)) >>\n\t\t\t\tI915_PMU_CLASS_SHIFT;\n\n\t\tengine->instance = (engine->busy.config >>\n\t\t\t\t    I915_PMU_SAMPLE_BITS) &\n\t\t\t\t    ((1 << I915_PMU_SAMPLE_INSTANCE_BITS) - 1);\n\n\t\tret = asprintf(&engine->display_name, \"%s/%u\",\n\t\t\t       class_display_name(engine->class),\n\t\t\t       engine->instance);\n\t\tif (ret <= 0) {\n\t\t\tret = errno;\n\t\t\tbreak;\n\t\t}\n\n\t\tret = asprintf(&engine->short_name, \"%s/%u\",\n\t\t\t       class_short_name(engine->class),\n\t\t\t       engine->instance);\n\t\tif (ret <= 0) {\n\t\t\tret = errno;\n\t\t\tbreak;\n\t\t}\n\n\t\tengines->num_engines++;\n\t\tengines = realloc(engines, sizeof(struct engines) +\n\t\t\t\t  engines->num_engines * sizeof(struct engine));\n\t\tif (!engines) {\n\t\t\tret = errno;\n\t\t\tbreak;\n\t\t}\n\n\t\tret = 0;\n\t}\n\n\tif (ret) {\n\t\terrno = ret;\n\t\tgoto err;\n\t}\n\n\tqsort(engine_ptr(engines, 0), engines->num_engines,\n\t      sizeof(struct engine), engine_cmp);\n\n\tengines->root = d;\n\n\treturn engines;\n\nerr:\n\tfree(engines);\n\n\treturn NULL;\n}\n\nvoid free_engines(struct engines *engines)\n{\n\tstruct pmu_counter **pmu, *free_list[] = {\n\t\t&engines->r_gpu,\n\t\t&engines->r_pkg,\n\t\t&engines->imc_reads,\n\t\t&engines->imc_writes,\n\t\tNULL\n\t};\n\tunsigned int i;\n\n\tif (!engines)\n\t\treturn;\n\n\tfor (pmu = &free_list[0]; *pmu; pmu++) {\n\t\tif ((*pmu)->present)\n\t\t\tfree((char *)(*pmu)->units);\n\t}\n\n\tfor (i = 0; i < engines->num_engines; i++) {\n\t\tstruct engine *engine = engine_ptr(engines, i);\n\n\t\tfree((char *)engine->name);\n\t\tfree((char *)engine->short_name);\n\t\tfree((char *)engine->display_name);\n\t}\n\n\tclosedir(engines->root);\n\n\tfree(engines->class);\n\tfree(engines);\n}\n\n#define _open_pmu(type, cnt, pmu, fd) \\\n({ \\\n\tint fd__; \\\n\\\n\tfd__ = igt_perf_open_group((type), (pmu)->config, (fd)); \\\n\tif (fd__ >= 0) { \\\n\t\tif ((fd) == -1) \\\n\t\t\t(fd) = fd__; \\\n\t\t(pmu)->present = true; \\\n\t\t(pmu)->idx = (cnt)++; \\\n\t} \\\n\\\n\tfd__; \\\n})\n\nstatic int imc_parse(struct pmu_counter *pmu, const char *str)\n{\n\treturn pmu_parse(pmu, \"/sys/devices/uncore_imc\", str);\n}\n\nstatic void\nimc_open(struct pmu_counter *pmu,\n\t const char *domain,\n\t struct engines *engines)\n{\n\tint fd;\n\n\tif (imc_parse(pmu, domain) < 0)\n\t\treturn;\n\n\tfd = igt_perf_open_group(pmu->type, pmu->config, engines->imc_fd);\n\tif (fd < 0)\n\t\treturn;\n\n\tif (engines->imc_fd == -1)\n\t\tengines->imc_fd = fd;\n\n\tpmu->idx = engines->num_imc++;\n\tpmu->present = true;\n}\n\nstatic void imc_writes_open(struct pmu_counter *pmu, struct engines *engines)\n{\n\timc_open(pmu, \"data_writes\", engines);\n}\n\nstatic void imc_reads_open(struct pmu_counter *pmu, struct engines *engines)\n{\n\timc_open(pmu, \"data_reads\", engines);\n}\n\nstatic int get_num_gts(uint64_t type)\n{\n\tint fd, cnt;\n\n\terrno = 0;\n\tfor (cnt = 0; cnt < MAX_GTS; cnt++) {\n\t\tfd = igt_perf_open(type, __I915_PMU_INTERRUPTS(cnt));\n\t\tif (fd < 0)\n\t\t\tbreak;\n\n\t\tclose(fd);\n\t}\n\n\tif (!cnt || (errno && errno != ENOENT))\n\t\tcnt = -errno;\n\n\treturn cnt;\n}\n\nstatic void init_aggregate_counters(struct engines *engines)\n{\n\tstruct pmu_counter *pmu;\n\n\tpmu = &engines->freq_req;\n\tpmu->type = igt_perf_type_id(engines->device);\n\tpmu->config = I915_PMU_REQUESTED_FREQUENCY;\n\tpmu->present = true;\n\n\tpmu = &engines->freq_act;\n\tpmu->type = igt_perf_type_id(engines->device);\n\tpmu->config = I915_PMU_ACTUAL_FREQUENCY;\n\tpmu->present = true;\n\n\tpmu = &engines->rc6;\n\tpmu->type = igt_perf_type_id(engines->device);\n\tpmu->config = I915_PMU_RC6_RESIDENCY;\n\tpmu->present = true;\n}\n\nint pmu_init(struct engines *engines)\n{\n\tunsigned int i;\n\tint fd;\n\tuint64_t type = igt_perf_type_id(engines->device);\n\n\tengines->fd = -1;\n\tengines->num_counters = 0;\n\tengines->num_gts = get_num_gts(type);\n\tif (engines->num_gts <= 0)\n\t\treturn -1;\n\n\tengines->irq.config = I915_PMU_INTERRUPTS;\n\tfd = _open_pmu(type, engines->num_counters, &engines->irq, engines->fd);\n\tif (fd < 0)\n\t\treturn -1;\n\n\tinit_aggregate_counters(engines);\n\n\tfor (i = 0; i < engines->num_gts; i++) {\n\t\tengines->freq_req_gt[i].config = __I915_PMU_REQUESTED_FREQUENCY(i);\n\t\t_open_pmu(type, engines->num_counters, &engines->freq_req_gt[i], engines->fd);\n\n\t\tengines->freq_act_gt[i].config = __I915_PMU_ACTUAL_FREQUENCY(i);\n\t\t_open_pmu(type, engines->num_counters, &engines->freq_act_gt[i], engines->fd);\n\n\t\tengines->rc6_gt[i].config = __I915_PMU_RC6_RESIDENCY(i);\n\t\t_open_pmu(type, engines->num_counters, &engines->rc6_gt[i], engines->fd);\n\t}\n\n\tfor (i = 0; i < engines->num_engines; i++) {\n\t\tstruct engine *engine = engine_ptr(engines, i);\n\t\tstruct {\n\t\t\tstruct pmu_counter *pmu;\n\t\t\tconst char *counter;\n\t\t} *cnt, counters[] = {\n\t\t\t{ .pmu = &engine->busy, .counter = \"busy\" },\n\t\t\t{ .pmu = &engine->wait, .counter = \"wait\" },\n\t\t\t{ .pmu = &engine->sema, .counter = \"sema\" },\n\t\t\t{ .pmu = NULL, .counter = NULL },\n\t\t};\n\n\t\tfor (cnt = counters; cnt->pmu; cnt++) {\n\t\t\tif (!cnt->pmu->config)\n\t\t\t\tcnt->pmu->config =\n\t\t\t\t\tget_pmu_config(dirfd(engines->root),\n\t\t\t\t\t\t       engine->name,\n\t\t\t\t\t\t       cnt->counter);\n\t\t\tfd = _open_pmu(type, engines->num_counters, cnt->pmu,\n\t\t\t\t       engines->fd);\n\t\t\tif (fd >= 0)\n\t\t\t\tengine->num_counters++;\n\t\t}\n\t}\n\n\tengines->rapl_fd = -1;\n\tif (!engines->discrete) {\n\t\tgpu_power_open(&engines->r_gpu, engines);\n\t\tpkg_power_open(&engines->r_pkg, engines);\n\t}\n\n\tengines->imc_fd = -1;\n\timc_reads_open(&engines->imc_reads, engines);\n\timc_writes_open(&engines->imc_writes, engines);\n\n\treturn 0;\n}\n\nstatic uint64_t pmu_read_multi(int fd, unsigned int num, uint64_t *val)\n{\n\tuint64_t buf[2 + num];\n\tunsigned int i;\n\tssize_t len;\n\n\tmemset(buf, 0, sizeof(buf));\n\n\tlen = read(fd, buf, sizeof(buf));\n\tassert(len == sizeof(buf));\n\n\tfor (i = 0; i < num; i++)\n\t\tval[i] = buf[2 + i];\n\n\treturn buf[1];\n}\n\ndouble pmu_calc(struct pmu_pair *p, double d, double t, double s)\n{\n\tdouble v;\n\n\tv = p->cur - p->prev;\n\tv /= d;\n\tv /= t;\n\tv *= s;\n\n\tif (s == 100.0 && v > 100.0)\n\t\tv = 100.0;\n\n\treturn v;\n}\n\nstatic void __update_sample(struct pmu_counter *counter, uint64_t val)\n{\n\tcounter->val.prev = counter->val.cur;\n\tcounter->val.cur = val;\n}\n\nstatic void update_sample(struct pmu_counter *counter, uint64_t *val)\n{\n\tif (counter->present)\n\t\t__update_sample(counter, val[counter->idx]);\n}\n\nvoid pmu_sample(struct engines *engines)\n{\n\tconst int num_val = engines->num_counters;\n\tuint64_t val[2 + num_val];\n\tunsigned int i;\n\n\tengines->ts.prev = engines->ts.cur;\n\tengines->ts.cur = pmu_read_multi(engines->fd, num_val, val);\n\n\tengines->freq_req.val.cur = engines->freq_req.val.prev = 0;\n\tengines->freq_act.val.cur = engines->freq_act.val.prev = 0;\n\tengines->rc6.val.cur = engines->rc6.val.prev = 0;\n\n\tfor (i = 0; i < engines->num_gts; i++) {\n\t\tupdate_sample(&engines->freq_req_gt[i], val);\n\t\tengines->freq_req.val.cur += engines->freq_req_gt[i].val.cur;\n\t\tengines->freq_req.val.prev += engines->freq_req_gt[i].val.prev;\n\n\t\tupdate_sample(&engines->freq_act_gt[i], val);\n\t\tengines->freq_act.val.cur += engines->freq_act_gt[i].val.cur;\n\t\tengines->freq_act.val.prev += engines->freq_act_gt[i].val.prev;\n\n\t\tupdate_sample(&engines->rc6_gt[i], val);\n\t\tengines->rc6.val.cur += engines->rc6_gt[i].val.cur;\n\t\tengines->rc6.val.prev += engines->rc6_gt[i].val.prev;\n\t}\n\n\tengines->freq_req.val.cur /= engines->num_gts;\n\tengines->freq_req.val.prev /= engines->num_gts;\n\n\tengines->freq_act.val.cur /= engines->num_gts;\n\tengines->freq_act.val.prev /= engines->num_gts;\n\n\tengines->rc6.val.cur /= engines->num_gts;\n\tengines->rc6.val.prev /= engines->num_gts;\n\n\tupdate_sample(&engines->irq, val);\n\n\tfor (i = 0; i < engines->num_engines; i++) {\n\t\tstruct engine *engine = engine_ptr(engines, i);\n\n\t\tupdate_sample(&engine->busy, val);\n\t\tupdate_sample(&engine->sema, val);\n\t\tupdate_sample(&engine->wait, val);\n\t}\n\n\tif (engines->num_rapl) {\n\t\tpmu_read_multi(engines->rapl_fd, engines->num_rapl, val);\n\t\tupdate_sample(&engines->r_gpu, val);\n\t\tupdate_sample(&engines->r_pkg, val);\n\t}\n\n\tif (engines->num_imc) {\n\t\tpmu_read_multi(engines->imc_fd, engines->num_imc, val);\n\t\tupdate_sample(&engines->imc_reads, val);\n\t\tupdate_sample(&engines->imc_writes, val);\n\t}\n}\n"
  },
  {
    "path": "src/linux/intel_gpu_top/intel_gpu_top.h",
    "content": "#ifndef INTEL_GPU_TOP_H\n#define INTEL_GPU_TOP_H\n\n#include <stdbool.h>\n#include <stdint.h>\n#include <dirent.h>\n\nstruct pmu_pair {\n\tuint64_t cur;\n\tuint64_t prev;\n};\n\nstruct pmu_counter {\n\tuint64_t type;\n\tuint64_t config;\n\tunsigned int idx;\n\tstruct pmu_pair val;\n\tdouble scale;\n\tconst char *units;\n\tbool present;\n};\n\nstruct engine_class {\n\tunsigned int engine_class;\n\tconst char *name;\n\tunsigned int num_engines;\n};\n\nstruct engine {\n\tconst char *name;\n\tchar *display_name;\n\tchar *short_name;\n\n\tunsigned int class;\n\tunsigned int instance;\n\n\tunsigned int num_counters;\n\n\tstruct pmu_counter busy;\n\tstruct pmu_counter wait;\n\tstruct pmu_counter sema;\n};\n\n#define MAX_GTS 4\nstruct engines {\n\tunsigned int num_engines;\n\tunsigned int num_classes;\n\tstruct engine_class *class;\n\tunsigned int num_counters;\n\tDIR *root;\n\tint fd;\n\tstruct pmu_pair ts;\n\n\tint rapl_fd;\n\tstruct pmu_counter r_gpu, r_pkg;\n\tunsigned int num_rapl;\n\n\tint imc_fd;\n\tstruct pmu_counter imc_reads;\n\tstruct pmu_counter imc_writes;\n\tunsigned int num_imc;\n\n\tstruct pmu_counter freq_req;\n\tstruct pmu_counter freq_req_gt[MAX_GTS];\n\tstruct pmu_counter freq_act;\n\tstruct pmu_counter freq_act_gt[MAX_GTS];\n\tstruct pmu_counter irq;\n\tstruct pmu_counter rc6;\n\tstruct pmu_counter rc6_gt[MAX_GTS];\n\n\tbool discrete;\n\tchar *device;\n\n\tint num_gts;\n\n\t/* Do not edit below this line.\n\t * This structure is reallocated every time a new engine is\n\t * found and size is increased by sizeof (engine).\n\t */\n\n\tstruct engine engine;\n\n};\n\nstruct engines *discover_engines(const char *device);\nvoid free_engines(struct engines *engines);\nint pmu_init(struct engines *engines);\nvoid pmu_sample(struct engines *engines);\ndouble pmu_calc(struct pmu_pair *p, double d, double t, double s);\n\nchar* find_intel_gpu_dir();\nchar* get_intel_device_id(const char* vendor_path);\nchar *get_intel_device_name(const char *device_id);\n\n#endif"
  },
  {
    "path": "src/linux/intel_gpu_top/intel_name_lookup_shim.c",
    "content": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <dirent.h>\n#include <unistd.h>\n#include <ctype.h>\n\n#include \"intel_gpu_top.h\"\n#include \"intel_chipset.h\"\n\n#define VENDOR_ID \"0x8086\"\n#define SYSFS_PATH \"/sys/class/drm\"\n#define VENDOR_FILE \"vendor\"\n#define DEVICE_FILE \"device\"\n\nchar* find_intel_gpu_dir() {\n    DIR *dir;\n    struct dirent *entry;\n    static char path[256];\n    char vendor_path[256];\n    char vendor_id[16];\n\n    if ((dir = opendir(SYSFS_PATH)) == NULL) {\n        perror(\"opendir\");\n        return NULL;\n    }\n\n    while ((entry = readdir(dir)) != NULL) {\n        // Construct the path to the vendor file\n        snprintf(vendor_path, sizeof(vendor_path), \"%s/%s/device/%s\", SYSFS_PATH, entry->d_name, VENDOR_FILE);\n\n        // Check if the vendor file exists\n        if (access(vendor_path, F_OK) != -1) {\n            FILE *file = fopen(vendor_path, \"r\");\n            if (file) {\n                if (fgets(vendor_id, sizeof(vendor_id), file)) {\n                    // Trim the newline character\n                    vendor_id[strcspn(vendor_id, \"\\n\")] = 0;\n\n                    if (strcmp(vendor_id, VENDOR_ID) == 0) {\n                        // Return the parent directory (i.e., /sys/class/drm/card*)\n                        snprintf(path, sizeof(path), \"%s/%s\", SYSFS_PATH, entry->d_name);\n                        fclose(file);\n                        closedir(dir);\n                        return path;\n                    }\n                }\n                fclose(file);\n            }\n        }\n    }\n\n    closedir(dir);\n    return NULL;  // Intel GPU not found\n}\n\nchar* get_intel_device_id(const char* gpu_dir) {\n    static char device_path[256];\n    char device_id[16];\n\n    // Construct the path to the device file\n    snprintf(device_path, sizeof(device_path), \"%s/device/%s\", gpu_dir, DEVICE_FILE);\n\n    FILE *file = fopen(device_path, \"r\");\n    if (file) {\n        if (fgets(device_id, sizeof(device_id), file)) {\n            fclose(file);\n            // Trim the newline character\n            device_id[strcspn(device_id, \"\\n\")] = 0;\n            // Return a copy of the device ID\n            return strdup(device_id);\n        }\n        fclose(file);\n    } else {\n        perror(\"fopen\");\n    }\n\n    return NULL;\n}\n\nchar *get_intel_device_name(const char *device_id) {\n    uint16_t devid = strtol(device_id, NULL, 16);\n    char dev_name[256];\n    char full_name[256];\n    const struct intel_device_info *info = intel_get_device_info(devid);\n    if (info) {\n        if (info->codename == NULL) {\n            strcpy(dev_name, \"(unknown)\");\n        } else {\n            strcpy(dev_name, info->codename);\n            dev_name[0] = toupper(dev_name[0]);\n        }\n        snprintf(full_name, sizeof(full_name), \"Intel %s (Gen%u)\", dev_name, info->graphics_ver);\n        return strdup(full_name);\n    }\n    return NULL;\n}\n"
  },
  {
    "path": "src/linux/intel_gpu_top/source.txt",
    "content": "0f02dc176959e6296866b1bafd3982e277a5e44b\nhttps://gitlab.freedesktop.org/drm/igt-gpu-tools.git"
  },
  {
    "path": "src/linux/intel_gpu_top/xe_pciids.h",
    "content": "/* SPDX-License-Identifier: MIT */\n/*\n * Copyright © 2022 Intel Corporation\n */\n\n#ifndef _XE_PCIIDS_H_\n#define _XE_PCIIDS_H_\n\n/*\n * Lists below can be turned into initializers for a struct pci_device_id\n * by defining INTEL_VGA_DEVICE:\n *\n * #define INTEL_VGA_DEVICE(id, info) { \\\n *\t0x8086, id,\t\t\t\\\n *\t~0, ~0,\t\t\t\t\\\n *\t0x030000, 0xff0000,\t\t\\\n *\t(unsigned long) info }\n *\n * And then calling like:\n *\n * XE_TGL_12_GT1_IDS(INTEL_VGA_DEVICE, ## __VA_ARGS__)\n *\n * To turn them into something else, just provide a different macro passed as\n * first argument.\n */\n\n/* TGL */\n#define XE_TGL_GT1_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x9A60, ## __VA_ARGS__),\t\\\n\tMACRO__(0x9A68, ## __VA_ARGS__),\t\\\n\tMACRO__(0x9A70, ## __VA_ARGS__)\n\n#define XE_TGL_GT2_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x9A40, ## __VA_ARGS__),\t\\\n\tMACRO__(0x9A49, ## __VA_ARGS__),\t\\\n\tMACRO__(0x9A59, ## __VA_ARGS__),\t\\\n\tMACRO__(0x9A78, ## __VA_ARGS__),\t\\\n\tMACRO__(0x9AC0, ## __VA_ARGS__),\t\\\n\tMACRO__(0x9AC9, ## __VA_ARGS__),\t\\\n\tMACRO__(0x9AD9, ## __VA_ARGS__),\t\\\n\tMACRO__(0x9AF8, ## __VA_ARGS__)\n\n#define XE_TGL_IDS(MACRO__, ...)\t\t\\\n\tXE_TGL_GT1_IDS(MACRO__, ## __VA_ARGS__),\\\n\tXE_TGL_GT2_IDS(MACRO__, ## __VA_ARGS__)\n\n/* RKL */\n#define XE_RKL_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x4C80, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4C8A, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4C8B, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4C8C, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4C90, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4C9A, ## __VA_ARGS__)\n\n/* DG1 */\n#define XE_DG1_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x4905, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4906, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4907, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4908, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4909, ## __VA_ARGS__)\n\n/* ADL-S */\n#define XE_ADLS_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x4680, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4682, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4688, ## __VA_ARGS__),\t\\\n\tMACRO__(0x468A, ## __VA_ARGS__),\t\\\n\tMACRO__(0x468B, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4690, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4692, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4693, ## __VA_ARGS__)\n\n/* ADL-P */\n#define XE_ADLP_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x46A0, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46A1, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46A2, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46A3, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46A6, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46A8, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46AA, ## __VA_ARGS__),\t\\\n\tMACRO__(0x462A, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4626, ## __VA_ARGS__),\t\\\n\tMACRO__(0x4628, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46B0, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46B1, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46B2, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46B3, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46C0, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46C1, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46C2, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46C3, ## __VA_ARGS__)\n\n/* ADL-N */\n#define XE_ADLN_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x46D0, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46D1, ## __VA_ARGS__),\t\\\n\tMACRO__(0x46D2, ## __VA_ARGS__)\n\n/* RPL-S */\n#define XE_RPLS_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0xA780, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA781, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA782, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA783, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA788, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA789, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA78A, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA78B, ## __VA_ARGS__)\n\n/* RPL-U */\n#define XE_RPLU_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0xA721, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA7A1, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA7A9, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA7AC, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA7AD, ## __VA_ARGS__)\n\n/* RPL-P */\n#define XE_RPLP_IDS(MACRO__, ...)\t\t\\\n\tXE_RPLU_IDS(MACRO__, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA720, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA7A0, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA7A8, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA7AA, ## __VA_ARGS__),\t\\\n\tMACRO__(0xA7AB, ## __VA_ARGS__)\n\n/* DG2 */\n#define XE_DG2_G10_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x5690, ## __VA_ARGS__),\t\\\n\tMACRO__(0x5691, ## __VA_ARGS__),\t\\\n\tMACRO__(0x5692, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56A0, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56A1, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56A2, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56BE, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56BF, ## __VA_ARGS__)\n\n#define XE_DG2_G11_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x5693, ## __VA_ARGS__),\t\\\n\tMACRO__(0x5694, ## __VA_ARGS__),\t\\\n\tMACRO__(0x5695, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56A5, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56A6, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56B0, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56B1, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56BA, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56BB, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56BC, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56BD, ## __VA_ARGS__)\n\n#define XE_DG2_G12_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x5696, ## __VA_ARGS__),\t\\\n\tMACRO__(0x5697, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56A3, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56A4, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56B2, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56B3, ## __VA_ARGS__)\n\n#define XE_DG2_IDS(MACRO__, ...)\t\t\\\n\tXE_DG2_G10_IDS(MACRO__, ## __VA_ARGS__),\\\n\tXE_DG2_G11_IDS(MACRO__, ## __VA_ARGS__),\\\n\tXE_DG2_G12_IDS(MACRO__, ## __VA_ARGS__)\n\n#define XE_ATS_M150_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x56C0, ## __VA_ARGS__),\t\\\n\tMACRO__(0x56C2, ## __VA_ARGS__)\n\n#define XE_ATS_M75_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x56C1, ## __VA_ARGS__)\n\n#define XE_ATS_M_IDS(MACRO__, ...)\t\t\\\n\tXE_ATS_M150_IDS(MACRO__, ## __VA_ARGS__),\\\n\tXE_ATS_M75_IDS(MACRO__, ## __VA_ARGS__)\n\n/* MTL / ARL */\n#define XE_MTL_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x7D40, ## __VA_ARGS__),\t\\\n\tMACRO__(0x7D41, ## __VA_ARGS__),\t\\\n\tMACRO__(0x7D45, ## __VA_ARGS__),\t\\\n\tMACRO__(0x7D51, ## __VA_ARGS__),        \\\n\tMACRO__(0x7D55, ## __VA_ARGS__),\t\\\n\tMACRO__(0x7D60, ## __VA_ARGS__),\t\\\n\tMACRO__(0x7D67, ## __VA_ARGS__),\t\\\n\tMACRO__(0x7DD1, ## __VA_ARGS__),        \\\n\tMACRO__(0x7DD5, ## __VA_ARGS__)\n\n/* PVC */\n#define XE_PVC_IDS(MACRO__, ...)\t\t\\\n\tMACRO__(0x0B69, ## __VA_ARGS__),\t\\\n\tMACRO__(0x0B6E, ## __VA_ARGS__),\t\\\n\tMACRO__(0x0BD4, ## __VA_ARGS__),\t\\\n\tMACRO__(0x0BD5, ## __VA_ARGS__),\t\\\n\tMACRO__(0x0BD6, ## __VA_ARGS__),\t\\\n\tMACRO__(0x0BD7, ## __VA_ARGS__),\t\\\n\tMACRO__(0x0BD8, ## __VA_ARGS__),\t\\\n\tMACRO__(0x0BD9, ## __VA_ARGS__),\t\\\n\tMACRO__(0x0BDA, ## __VA_ARGS__),\t\\\n\tMACRO__(0x0BDB, ## __VA_ARGS__),\t\\\n\tMACRO__(0x0BE0, ## __VA_ARGS__),\t\\\n\tMACRO__(0x0BE1, ## __VA_ARGS__),\t\\\n\tMACRO__(0x0BE5, ## __VA_ARGS__)\n\n#define XE_LNL_IDS(MACRO__, ...) \\\n\tMACRO__(0x6420, ## __VA_ARGS__), \\\n\tMACRO__(0x64A0, ## __VA_ARGS__), \\\n\tMACRO__(0x64B0, ## __VA_ARGS__)\n\n#define XE_BMG_IDS(MACRO__, ...) \\\n\tMACRO__(0xE202, ## __VA_ARGS__), \\\n\tMACRO__(0xE20B, ## __VA_ARGS__), \\\n\tMACRO__(0xE20C, ## __VA_ARGS__), \\\n\tMACRO__(0xE20D, ## __VA_ARGS__), \\\n\tMACRO__(0xE212, ## __VA_ARGS__)\n\n#endif\n"
  },
  {
    "path": "src/main.cpp",
    "content": "// SPDX-License-Identifier: Apache-2.0\n\n#include \"btop.hpp\"\n\n#include <iterator>\n#include <ranges>\n#include <string_view>\n#include <vector>\n\nauto main(int argc, const char* argv[]) -> int {\n\treturn btop_main(std::views::counted(std::next(argv), argc - 1) | std::ranges::to<std::vector<std::string_view>>());\n}\n"
  },
  {
    "path": "src/netbsd/btop_collect.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n   Copyright 2024 Santhosh Raju (fox@NetBSD.org)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n#include <arpa/inet.h>\n#include <cstddef>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n// man 3 getifaddrs: \"BUGS: If\tboth <net/if.h>\tand <ifaddrs.h>\tare being included, <net/if.h> must be included before <ifaddrs.h>\"\n#include <net/if.h>\n#include <ifaddrs.h>\n#include <net/if_dl.h>\n#include <net/route.h>\n#include <netdb.h>\n#include <netinet/tcp_fsm.h>\n#include <netinet/in.h> // for inet_ntop stuff\n#include <pwd.h>\n#include <prop/proplib.h>\n#include <sys/endian.h>\n#include <sys/iostat.h>\n#include <sys/envsys.h>\n#include <sys/resource.h>\n#include <sys/socket.h>\n#include <sys/statvfs.h>\n#include <sys/sysctl.h>\n#include <sys/sched.h>\n#include <sys/signal.h>\n#include <sys/siginfo.h>\n#include <sys/proc.h>\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/ucred.h>\n#include <sys/mount.h>\n#include <sys/vmmeter.h>\n#include <sys/disk.h>\n#include <vector>\n#include <kvm.h>\n#include <paths.h>\n#include <fcntl.h>\n#include <regex.h>\n#include <unistd.h>\n#include <uvm/uvm_extern.h>\n\n#include <stdexcept>\n#include <cmath>\n#include <fstream>\n#include <numeric>\n#include <ranges>\n#include <algorithm>\n#include <regex>\n#include <string>\n#include <memory>\n#include <utility>\n#include <unordered_set>\n\n#include <fmt/format.h>\n\n#include \"../btop_config.hpp\"\n#include \"../btop_log.hpp\"\n#include \"../btop_shared.hpp\"\n#include \"../btop_tools.hpp\"\n\nusing std::clamp, std::string_literals::operator\"\"s, std::cmp_equal, std::cmp_less, std::cmp_greater;\nusing std::ifstream, std::numeric_limits, std::streamsize, std::round, std::max, std::min;\nnamespace fs = std::filesystem;\nnamespace rng = std::ranges;\nusing namespace Tools;\n\n//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------\n\nnamespace Cpu {\n\tvector<long long> core_old_totals;\n\tvector<long long> core_old_idles;\n\tvector<string> available_fields = {\"total\"};\n\tvector<string> available_sensors = {\"Auto\"};\n\tcpu_info current_cpu;\n\tbool got_sensors = false, cpu_temp_only = false, supports_watts = false;\n\n\t//* Populate found_sensors map\n\tbool get_sensors();\n\n\t//* Get current cpu clock speed\n\tstring get_cpuHz();\n\n\t//* Search /proc/cpuinfo for a cpu name\n\tstring get_cpuName();\n\n\tstruct Sensor {\n\t\tfs::path path;\n\t\tstring label;\n\t\tint64_t temp = 0;\n\t\tint64_t high = 0;\n\t\tint64_t crit = 0;\n\t};\n\n\tstring cpu_sensor;\n\tvector<string> core_sensors;\n\tstd::unordered_map<int, int> core_mapping;\n}  // namespace Cpu\n\nnamespace Mem {\n\tdouble old_uptime;\n}\n\nnamespace Shared {\n\n\tfs::path passwd_path;\n\tuint64_t totalMem;\n\tlong pageSize, clkTck, coreCount, physicalCoreCount, arg_max;\n\tint totalMem_len, kfscale;\n\tlong bootTime;\n\tsize_t size;\n\n\tvoid init() {\n\t\t//? Shared global variables init\n\t\tint mib[2];\n\t\tmib[0] = CTL_HW;\n\t\tmib[1] = HW_NCPU;\n\t\tint ncpu;\n\t\tsize_t len = sizeof(ncpu);\n\t\tif (sysctl(mib, 2, &ncpu, &len, nullptr, 0) == -1) {\n\t\t\tLogger::warning(\"Could not determine number of cores, defaulting to 1.\");\n\t\t} else {\n\t\t\tcoreCount = ncpu;\n\t\t}\n\n\t\tsize = sizeof(pageSize);\n\t\tif (sysctlbyname(\"hw.pagesize\", &pageSize, &size, nullptr, 0) < 0) {\n\t\t\tpageSize = 4096;\n\t\t\tLogger::warning(\"Could not get system page size. Defaulting to 4096, processes memory usage might be incorrect.\");\n\t\t}\n\n\t\tclkTck = sysconf(_SC_CLK_TCK);\n\t\tif (clkTck <= 0) {\n\t\t\tclkTck = 100;\n\t\t\tLogger::warning(\"Could not get system clock ticks per second. Defaulting to 100, processes cpu usage might be incorrect.\");\n\t\t}\n\n\t\tsize = sizeof(totalMem);\n\t\tif (sysctlbyname(\"hw.physmem64\", &totalMem, &size, nullptr, 0) < 0) {\n\t\t\tLogger::warning(\"Could not get memory size\");\n\t\t}\n\n\t\tstruct timeval result;\n\t\tsize = sizeof(result);\n\t\tif (sysctlbyname(\"kern.boottime\", &result, &size, nullptr, 0) < 0) {\n\t\t\tLogger::warning(\"Could not get boot time\");\n\t\t} else {\n\t\t\tbootTime = result.tv_sec;\n\t\t}\n\n\t\tsize = sizeof(kfscale);\n\t\tif (sysctlbyname(\"kern.fscale\", &kfscale, &size, nullptr, 0) == -1) {\n\t\t\tkfscale = 2048;\n\t\t}\n\n\t\t//* Get maximum length of process arguments\n\t\targ_max = sysconf(_SC_ARG_MAX);\n\n\t\t//? Init for namespace Cpu\n\t\tCpu::current_cpu.core_percent.insert(Cpu::current_cpu.core_percent.begin(), Shared::coreCount, {});\n\t\tCpu::current_cpu.temp.insert(Cpu::current_cpu.temp.begin(), Shared::coreCount + 1, {});\n\t\tCpu::core_old_totals.insert(Cpu::core_old_totals.begin(), Shared::coreCount, 0);\n\t\tCpu::core_old_idles.insert(Cpu::core_old_idles.begin(), Shared::coreCount, 0);\n\t\tCpu::collect();\n\t\tfor (auto &[field, vec] : Cpu::current_cpu.cpu_percent) {\n\t\t\tif (not vec.empty() and not v_contains(Cpu::available_fields, field)) Cpu::available_fields.push_back(field);\n\t\t}\n\t\tCpu::cpuName = Cpu::get_cpuName();\n\t\tCpu::got_sensors = Cpu::get_sensors();\n\t\tCpu::core_mapping = Cpu::get_core_mapping();\n\n\t\t//? Init for namespace Mem\n\t\tMem::old_uptime = system_uptime();\n\t\tMem::collect();\n\t}\n}  // namespace Shared\n\nnamespace Cpu {\n\tstring cpuName;\n\tstring cpuHz;\n\tbool has_battery = true;\n\ttuple<int, float, long, string> current_bat;\n\n\tconst array<string, 10> time_names = {\"user\", \"nice\", \"system\", \"idle\"};\n\n\tstd::unordered_map<string, long long> cpu_old = {\n\t\t{\"totals\", 0},\n\t\t{\"idles\", 0},\n\t\t{\"user\", 0},\n\t\t{\"nice\", 0},\n\t\t{\"system\", 0},\n\t\t{\"idle\", 0}\n\t};\n\n\tstring get_cpuName() {\n\t\tstring name;\n\t\tchar buffer[1024];\n\t\tsize_t size = sizeof(buffer);\n\t\tif (sysctlbyname(\"hw.model\", &buffer, &size, nullptr, 0) < 0) {\n\t\t\tLogger::error(\"Failed to get CPU name\");\n\t\t\treturn name;\n\t\t}\n\t\treturn trim_name(string(buffer));\n\t}\n\n\tbool get_sensors() {\n\t\tgot_sensors = false;\n\t\tprop_dictionary_t dict;\n\t\tprop_object_t fields_array;\n\t\t// List of common thermal sensors in NetBSD.\n\t\tconst string sensors[6] = {\n\t\t\t\"coretemp0\",\n\t\t\t\"acpitz0\",\n\t\t\t\"thinkpad0\",\n\t\t\t\"amdzentemp0\",\n\t\t\t\"coretemp1\",\n\t\t\t\"acpitz1\"\n\t\t};\n\n\t\tint fd = open(_PATH_SYSMON, O_RDONLY);\n\t\tif (fd == -1) {\n\t\t\tLogger::warning(\"failed to open {}\", _PATH_SYSMON);\n\t\t\treturn got_sensors;\n\t\t}\n\n\t\tif (prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict) != 0) {\n\t\t\tif (fd != -1) {\n\t\t\t\tclose(fd);\n\t\t\t}\n\t\t\tLogger::warning(\"failed to open envsys dict\");\n\t\t\treturn got_sensors;\n\t\t}\n\n\t\tclose(fd);\n\n\t\tif (prop_dictionary_count(dict) == 0) {\n\t\t\tLogger::warning(\"no drivers registered for envsys\");\n\t\t\treturn got_sensors;\n\t\t}\n\n\t\t// Search through a known list of sensors and break the loop on finding the first.\n\t\tfor(const string &sensor : sensors) {\n\t\t\tfields_array = prop_dictionary_get(prop_dictionary_t(dict), sensor.c_str());\n\t\t\tif (prop_object_type(fields_array) != PROP_TYPE_ARRAY) {\n\t\t\t\tLogger::warning(\"unknown device {}\", sensor);\n\t\t\t} else {\n\t\t\t\tCpu::cpu_sensor = sensor;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (prop_object_type(fields_array) != PROP_TYPE_ARRAY) {\n\t\t\treturn got_sensors;\n\t\t}\n\n\t\tif (Config::getB(\"show_coretemp\") and Config::getB(\"check_temp\")) {\n\t\t\tgot_sensors = true;\n\t\t}\n\n\t\treturn got_sensors;\n\t}\n\n#define MUKTOC(v) ((v - 273150000) / 1000000.0)\n\n\tvoid update_sensors() {\n\t\tint64_t current_temp = -1;\n\t\tcurrent_cpu.temp_max = 95;\n\t\tprop_dictionary_t dict, fields, props;\n\n\t\tint fd = open(_PATH_SYSMON, O_RDONLY);\n\t\tif (fd == -1) {\n\t\t\tLogger::warning(\"failed to open {}\", _PATH_SYSMON);\n\t\t\treturn;\n\t\t}\n\n\t\tif (prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict) != 0) {\n\t\t\tif (fd != -1) {\n\t\t\t\tclose(fd);\n\t\t\t}\n\t\t\tLogger::warning(\"failed to open envsys dict\");\n\t\t\treturn;\n\t\t}\n\n\t\tclose(fd);\n\n\t\tif (prop_dictionary_count(dict) == 0) {\n\t\t\tLogger::warning(\"no drivers registered for envsys\");\n\t\t\treturn;\n\t\t}\n\n\t\tprop_object_t fields_array = prop_dictionary_get(prop_dictionary_t(dict), Cpu::cpu_sensor.c_str());\n\t\tif (prop_object_type(fields_array) != PROP_TYPE_ARRAY) {\n\t\t\tLogger::warning(\"unknown device {}\", Cpu::cpu_sensor);\n\t\t\treturn;\n\t\t}\n\n\t\tprop_object_iterator_t fields_iter = prop_array_iterator(prop_array_t(fields_array));\n\t\tif (fields_iter == NULL) {\n\t\t\treturn;\n\t\t}\n\n\t\tregex_t r;\n\t\tif (regcomp(&r, \"(cpu[0-9]* )*temperature\", REG_EXTENDED)) {\n\t\t\tLogger::warning(\"regcomp() failed\");\n\t\t\treturn;\n\t\t}\n\n\t\tstring prop_description = \"no description\";\n\t\tchar buf[64];\n\t\twhile ((fields = (prop_dictionary_t) prop_object_iterator_next(prop_object_iterator_t(fields_iter))) != NULL) {\n\t\t\tprops = (prop_dictionary_t) prop_dictionary_get(fields, \"device-properties\");\n\t\t\tif (props != NULL) continue;\n\n\t\t\tprop_object_t cur_value = prop_dictionary_get(fields, \"cur-value\");\n\t\t\tprop_object_t max_value = prop_dictionary_get(fields, \"critical-max\");\n\t\t\tprop_object_t description = prop_dictionary_get(fields, \"description\");\n\n\t\t\tif (description == NULL || cur_value == NULL) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\n\t\t\tprop_string_copy_value(prop_string_t(description), buf, sizeof buf);\n\t\t\tprop_description = buf;\n\n\t\t\tif (regexec(&r, prop_description.c_str(), 0, NULL, 0) == 0) {\n\t\t\t\tcurrent_temp = prop_number_signed_value(prop_number_t(cur_value));\n\t\t\t\tif (max_value != NULL) {\n\t\t\t\t\tcurrent_cpu.temp_max = MUKTOC(prop_number_signed_value(prop_number_t(max_value)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tregfree(&r);\n\n\t\tprop_object_iterator_release(fields_iter);\n\t\tprop_object_release(dict);\n\n\t\tif (current_temp > -1) {\n\t\t\tcurrent_temp = MUKTOC(current_temp);\n\t\t\tfor (int i = 0; i < Shared::coreCount; i++) {\n\t\t\t\tif (cmp_less(i + 1, current_cpu.temp.size())) {\n\t\t\t\t\tcurrent_cpu.temp.at(i + 1).push_back(current_temp);\n\t\t\t\t\tif (current_cpu.temp.at(i + 1).size() > 20) {\n\t\t\t\t\t\tcurrent_cpu.temp.at(i + 1).pop_front();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurrent_cpu.temp.at(0).push_back(current_temp);\n\t\t\tif (current_cpu.temp.at(0).size() > 20) {\n\t\t\t\tcurrent_cpu.temp.at(0).pop_front();\n\t\t\t}\n\t\t}\n\n\t}\n\n\tstring get_cpuHz() {\n\t\tunsigned int freq = 1;\n\t\tsize_t size = sizeof(freq);\n\n\t\tif (sysctlbyname(\"hw.cpuspeed\", &freq, &size, nullptr, 0) < 0) {\n\t\t\treturn \"\";\n\t\t}\n\t\treturn std::to_string(freq / 1000.0 ).substr(0, 3); // seems to be in MHz\n\t}\n\n\tauto get_core_mapping() -> std::unordered_map<int, int> {\n\t\tstd::unordered_map<int, int> core_map;\n\t\tif (cpu_temp_only) return core_map;\n\n\t\tfor (long i = 0; i < Shared::coreCount; i++) {\n\t\t\tcore_map[i] = i;\n\t\t}\n\n\t\t//? If core mapping from cpuinfo was incomplete try to guess remainder, if missing completely, map 0-0 1-1 2-2 etc.\n\t\tif (cmp_less(core_map.size(), Shared::coreCount)) {\n\t\t\tif (Shared::coreCount % 2 == 0 and (long) core_map.size() == Shared::coreCount / 2) {\n\t\t\t\tfor (int i = 0, n = 0; i < Shared::coreCount / 2; i++) {\n\t\t\t\t\tif (std::cmp_greater_equal(n, core_sensors.size())) n = 0;\n\t\t\t\t\tcore_map[Shared::coreCount / 2 + i] = n++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcore_map.clear();\n\t\t\t\tfor (int i = 0, n = 0; i < Shared::coreCount; i++) {\n\t\t\t\t\tif (std::cmp_greater_equal(n, core_sensors.size())) n = 0;\n\t\t\t\t\tcore_map[i] = n++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//? Apply user set custom mapping if any\n\t\tconst auto &custom_map = Config::getS(\"cpu_core_map\");\n\t\tif (not custom_map.empty()) {\n\t\t\ttry {\n\t\t\t\tfor (const auto &split : ssplit(custom_map)) {\n\t\t\t\t\tconst auto vals = ssplit(split, ':');\n\t\t\t\t\tif (vals.size() != 2) continue;\n\t\t\t\t\tint change_id = std::stoi(vals.at(0));\n\t\t\t\t\tint new_id = std::stoi(vals.at(1));\n\t\t\t\t\tif (not core_map.contains(change_id) or cmp_greater(new_id, core_sensors.size())) continue;\n\t\t\t\t\tcore_map.at(change_id) = new_id;\n\t\t\t\t}\n\t\t\t} catch (...) {\n\t\t\t}\n\t\t}\n\n\t\treturn core_map;\n\t}\n\n\tauto get_battery() -> tuple<int, float, long, string> {\n\t\tif (not has_battery) return {0, 0.0, 0, \"\"};\n\n\t\tprop_dictionary_t dict, fields, props;\n\n\t\tint64_t total_charge = 0;\n\t\tint64_t total_capacity = 0;\n\n\t\tint fd = open(_PATH_SYSMON, O_RDONLY);\n\t\tif (fd == -1) {\n\t\t\tLogger::warning(\"failed to open {}\", _PATH_SYSMON);\n\t\t\thas_battery = false;\n\t\t\treturn {0, 0.0, 0, \"\"};\n\t\t}\n\n\t\tif (prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict) != 0) {\n\t\t\tif (fd != -1) {\n\t\t\t\tclose(fd);\n\t\t\t}\n\t\t\thas_battery = false;\n\t\t\tLogger::warning(\"failed to open envsys dict\");\n\t\t\treturn {0, 0.0, 0, \"\"};\n\t\t}\n\n\t\tclose(fd);\n\n\t\tif (prop_dictionary_count(dict) == 0) {\n\t\t\thas_battery = false;\n\t\t\tLogger::warning(\"no drivers registered for envsys\");\n\t\t\treturn {0, 0.0, 0, \"\"};\n\t\t}\n\n\t\tprop_object_t fields_array = prop_dictionary_get(prop_dictionary_t(dict), \"acpibat0\");\n\t\tif (prop_object_type(fields_array) != PROP_TYPE_ARRAY) {\n\t\t\thas_battery = false;\n\t\t\tLogger::warning(\"unknown device 'acpibat0'\");\n\t\t\treturn {0, 0.0, 0, \"\"};\n\t\t}\n\n\t\tprop_object_iterator_t fields_iter = prop_array_iterator(prop_array_t(fields_array));\n\t\tif (fields_iter == NULL) {\n\t\t\thas_battery = false;\n\t\t\treturn {0, 0.0, 0, \"\"};\n\t\t}\n\n\t\t/* only assume battery is not present if explicitly stated */\n\t\tbool is_battery = false;\n\t\tint64_t is_present = 1;\n\t\tint64_t cur_charge = 0;\n\t\tint64_t max_charge = 0;\n\t\tstring status = \"unknown\";\n\t\tstring prop_description = \"no description\";\n\t\tchar buf[64];\n\n\t\twhile ((fields = (prop_dictionary_t) prop_object_iterator_next(prop_object_iterator_t(fields_iter))) != NULL) {\n\t\t\tprops = (prop_dictionary_t) prop_dictionary_get(fields, \"device-properties\");\n\t\t\tif (props != NULL) continue;\n\n\t\t\tprop_object_t cur_value = prop_dictionary_get(fields, \"cur-value\");\n\t\t\tprop_object_t max_value = prop_dictionary_get(fields, \"max-value\");\n\t\t\tprop_object_t description = prop_dictionary_get(fields, \"description\");\n\n\t\t\tif (description == NULL || cur_value == NULL) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\n\t\t\tprop_string_copy_value(prop_string_t(description), buf, sizeof buf);\n\t\t\tprop_description = buf;\n\n\t\t\tif (prop_description == \"charge\") {\n\t\t\t\tif (max_value == NULL) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tcur_charge = prop_number_signed_value(prop_number_t(cur_value));\n\t\t\t\tmax_charge = prop_number_signed_value(prop_number_t(max_value));\n\t\t\t}\n\n\t\t\tif (prop_description == \"present\") {\n\t\t\t\tis_present = prop_number_signed_value(prop_number_t(cur_value));\n\t\t\t}\n\n\t\t\tif (prop_description == \"charging\") {\n\t\t\t\tstatus = prop_description;\n\t\t\t\tchar buf[64];\n\t\t\t\tprop_string_copy_value(prop_string_t(prop_dictionary_get(fields, \"type\")), buf, sizeof buf);\n\t\t\t\tstring charging_type = buf;\n\t\t\t\tis_battery = charging_type == \"Battery charge\" ? true : false;\n\t\t\t}\n\n\t\t\tif (is_battery && is_present) {\n\t\t\t\ttotal_charge += cur_charge;\n\t\t\t\ttotal_capacity += max_charge;\n\t\t\t}\n\t\t}\n\n\t\tprop_object_iterator_release(fields_iter);\n\t\tprop_object_release(dict);\n\n\t\tuint32_t percent = ((double)total_charge / (double)total_capacity) * 100.0;\n\n\t\tif (percent == 100) {\n\t\t\tstatus = \"full\";\n\t\t}\n\n\t\treturn {percent, -1, -1, status};\n\t}\n\n\tauto collect(bool no_update) -> cpu_info & {\n\t\tif (Runner::stopping or (no_update and not current_cpu.cpu_percent.at(\"total\").empty()))\n\t\t\treturn current_cpu;\n\t\tauto &cpu = current_cpu;\n\n\t\tif (getloadavg(cpu.load_avg.data(), cpu.load_avg.size()) < 0) {\n\t\t\tLogger::error(\"failed to get load averages\");\n\t\t}\n\n\t\tvector<array<long, CPUSTATES>> cpu_time(Shared::coreCount);\n\t\tsize_t size = sizeof(long) * CPUSTATES * Shared::coreCount;\n\t\tif (sysctlbyname(\"kern.cp_time\", &cpu_time[0], &size, nullptr, 0) == -1) {\n\t\t\tLogger::error(\"failed to get CPU time\");\n\t\t}\n\t\tlong long global_totals = 0;\n\t\tlong long global_idles = 0;\n\t\tvector<long long> times_summed = {0, 0, 0, 0};\n\n\t\tfor (long i = 0; i < Shared::coreCount; i++) {\n\t\t\tvector<long long> times;\n\t\t\t//? 0=user, 1=nice, 2=system, 3=idle\n\t\t\tfor (int x = 0; const unsigned int c_state : {CP_USER, CP_NICE, CP_SYS, CP_IDLE}) {\n\t\t\t\tauto val = cpu_time[i][c_state];\n\t\t\t\ttimes.push_back(val);\n\t\t\t\ttimes_summed.at(x++) += val;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\t//? All values\n\t\t\t\tconst long long totals = std::accumulate(times.begin(), times.end(), 0ll);\n\n\t\t\t\t//? Idle time\n\t\t\t\tconst long long idles = times.at(3);\n\n\t\t\t\tglobal_totals += totals;\n\t\t\t\tglobal_idles += idles;\n\n\t\t\t\t//? Calculate cpu total for each core\n\t\t\t\tif (i > Shared::coreCount) break;\n\t\t\t\tconst long long calc_totals = max(0ll, totals - core_old_totals.at(i));\n\t\t\t\tconst long long calc_idles = max(0ll, idles - core_old_idles.at(i));\n\t\t\t\tcore_old_totals.at(i) = totals;\n\t\t\t\tcore_old_idles.at(i) = idles;\n\n\t\t\t\tcpu.core_percent.at(i).push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));\n\n\t\t\t\t//? Reduce size if there are more values than needed for graph\n\t\t\t\tif (cpu.core_percent.at(i).size() > 40) cpu.core_percent.at(i).pop_front();\n\n\t\t\t} catch (const std::exception& e) {\n\t\t\t\tLogger::error(\"Cpu::collect() : {}\", e.what());\n\t\t\t\tthrow std::runtime_error(fmt::format(\"collect() : {}\", e.what()));\n\t\t\t}\n\n\t\t}\n\n\t\tconst long long calc_totals = max(1ll, global_totals - cpu_old.at(\"totals\"));\n\t\tconst long long calc_idles = max(1ll, global_idles - cpu_old.at(\"idles\"));\n\n\t\t//? Populate cpu.cpu_percent with all fields from syscall\n\t\tfor (int ii = 0; const auto &val : times_summed) {\n\t\t\tcpu.cpu_percent.at(time_names.at(ii)).push_back(clamp((long long)round((double)(val - cpu_old.at(time_names.at(ii))) * 100 / calc_totals), 0ll, 100ll));\n\t\t\tcpu_old.at(time_names.at(ii)) = val;\n\n\t\t\t//? Reduce size if there are more values than needed for graph\n\t\t\twhile (cmp_greater(cpu.cpu_percent.at(time_names.at(ii)).size(), width * 2)) cpu.cpu_percent.at(time_names.at(ii)).pop_front();\n\n\t\t\tii++;\n\t\t}\n\n\t\tcpu_old.at(\"totals\") = global_totals;\n\t\tcpu_old.at(\"idles\") = global_idles;\n\n\t\t//? Total usage of cpu\n\t\tcpu.cpu_percent.at(\"total\").push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));\n\n\t\t//? Reduce size if there are more values than needed for graph\n\t\twhile (cmp_greater(cpu.cpu_percent.at(\"total\").size(), width * 2)) cpu.cpu_percent.at(\"total\").pop_front();\n\n\t\tif (Config::getB(\"show_cpu_freq\")) {\n\t\t\tauto hz = get_cpuHz();\n\t\t\tif (hz != \"\") {\n\t\t\t\tcpuHz = hz;\n\t\t\t}\n\t\t}\n\n\t\tif (Config::getB(\"check_temp\") and got_sensors)\n\t\t\tupdate_sensors();\n\n\t\tif (Config::getB(\"show_battery\") and has_battery)\n\t\t\tcurrent_bat = get_battery();\n\n\t\treturn current_cpu;\n\t}\n} // namespace Cpu\n\nnamespace Mem {\n\tbool has_swap = false;\n\tvector<string> fstab;\n\tfs::file_time_type fstab_time;\n\tint disk_ios = 0;\n\tvector<string> last_found;\n\n\tmem_info current_mem{};\n\n\tuint64_t get_totalMem() {\n\t\treturn Shared::totalMem;\n\t}\n\n\tvoid assign_values(struct disk_info& disk, int64_t readBytes, int64_t writeBytes) {\n\t\tdisk_ios++;\n\t\tif (disk.io_read.empty()) {\n\t\t\tdisk.io_read.push_back(0);\n\t\t} else {\n\t\t\tdisk.io_read.push_back(max((int64_t)0, (readBytes - disk.old_io.at(0))));\n\t\t}\n\t\tdisk.old_io.at(0) = readBytes;\n\t\twhile (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front();\n\n\t\tif (disk.io_write.empty()) {\n\t\t\tdisk.io_write.push_back(0);\n\t\t} else {\n\t\t\tdisk.io_write.push_back(max((int64_t)0, (writeBytes - disk.old_io.at(1))));\n\t\t}\n\t\tdisk.old_io.at(1) = writeBytes;\n\t\twhile (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front();\n\n\t\t// no io times - need to push something anyway or we'll get an ABORT\n\t\tif (disk.io_activity.empty())\n\t\t\tdisk.io_activity.push_back(0);\n\t\telse\n\t\t\tdisk.io_activity.push_back(clamp((long)round((double)(disk.io_write.back() + disk.io_read.back()) / (1 << 20)), 0l, 100l));\n\t\twhile (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();\n\t}\n\n\tvoid collect_disk(std::unordered_map<string, disk_info> &disks, std::unordered_map<string, string> &mapping) {\n\t\tuint64_t total_bytes_read = 0;\n\t\tuint64_t total_bytes_write = 0;\n\n\t\tint num_drives = 0;\n\t\tint mib[3] = { CTL_HW, HW_IOSTATS, sizeof(struct io_sysctl)};\n\n\t\tsize_t size;\n\t\tif (sysctl(mib, 3, NULL, &size, NULL, 0) == -1) {\n\t\t\tLogger::error(\"sysctl hw.drivestats failed\");\n\t\t\treturn;\n\t\t}\n\t\tnum_drives = size / sizeof(struct io_sysctl);\n\n\t\tauto drives = std::unique_ptr<struct io_sysctl[], void(*)(void*)> {\n\t\t\treinterpret_cast<struct io_sysctl*>(malloc(size)),\n\t\t\tfree\n\t\t};\n\n\t\tif (sysctl(mib, 3, drives.get(), &size, NULL, 0) == -1) {\n\t\t\tLogger::error(\"sysctl hw.iostats failed\");\n\t\t}\n\t\tfor (int i = 0; i < num_drives; i++) {\n\t\t\tfor (auto& [ignored, disk] : disks) {\n\t\t\t\tif (disk.dev.string().find(drives[i].name) != string::npos) {\n\t\t\t\t\tstring mountpoint = mapping.at(disk.dev);\n\t\t\t\t\ttotal_bytes_read = drives[i].rbytes;\n\t\t\t\t\ttotal_bytes_write = drives[i].wbytes;\n\t\t\t\t\tassign_values(disk, total_bytes_read, total_bytes_write);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\tauto collect(bool no_update) -> mem_info & {\n\t\tif (Runner::stopping or (no_update and not current_mem.percent.at(\"used\").empty()))\n\t\t\treturn current_mem;\n\n\t\tauto show_swap = Config::getB(\"show_swap\");\n\t\tauto show_disks = Config::getB(\"show_disks\");\n\t\tauto swap_disk = Config::getB(\"swap_disk\");\n\t\tauto &mem = current_mem;\n\t\tstatic bool snapped = (getenv(\"BTOP_SNAPPED\") != nullptr);\n\n\t\tuint64_t memActive, memWired, memCached, memFree;\n\t\tsize_t size;\n\n\t\tstatic int uvmexp_mib[] = {CTL_VM, VM_UVMEXP2};\n\t\tstruct uvmexp_sysctl uvmexp;\n\t\tsize = sizeof(uvmexp);\n\t\tif (sysctl(uvmexp_mib, 2, &uvmexp, &size, NULL, 0) == -1) {\n\t\t\tLogger::error(\"uvmexp sysctl failed\");\n\t\t\tbzero(&uvmexp, sizeof(uvmexp));\n\t\t}\n\n\t\tmemActive = uvmexp.active * Shared::pageSize;\n\t\tmemWired = uvmexp.wired * Shared::pageSize;\n\t\tmemFree = uvmexp.free * Shared::pageSize;\n\t\tmemCached = (uvmexp.filepages + uvmexp.execpages + uvmexp.anonpages) * Shared::pageSize;\n\t\tmem.stats.at(\"used\") = memActive + memWired;\n\t\tmem.stats.at(\"available\") = Shared::totalMem - (memActive + memWired);\n\t\tmem.stats.at(\"cached\") = memCached;\n\t\tmem.stats.at(\"free\") = memFree;\n\n\t\tif (show_swap) {\n\t\t\tmem.stats.at(\"swap_total\") = uvmexp.swpages * Shared::pageSize;\n\t\t\tmem.stats.at(\"swap_used\") = uvmexp.swpginuse * Shared::pageSize;\n\t\t\tmem.stats.at(\"swap_free\") = (uvmexp.swpages - uvmexp.swpginuse) * Shared::pageSize;\n\t\t}\n\n\t\tif (show_swap and mem.stats.at(\"swap_total\") > 0) {\n\t\t\tfor (const auto &name : swap_names) {\n\t\t\t\tmem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / mem.stats.at(\"swap_total\")));\n\t\t\t\twhile (cmp_greater(mem.percent.at(name).size(), width * 2))\n\t\t\t\t\tmem.percent.at(name).pop_front();\n\t\t\t}\n\t\t\thas_swap = true;\n\t\t} else\n\t\t\thas_swap = false;\n\t\t//? Calculate percentages\n\t\tfor (const auto &name : mem_names) {\n\t\t\tmem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / Shared::totalMem));\n\t\t\twhile (cmp_greater(mem.percent.at(name).size(), width * 2))\n\t\t\t\tmem.percent.at(name).pop_front();\n\t\t}\n\n\t\tif (show_disks) {\n\t\t\tstd::unordered_map<string, string> mapping;  // keep mapping from device -> mountpoint, since IOKit doesn't give us the mountpoint\n\t\t\tdouble uptime = system_uptime();\n\t\t\tauto &disks_filter = Config::getS(\"disks_filter\");\n\t\t\tbool filter_exclude = false;\n\t\t\t// auto only_physical = Config::getB(\"only_physical\");\n\t\t\tauto &disks = mem.disks;\n\t\t\tvector<string> filter;\n\t\t\tif (not disks_filter.empty()) {\n\t\t\t\tfilter = ssplit(disks_filter);\n\t\t\t\tif (filter.at(0).starts_with(\"exclude=\")) {\n\t\t\t\t\tfilter_exclude = true;\n\t\t\t\t\tfilter.at(0) = filter.at(0).substr(8);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstruct statvfs *stvfs;\n\t\t\tint count = getmntinfo(&stvfs, MNT_WAIT);\n\t\t\tvector<string> found;\n\t\t\tfound.reserve(last_found.size());\n\t\t\tfor (int i = 0; i < count; i++) {\n\t\t\t\tauto fstype = string(stvfs[i].f_fstypename);\n\t\t\t\tif (fstype == \"autofs\" || fstype == \"devfs\" || fstype == \"linprocfs\" || fstype == \"procfs\" || fstype == \"tmpfs\" || fstype == \"linsysfs\" ||\n\t\t\t\t\tfstype == \"fdesckfs\") {\n\t\t\t\t\t// in memory filesystems -> not useful to show\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tstd::error_code ec;\n\t\t\t\tstring mountpoint = stvfs[i].f_mntonname;\n\t\t\t\tstring dev = stvfs[i].f_mntfromname;\n\t\t\t\tmapping[dev] = mountpoint;\n\n\t\t\t\t//? Match filter if not empty\n\t\t\t\tif (not filter.empty()) {\n\t\t\t\t\tbool match = v_contains(filter, mountpoint);\n\t\t\t\t\tif ((filter_exclude and match) or (not filter_exclude and not match))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfound.push_back(mountpoint);\n\t\t\t\tif (not disks.contains(mountpoint)) {\n\t\t\t\t\tdisks[mountpoint] = disk_info{fs::canonical(dev, ec), fs::path(mountpoint).filename()};\n\n\t\t\t\t\tif (disks.at(mountpoint).dev.empty())\n\t\t\t\t\t\tdisks.at(mountpoint).dev = dev;\n\n\t\t\t\t\tif (disks.at(mountpoint).name.empty())\n\t\t\t\t\t\tdisks.at(mountpoint).name = (mountpoint == \"/\" ? \"root\" : mountpoint);\n\t\t\t\t}\n\n\n\t\t\t\tif (not v_contains(last_found, mountpoint))\n\t\t\t\t\tredraw = true;\n\n\t\t\t\tdisks.at(mountpoint).free = stvfs[i].f_bfree;\n\t\t\t\tdisks.at(mountpoint).total = stvfs[i].f_iosize;\n\t\t\t}\n\n\t\t\t//? Remove disks no longer mounted or filtered out\n\t\t\tif (swap_disk and has_swap) found.push_back(\"swap\");\n\t\t\tfor (auto it = disks.begin(); it != disks.end();) {\n\t\t\t\tif (not v_contains(found, it->first))\n\t\t\t\t\tit = disks.erase(it);\n\t\t\t\telse\n\t\t\t\t\tit++;\n\t\t\t}\n\t\t\tif (found.size() != last_found.size()) redraw = true;\n\t\t\tlast_found = std::move(found);\n\n\t\t\t//? Get disk/partition stats\n\t\t\tfor (auto &[mountpoint, disk] : disks) {\n\t\t\t\tif (std::error_code ec; not fs::exists(mountpoint, ec))\n\t\t\t\t\tcontinue;\n\t\t\t\tstruct statvfs vfs;\n\t\t\t\tif (statvfs(mountpoint.c_str(), &vfs) < 0) {\n\t\t\t\t\tLogger::warning(\"Failed to get disk/partition stats with statvfs() for: {}\", mountpoint);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tdisk.total = vfs.f_blocks * vfs.f_frsize;\n\t\t\t\tdisk.free = vfs.f_bfree * vfs.f_frsize;\n\t\t\t\tdisk.used = disk.total - disk.free;\n\t\t\t\tif (disk.total != 0) {\n\t\t\t\t\tdisk.used_percent = round((double)disk.used * 100 / disk.total);\n\t\t\t\t\tdisk.free_percent = 100 - disk.used_percent;\n\t\t\t\t} else {\n\t\t\t\t\tdisk.used_percent = 0;\n\t\t\t\t\tdisk.free_percent = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Setup disks order in UI and add swap if enabled\n\t\t\tmem.disks_order.clear();\n\t\t\tif (snapped and disks.contains(\"/mnt\"))\n\t\t\t\tmem.disks_order.push_back(\"/mnt\");\n\t\t\telse if (disks.contains(\"/\"))\n\t\t\t\tmem.disks_order.push_back(\"/\");\n\t\t\tif (swap_disk and has_swap) {\n\t\t\t\tmem.disks_order.push_back(\"swap\");\n\t\t\t\tif (not disks.contains(\"swap\"))\n\t\t\t\t\tdisks[\"swap\"] = {\"\", \"swap\"};\n\t\t\t\tdisks.at(\"swap\").total = mem.stats.at(\"swap_total\");\n\t\t\t\tdisks.at(\"swap\").used = mem.stats.at(\"swap_used\");\n\t\t\t\tdisks.at(\"swap\").free = mem.stats.at(\"swap_free\");\n\t\t\t\tdisks.at(\"swap\").used_percent = mem.percent.at(\"swap_used\").back();\n\t\t\t\tdisks.at(\"swap\").free_percent = mem.percent.at(\"swap_free\").back();\n\t\t\t}\n\t\t\tfor (const auto &name : last_found)\n\t\t\t\tif (not is_in(name, \"/\", \"swap\", \"/dev\"))\n\t\t\t\t\tmem.disks_order.push_back(name);\n\n\t\t\tdisk_ios = 0;\n\t\t\tcollect_disk(disks, mapping);\n\n\t\t\told_uptime = uptime;\n\t\t}\n\t\treturn mem;\n\t}\n\n}  // namespace Mem\n\nnamespace Net {\n\tstd::unordered_map<string, net_info> current_net;\n\tnet_info empty_net = {};\n\tvector<string> interfaces;\n\tstring selected_iface;\n\tint errors = 0;\n\tstd::unordered_map<string, uint64_t> graph_max = {{\"download\", {}}, {\"upload\", {}}};\n\tstd::unordered_map<string, array<int, 2>> max_count = {{\"download\", {}}, {\"upload\", {}}};\n\tbool rescale = true;\n\tuint64_t timestamp = 0;\n\n\tauto collect(bool no_update) -> net_info & {\n\t\tauto &net = current_net;\n\t\tauto &config_iface = Config::getS(\"net_iface\");\n\t\tauto net_sync = Config::getB(\"net_sync\");\n\t\tauto net_auto = Config::getB(\"net_auto\");\n\t\tauto new_timestamp = time_ms();\n\n\t\tif (not no_update and errors < 3) {\n\t\t\t//? Get interface list using getifaddrs() wrapper\n\t\t\tIfAddrsPtr if_addrs {};\n\t\t\tif (if_addrs.get_status() != 0) {\n\t\t\t\terrors++;\n\t\t\t\tLogger::error(\"Net::collect() -> getifaddrs() failed with id {}\", if_addrs.get_status());\n\t\t\t\tredraw = true;\n\t\t\t\treturn empty_net;\n\t\t\t}\n\t\t\tint family = 0;\n\t\t\tstatic_assert(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN); // 46 >= 16, compile-time assurance.\n\t\t\tenum { IPBUFFER_MAXSIZE = INET6_ADDRSTRLEN }; // manually using the known biggest value, guarded by the above static_assert\n\t\t\tchar ip[IPBUFFER_MAXSIZE];\n\t\t\tinterfaces.clear();\n\t\t\tstring ipv4, ipv6;\n\n\t\t\t//? Iteration over all items in getifaddrs() list\n\t\t\tfor (auto *ifa = if_addrs.get(); ifa != nullptr; ifa = ifa->ifa_next) {\n\t\t\t\tif (ifa->ifa_addr == nullptr) continue;\n\t\t\t\tfamily = ifa->ifa_addr->sa_family;\n\t\t\t\tconst auto &iface = ifa->ifa_name;\n\t\t\t\t//? Update available interfaces vector and get status of interface\n\t\t\t\tif (not v_contains(interfaces, iface)) {\n\t\t\t\t\tinterfaces.push_back(iface);\n\t\t\t\t\tnet[iface].connected = (ifa->ifa_flags & IFF_RUNNING);\n\n\t\t\t\t\t// An interface can have more than one IP of the same family associated with it,\n\t\t\t\t\t// but we pick only the first one to show in the NET box.\n\t\t\t\t\t// Note: Interfaces without any IPv4 and IPv6 set are still valid and monitorable!\n\t\t\t\t\tnet[iface].ipv4.clear();\n\t\t\t\t\tnet[iface].ipv6.clear();\n\t\t\t\t}\n\t\t\t\t//? Get IPv4 address\n\t\t\t\tif (family == AF_INET) {\n\t\t\t\t\tif (net[iface].ipv4.empty()) {\n\t\t\t\t\t\tif (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr)->sin_addr), ip, IPBUFFER_MAXSIZE)) {\n\n\t\t\t\t\t\t\tnet[iface].ipv4 = ip;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tint errsv = errno;\n\t\t\t\t\t\t\tLogger::error(\"Net::collect() -> Failed to convert IPv4 to string for iface {}, errno: {}\", iface, strerror(errsv));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? Get IPv6 address\n\t\t\t\telse if (family == AF_INET6) {\n\t\t\t\t\tif (net[iface].ipv6.empty()) {\n\t\t\t\t\t\tif (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr)->sin6_addr), ip, IPBUFFER_MAXSIZE)) {\n\t\t\t\t\t\t\tnet[iface].ipv6 = ip;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tint errsv = errno;\n\t\t\t\t\t\t\tLogger::error(\"Net::collect() -> Failed to convert IPv6 to string for iface {}, errno: {}\", iface, strerror(errsv));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}  //else, ignoring family==AF_LINK (see man 3 getifaddrs)\n\t\t\t}\n\n\t\t\tstd::unordered_map<string, std::tuple<uint64_t, uint64_t>> ifstats;\n\t\t\tint mib[] = {CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, 0};\n\t\t\tsize_t len;\n\t\t\tif (sysctl(mib, 6, nullptr, &len, nullptr, 0) < 0) {\n\t\t\t\tLogger::error(\"failed getting network interfaces\");\n\t\t\t} else {\n\t\t\t\tstd::unique_ptr<char[]> buf(new char[len]);\n\t\t\t\tif (sysctl(mib, 6, buf.get(), &len, nullptr, 0) < 0) {\n\t\t\t\t\tLogger::error(\"failed getting network interfaces\");\n\t\t\t\t} else {\n\t\t\t\t\tchar *lim = buf.get() + len;\n\t\t\t\t\tchar *next = nullptr;\n\t\t\t\t\tfor (next = buf.get(); next < lim;) {\n\t\t\t\t\t\tstruct if_msghdr *ifm = (struct if_msghdr *)next;\n\t\t\t\t\t\tnext += ifm->ifm_msglen;\n\t\t\t\t\t\tstruct if_data ifm_data = ifm->ifm_data;\n\t\t\t\t\t\tif (ifm->ifm_addrs & RTA_IFP) {\n\t\t\t\t\t\t\tstruct sockaddr_dl *sdl = (struct sockaddr_dl *)(ifm + 1);\n\t\t\t\t\t\t\tchar iface[32];\n\t\t\t\t\t\t\tstrncpy(iface, sdl->sdl_data, sdl->sdl_nlen);\n\t\t\t\t\t\t\tiface[sdl->sdl_nlen] = 0;\n\t\t\t\t\t\t\tifstats[iface] = std::tuple(ifm_data.ifi_ibytes, ifm_data.ifi_obytes);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Get total received and transmitted bytes + device address if no ip was found\n\t\t\tfor (const auto &iface : interfaces) {\n\t\t\t\tfor (const string dir : {\"download\", \"upload\"}) {\n\t\t\t\t\tauto &saved_stat = net.at(iface).stat.at(dir);\n\t\t\t\t\tauto &bandwidth = net.at(iface).bandwidth.at(dir);\n\t\t\t\t\tuint64_t val = dir == \"download\" ? std::get<0>(ifstats[iface]) : std::get<1>(ifstats[iface]);\n\n\t\t\t\t\t//? Update speed, total and top values\n\t\t\t\t\tif (val < saved_stat.last) {\n\t\t\t\t\t\tsaved_stat.rollover += saved_stat.last;\n\t\t\t\t\t\tsaved_stat.last = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (cmp_greater((unsigned long long)saved_stat.rollover + (unsigned long long)val, numeric_limits<uint64_t>::max())) {\n\t\t\t\t\t\tsaved_stat.rollover = 0;\n\t\t\t\t\t\tsaved_stat.last = 0;\n\t\t\t\t\t}\n\t\t\t\t\tsaved_stat.speed = round((double)(val - saved_stat.last) / ((double)(new_timestamp - timestamp) / 1000));\n\t\t\t\t\tif (saved_stat.speed > saved_stat.top) saved_stat.top = saved_stat.speed;\n\t\t\t\t\tif (saved_stat.offset > val + saved_stat.rollover) saved_stat.offset = 0;\n\t\t\t\t\tsaved_stat.total = (val + saved_stat.rollover) - saved_stat.offset;\n\t\t\t\t\tsaved_stat.last = val;\n\n\t\t\t\t\t//? Add values to graph\n\t\t\t\t\tbandwidth.push_back(saved_stat.speed);\n\t\t\t\t\twhile (cmp_greater(bandwidth.size(), width * 2)) bandwidth.pop_front();\n\n\t\t\t\t\t//? Set counters for auto scaling\n\t\t\t\t\tif (net_auto and selected_iface == iface) {\n\t\t\t\t\t\tif (saved_stat.speed > graph_max[dir]) {\n\t\t\t\t\t\t\t++max_count[dir][0];\n\t\t\t\t\t\t\tif (max_count[dir][1] > 0) --max_count[dir][1];\n\t\t\t\t\t\t} else if (graph_max[dir] > 10 << 10 and saved_stat.speed < graph_max[dir] / 10) {\n\t\t\t\t\t\t\t++max_count[dir][1];\n\t\t\t\t\t\t\tif (max_count[dir][0] > 0) --max_count[dir][0];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Clean up net map if needed\n\t\t\tif (net.size() > interfaces.size()) {\n\t\t\t\tfor (auto it = net.begin(); it != net.end();) {\n\t\t\t\t\tif (not v_contains(interfaces, it->first))\n\t\t\t\t\t\tit = net.erase(it);\n\t\t\t\t\telse\n\t\t\t\t\t\tit++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttimestamp = new_timestamp;\n\t\t}\n\t\t//? Return empty net_info struct if no interfaces was found\n\t\tif (net.empty())\n\t\t\treturn empty_net;\n\n\t\t//? Find an interface to display if selected isn't set or valid\n\t\tif (selected_iface.empty() or not v_contains(interfaces, selected_iface)) {\n\t\t\tmax_count[\"download\"][0] = max_count[\"download\"][1] = max_count[\"upload\"][0] = max_count[\"upload\"][1] = 0;\n\t\t\tredraw = true;\n\t\t\tif (net_auto) rescale = true;\n\t\t\tif (not config_iface.empty() and v_contains(interfaces, config_iface))\n\t\t\t\tselected_iface = config_iface;\n\t\t\telse {\n\t\t\t\t//? Sort interfaces by total upload + download bytes\n\t\t\t\tauto sorted_interfaces = interfaces;\n\t\t\t\trng::sort(sorted_interfaces, [&](const auto &a, const auto &b) {\n\t\t\t\t\treturn cmp_greater(net.at(a).stat[\"download\"].total + net.at(a).stat[\"upload\"].total,\n\t\t\t\t\t\t\t\t\t   net.at(b).stat[\"download\"].total + net.at(b).stat[\"upload\"].total);\n\t\t\t\t});\n\t\t\t\tselected_iface.clear();\n\t\t\t\t//? Try to set to a connected interface\n\t\t\t\tfor (const auto &iface : sorted_interfaces) {\n\t\t\t\t\tif (net.at(iface).connected) selected_iface = iface;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t//? If no interface is connected set to first available\n\t\t\t\tif (selected_iface.empty() and not sorted_interfaces.empty())\n\t\t\t\t\tselected_iface = sorted_interfaces.at(0);\n\t\t\t\telse if (sorted_interfaces.empty())\n\t\t\t\t\treturn empty_net;\n\t\t\t}\n\t\t}\n\n\t\t//? Calculate max scale for graphs if needed\n\t\tif (net_auto) {\n\t\t\tbool sync = false;\n\t\t\tfor (const auto &dir : {\"download\", \"upload\"}) {\n\t\t\t\tfor (const auto &sel : {0, 1}) {\n\t\t\t\t\tif (rescale or max_count[dir][sel] >= 5) {\n\t\t\t\t\t\tconst long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: net[selected_iface].stat[dir].speed);\n\t\t\t\t\t\tgraph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10);\n\t\t\t\t\t\tmax_count[dir][0] = max_count[dir][1] = 0;\n\t\t\t\t\t\tredraw = true;\n\t\t\t\t\t\tif (net_sync) sync = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? Sync download/upload graphs if enabled\n\t\t\t\tif (sync) {\n\t\t\t\t\tconst auto other = (string(dir) == \"upload\" ? \"download\" : \"upload\");\n\t\t\t\t\tgraph_max[other] = graph_max[dir];\n\t\t\t\t\tmax_count[other][0] = max_count[other][1] = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trescale = false;\n\t\treturn net.at(selected_iface);\n\t}\n}  // namespace Net\n\nnamespace Proc {\n\n\tvector<proc_info> current_procs;\n\tstd::unordered_map<string, string> uid_user;\n\tstring current_sort;\n\tstring current_filter;\n\tbool current_rev = false;\n\tbool is_tree_mode;\n\n\tfs::file_time_type passwd_time;\n\n\tuint64_t cputimes;\n\tint collapse = -1, expand = -1, toggle_children = -1;\n\tuint64_t old_cputimes = 0;\n\tatomic<int> numpids = 0;\n\tint filter_found = 0;\n\n\tdetail_container detailed;\n\tstatic std::unordered_set<size_t> dead_procs;\n\n\tstring get_status(char s) {\n\t\tif (s & LSRUN) return \"Running\";\n\t\tif (s & LSSLEEP) return \"Sleeping\";\n\t\tif (s & SIDL) return \"Idle\";\n\t\tif (s & SSTOP) return \"Stopped\";\n\t\tif (s & SZOMB) return \"Zombie\";\n\t\treturn \"Unknown\";\n\t}\n\n\t//* Get detailed info for selected process\n\tvoid _collect_details(const size_t pid, vector<proc_info> &procs) {\n\t\tif (pid != detailed.last_pid) {\n\t\t\tdetailed = {};\n\t\t\tdetailed.last_pid = pid;\n\t\t\tdetailed.skip_smaps = not Config::getB(\"proc_info_smaps\");\n\t\t}\n\n\t\t//? Copy proc_info for process from proc vector\n\t\tauto p_info = rng::find(procs, pid, &proc_info::pid);\n\t\tdetailed.entry = *p_info;\n\n\t\t//? Update cpu percent deque for process cpu graph\n\t\tif (not Config::getB(\"proc_per_core\")) detailed.entry.cpu_p *= Shared::coreCount;\n\t\tdetailed.cpu_percent.push_back(clamp((long long)round(detailed.entry.cpu_p), 0ll, 100ll));\n\t\twhile (cmp_greater(detailed.cpu_percent.size(), width)) detailed.cpu_percent.pop_front();\n\n\t\t//? Process runtime : current time - start time (both in unix time - seconds since epoch)\n\t\tstruct timeval currentTime;\n\t\tgettimeofday(&currentTime, nullptr);\n\t\t// only interested in second granularity, so ignoring tc_usec\n\t\tif (detailed.entry.state != 'X') detailed.elapsed = sec_to_dhms(currentTime.tv_sec - detailed.entry.cpu_s);\n\t\telse detailed.elapsed = sec_to_dhms(detailed.entry.death_time);\n\t\tif (detailed.elapsed.size() > 8) detailed.elapsed.resize(detailed.elapsed.size() - 3);\n\n\t\t//? Get parent process name\n\t\tif (detailed.parent.empty()) {\n\t\t\tauto p_entry = rng::find(procs, detailed.entry.ppid, &proc_info::pid);\n\t\t\tif (p_entry != procs.end()) detailed.parent = p_entry->name;\n\t\t}\n\n\t\t//? Expand process status from single char to explanative string\n\t\tdetailed.status = get_status(detailed.entry.state);\n\n\t\tdetailed.mem_bytes.push_back(detailed.entry.mem);\n\t\tdetailed.memory = floating_humanizer(detailed.entry.mem);\n\n\t\tif (detailed.first_mem == -1 or detailed.first_mem < detailed.mem_bytes.back() / 2 or detailed.first_mem > detailed.mem_bytes.back() * 4) {\n\t\t\tdetailed.first_mem = min((uint64_t)detailed.mem_bytes.back() * 2, Mem::get_totalMem());\n\t\t\tredraw = true;\n\t\t}\n\n\t\twhile (cmp_greater(detailed.mem_bytes.size(), width)) detailed.mem_bytes.pop_front();\n\t}\n\n\t//* Collects and sorts process information from /proc\n\tauto collect(bool no_update) -> vector<proc_info> & {\n\t\tconst auto &sorting = Config::getS(\"proc_sorting\");\n\t\tauto reverse = Config::getB(\"proc_reversed\");\n\t\tconst auto &filter = Config::getS(\"proc_filter\");\n\t\tauto per_core = Config::getB(\"proc_per_core\");\n\t\tauto tree = Config::getB(\"proc_tree\");\n\t\tauto show_detailed = Config::getB(\"show_detailed\");\n\t\tconst auto pause_proc_list = Config::getB(\"pause_proc_list\");\n\t\tconst size_t detailed_pid = Config::getI(\"detailed_pid\");\n\t\tbool should_filter = current_filter != filter;\n\t\tif (should_filter) current_filter = filter;\n\t\tbool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter);\n\t\tbool tree_mode_change = tree != is_tree_mode;\n\t\tif (sorted_change) {\n\t\t\tcurrent_sort = sorting;\n\t\t\tcurrent_rev = reverse;\n\t\t}\n\t\tif (tree_mode_change) is_tree_mode = tree;\n\n\t\tconst int cmult = (per_core) ? Shared::coreCount : 1;\n\t\tbool got_detailed = false;\n\n\t\tstatic vector<size_t> found;\n\n\t\t//* Use pids from last update if only changing filter, sorting or tree options\n\t\tif (no_update and not current_procs.empty()) {\n\t\t\tif (show_detailed and detailed_pid != detailed.last_pid) _collect_details(detailed_pid, current_procs);\n\t\t} else {\n\t\t\t//* ---------------------------------------------Collection start----------------------------------------------\n\n\t\t\tshould_filter = true;\n\t\t\tfound.clear();\n\t\t\tstruct timeval currentTime;\n\t\t\tgettimeofday(&currentTime, nullptr);\n\t\t\tconst double timeNow = currentTime.tv_sec + (currentTime.tv_usec / 1'000'000);\n\n\t\t\tint count = 0;\n\t\t\tchar buf[_POSIX2_LINE_MAX];\n\t\t\tShared::KvmPtr kd {kvm_openfiles(nullptr, nullptr, nullptr, KVM_NO_FILES, buf)};\n\t\t\tconst struct kinfo_proc2* kprocs = kvm_getproc2(kd.get(), KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), &count);\n\n\t\t\tfor (int i = 0; i < count; i++) {\n\t\t\t\tconst struct kinfo_proc2* kproc = &kprocs[i];\n\t\t\t\tconst size_t pid = (size_t)kproc->p_pid;\n\t\t\t\tif (pid < 1) continue;\n\t\t\t\tfound.push_back(pid);\n\n\t\t\t\t//? Check if pid already exists in current_procs\n\t\t\t\tbool no_cache = false;\n\t\t\t\tauto find_old = rng::find(current_procs, pid, &proc_info::pid);\n\t\t\t\t//? Only add new processes if not paused\n\t\t\t\tif (find_old == current_procs.end()) {\n\t\t\t\t\tif (not pause_proc_list) {\n\t\t\t\t\t\tcurrent_procs.push_back({pid});\n\t\t\t\t\t\tfind_old = current_procs.end() - 1;\n\t\t\t\t\t\tno_cache = true;\n\t\t\t\t\t}\n\t\t\t\t\telse continue;\n\t\t\t\t}\n\t\t\t\telse if (dead_procs.contains(pid)) continue;\n\n\t\t\t\tauto &new_proc = *find_old;\n\n\t\t\t\t//? Get program name, command, username, parent pid, nice and status\n\t\t\t\tif (no_cache) {\n\t\t\t\t\tif (string(kproc->p_comm) == \"idle\"s) {\n\t\t\t\t\t\tcurrent_procs.pop_back();\n\t\t\t\t\t\tfound.pop_back();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tnew_proc.name = kproc->p_comm;\n\t\t\t\t\tchar** argv = kvm_getargv2(kd.get(), kproc, 0);\n\t\t\t\t\tif (argv) {\n\t\t\t\t\t\tfor (int i = 0; argv[i] and cmp_less(new_proc.cmd.size(), 1000); i++) {\n\t\t\t\t\t\t\tnew_proc.cmd += argv[i] + \" \"s;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (not new_proc.cmd.empty()) new_proc.cmd.pop_back();\n\t\t\t\t\t}\n\t\t\t\t\tif (new_proc.cmd.empty()) new_proc.cmd = new_proc.name;\n\t\t\t\t\tif (new_proc.cmd.size() > 1000) {\n\t\t\t\t\t\tnew_proc.cmd.resize(1000);\n\t\t\t\t\t\tnew_proc.cmd.shrink_to_fit();\n\t\t\t\t\t}\n\t\t\t\t\tnew_proc.ppid = kproc->p_ppid;\n\t\t\t\t\tnew_proc.cpu_s = round(kproc->p_ustart_sec);\n\t\t\t\t\tstruct passwd *pwd = getpwuid(kproc->p_uid);\n\t\t\t\t\tif (pwd)\n\t\t\t\t\t\tnew_proc.user = pwd->pw_name;\n\t\t\t\t}\n\t\t\t\tnew_proc.p_nice = kproc->p_nice;\n\t\t\t\tnew_proc.state = kproc->p_stat;\n\n\t\t\t\tint cpu_t = 0;\n\t\t\t\tcpu_t \t= kproc->p_uctime_usec * 1'000'000 + kproc->p_uctime_sec;\n\n\t\t\t\tnew_proc.mem = kproc->p_vm_rssize * Shared::pageSize;\n\t\t\t\tnew_proc.threads = 1; // can't seem to find this in kinfo_proc\n\n\t\t\t\t//? Process cpu usage since last update\n\t\t\t\tnew_proc.cpu_p = clamp((100.0 * kproc->p_pctcpu / Shared::kfscale) * cmult, 0.0, 100.0 * Shared::coreCount);\n\n\t\t\t\t//? Process cumulative cpu usage since process start\n\t\t\t\tnew_proc.cpu_c = (double)(cpu_t * Shared::clkTck / 1'000'000) / max(1.0, timeNow - new_proc.cpu_s);\n\n\t\t\t\t//? Update cached value with latest cpu times\n\t\t\t\tnew_proc.cpu_t = cpu_t;\n\n\t\t\t\tif (show_detailed and not got_detailed and new_proc.pid == detailed_pid) {\n\t\t\t\t\tgot_detailed = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Clear dead processes from current_procs if not paused\n\t\t\tif (not pause_proc_list) {\n\t\t\t\tauto eraser = rng::remove_if(current_procs, [&](const auto& element) { return not v_contains(found, element.pid); });\n\t\t\t\tcurrent_procs.erase(eraser.begin(), eraser.end());\n\t\t\t\tif (!dead_procs.empty()) dead_procs.clear();\n\t\t\t}\n\t\t\t//? Set correct state of dead processes if paused\n\t\t\telse {\n\t\t\t\tconst bool keep_dead_proc_usage = Config::getB(\"keep_dead_proc_usage\");\n\t\t\t\tfor (auto& r : current_procs) {\n\t\t\t\t\tif (rng::find(found, r.pid) == found.end()) {\n\t\t\t\t\t\tif (r.state != 'X') {\n\t\t\t\t\t\t\tstruct timeval currentTime;\n\t\t\t\t\t\t\tgettimeofday(&currentTime, nullptr);\n\t\t\t\t\t\t\tr.death_time = currentTime.tv_sec - r.cpu_s;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tr.state = 'X';\n\t\t\t\t\t\tdead_procs.emplace(r.pid);\n\t\t\t\t\t\t//? Reset cpu usage for dead processes if paused and option is set\n\t\t\t\t\t\tif (!keep_dead_proc_usage) {\n\t\t\t\t\t\t\tr.cpu_p = 0.0;\n\t\t\t\t\t\t\tr.mem = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Update the details info box for process if active\n\t\t\tif (show_detailed and got_detailed) {\n\t\t\t\t_collect_details(detailed_pid, current_procs);\n\t\t\t} else if (show_detailed and not got_detailed and detailed.status != \"Dead\") {\n\t\t\t\tdetailed.status = \"Dead\";\n\t\t\t\tredraw = true;\n\t\t\t}\n\n\t\t\told_cputimes = cputimes;\n\n\t\t}\n\n\t\t//* ---------------------------------------------Collection done-----------------------------------------------\n\n\t\t//* Match filter if defined\n\t\tif (should_filter) {\n\t\t\tfilter_found = 0;\n\t\t\tfor (auto& p : current_procs) {\n\t\t\t\tif (not tree and not filter.empty()) {\n\t\t\t\t\t\tif (not s_contains_ic(to_string(p.pid), filter)\n\t\t\t\t\t\tand not s_contains_ic(p.name, filter)\n\t\t\t\t\t\tand not s_contains_ic(p.cmd, filter)\n\t\t\t\t\t\tand not s_contains_ic(p.user, filter)) {\n\t\t\t\t\t\t\tp.filtered = true;\n\t\t\t\t\t\t\tfilter_found++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tp.filtered = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tp.filtered = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//* Sort processes\n\t\tif ((sorted_change or tree_mode_change) or (not no_update and not pause_proc_list)) {\n\t\t\tproc_sorter(current_procs, sorting, reverse, tree);\n\t\t}\n\n\t\t//* Generate tree view if enabled\n\t\tif (tree and (not no_update or should_filter or sorted_change)) {\n\t\t\tbool locate_selection = false;\n\t\t\tif (auto find_pid = (collapse != -1 ? collapse : expand); find_pid != -1) {\n\t\t\t\tauto collapser = rng::find(current_procs, find_pid, &proc_info::pid);\n\t\t\t\tif (collapser != current_procs.end()) {\n\t\t\t\t\tif (collapse == expand) {\n\t\t\t\t\t\tcollapser->collapsed = not collapser->collapsed;\n\t\t\t\t\t}\n\t\t\t\t\telse if (collapse > -1) {\n\t\t\t\t\t\tcollapser->collapsed = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (expand > -1) {\n\t\t\t\t\t\tcollapser->collapsed = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (Config::ints.at(\"proc_selected\") > 0) locate_selection = true;\n\t\t\t\t}\n\t\t\t\tcollapse = expand = -1;\n\t\t\t}\n\t\t\tif (should_filter or not filter.empty()) filter_found = 0;\n\n\t\t\tvector<tree_proc> tree_procs;\n\t\t\ttree_procs.reserve(current_procs.size());\n\n\t\t\tif (!pause_proc_list) {\n\t\t\t\tfor (auto& p : current_procs) {\n\t\t\t\t\tif (not v_contains(found, p.ppid)) p.ppid = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Stable sort to retain selected sorting among processes with the same parent\n\t\t\trng::stable_sort(current_procs, rng::less{}, & proc_info::ppid);\n\n\t\t\t//? Start recursive iteration over processes with the lowest shared parent pids\n\t\t\tfor (auto& p : rng::equal_range(current_procs, current_procs.at(0).ppid, rng::less{}, &proc_info::ppid)) {\n\t\t\t\t_tree_gen(p, current_procs, tree_procs, 0, false, filter, false, no_update, should_filter);\n\t\t\t}\n\n\t\t\t//? Recursive sort over tree structure to account for collapsed processes in the tree\n\t\t\tint index = 0;\n\t\t\ttree_sort(tree_procs, sorting, reverse, (pause_proc_list and not (sorted_change or tree_mode_change)), index, current_procs.size());\n\n\t\t\t//? Recursive construction of ASCII tree prefixes.\n\t\t\tfor (auto t = tree_procs.begin(); t != tree_procs.end(); ++t) {\n\t\t\t\t_collect_prefixes(*t, t == tree_procs.end() - 1);\n\t\t\t}\n\n\t\t\t//? Final sort based on tree index\n\t\t\trng::stable_sort(current_procs, rng::less {}, &proc_info::tree_index);\n\n\t\t\t//? Move current selection/view to the selected process when collapsing/expanding in the tree\n\t\t\tif (locate_selection) {\n\t\t\t\tint loc = rng::find(current_procs, Proc::selected_pid, &proc_info::pid)->tree_index;\n\t\t\t\tif (Config::ints.at(\"proc_start\") >= loc or Config::ints.at(\"proc_start\") <= loc - Proc::select_max)\n\t\t\t\t\tConfig::ints.at(\"proc_start\") = max(0, loc - 1);\n\t\t\t\tConfig::ints.at(\"proc_selected\") = loc - Config::ints.at(\"proc_start\") + 1;\n\t\t\t}\n\t\t}\n\n\t\tnumpids = (int)current_procs.size() - filter_found;\n\t\treturn current_procs;\n\t}\n}  // namespace Proc\n\nnamespace Tools {\n\tdouble system_uptime() {\n\t\tstruct timeval ts, currTime;\n\t\tstd::size_t len = sizeof(ts);\n\t\tint mib[2] = {CTL_KERN, KERN_BOOTTIME};\n\t\tif (sysctl(mib, 2, &ts, &len, nullptr, 0) != -1) {\n\t\t\tgettimeofday(&currTime, nullptr);\n\t\t\treturn currTime.tv_sec - ts.tv_sec;\n\t\t}\n\t\treturn 0.0;\n\t}\n}  // namespace Tools\n"
  },
  {
    "path": "src/openbsd/btop_collect.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n#include <arpa/inet.h>\n#include <cstddef>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n// man 3 getifaddrs: \"BUGS: If\tboth <net/if.h>\tand <ifaddrs.h>\tare being included, <net/if.h> must be included before <ifaddrs.h>\"\n#include <net/if.h>\n#include <ifaddrs.h>\n#include <net/if_dl.h>\n#include <net/route.h>\n#include <netdb.h>\n#include <netinet/tcp_fsm.h>\n#include <netinet/in.h> // for inet_ntop stuff\n#include <pwd.h>\n#include <sys/endian.h>\n#include <sys/resource.h>\n#include <sys/socket.h>\n#include <sys/statvfs.h>\n#include <sys/sysctl.h>\n#include <sys/sched.h>\n#include <sys/signal.h>\n#include <sys/siginfo.h>\n#include <sys/proc.h>\n#include <sys/types.h>\n#include <sys/user.h>\n#include <sys/param.h>\n#include <sys/ucred.h>\n#include <sys/mount.h>\n#include <sys/vmmeter.h>\n#include <sys/limits.h>\n#include <sys/sensors.h>\n#include <sys/disk.h>\n#include <vector>\n#include <kvm.h>\n#include <paths.h>\n#include <fcntl.h>\n#include <unistd.h>\n\n#include <stdexcept>\n#include <cmath>\n#include <fstream>\n#include <numeric>\n#include <ranges>\n#include <algorithm>\n#include <regex>\n#include <string>\n#include <memory>\n#include <unordered_set>\n\n#include <fmt/format.h>\n\n#include \"../btop_config.hpp\"\n#include \"../btop_log.hpp\"\n#include \"../btop_shared.hpp\"\n#include \"../btop_tools.hpp\"\n\n#include \"./sysctlbyname.h\"\n\nusing std::clamp, std::string_literals::operator\"\"s, std::cmp_equal, std::cmp_less, std::cmp_greater;\nusing std::ifstream, std::numeric_limits, std::streamsize, std::round, std::max, std::min;\nnamespace fs = std::filesystem;\nnamespace rng = std::ranges;\nusing namespace Tools;\n\n//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------\n\nnamespace Cpu {\n\tvector<long long> core_old_totals;\n\tvector<long long> core_old_idles;\n\tvector<string> available_fields = {\"total\"};\n\tvector<string> available_sensors = {\"Auto\"};\n\tcpu_info current_cpu;\n\tbool got_sensors = false, cpu_temp_only = false, supports_watts = false;\n\n\t//* Populate found_sensors map\n\tbool get_sensors();\n\n\t//* Get current cpu clock speed\n\tstring get_cpuHz();\n\n\t//* Search /proc/cpuinfo for a cpu name\n\tstring get_cpuName();\n\n\tstruct Sensor {\n\t\tfs::path path;\n\t\tstring label;\n\t\tint64_t temp = 0;\n\t\tint64_t high = 0;\n\t\tint64_t crit = 0;\n\t};\n\n\tstring cpu_sensor;\n\tvector<string> core_sensors;\n\tstd::unordered_map<int, int> core_mapping;\n}  // namespace Cpu\n\nnamespace Mem {\n\tdouble old_uptime;\n}\n\nnamespace Shared {\n\n\tfs::path passwd_path;\n\tuint64_t totalMem;\n\tlong pageSize, clkTck, coreCount, physicalCoreCount, arg_max;\n\tint totalMem_len, kfscale;\n\tlong bootTime;\n\n\tvoid init() {\n\t\t//? Shared global variables init\n\t\tint mib[2];\n\t\tmib[0] = CTL_HW;\n\t\tmib[1] = HW_NCPU;\n\t\tint ncpu;\n\t\tsize_t len = sizeof(ncpu);\n\t\tif (sysctl(mib, 2, &ncpu, &len, nullptr, 0) == -1) {\n\t\t\tLogger::warning(\"Could not determine number of cores, defaulting to 1.\");\n\t\t} else {\n\t\t\tcoreCount = ncpu;\n\t\t}\n\n\t\tpageSize = sysconf(_SC_PAGE_SIZE);\n\t\tif (pageSize <= 0) {\n\t\t\tpageSize = 4096;\n\t\t\tLogger::warning(\"Could not get system page size. Defaulting to 4096, processes memory usage might be incorrect.\");\n\t\t}\n\n\t\tclkTck = sysconf(_SC_CLK_TCK);\n\t\tif (clkTck <= 0) {\n\t\t\tclkTck = 100;\n\t\t\tLogger::warning(\"Could not get system clock ticks per second. Defaulting to 100, processes cpu usage might be incorrect.\");\n\t\t}\n\n\t\tint64_t memsize = 0;\n\t\tsize_t size = sizeof(memsize);\n\t\tif (sysctlbyname(\"hw.physmem\", &memsize, &size, nullptr, 0) < 0) {\n\t\t\tLogger::warning(\"Could not get memory size\");\n\t\t}\n\t\ttotalMem = memsize;\n\n\t\tstruct timeval result;\n\t\tsize = sizeof(result);\n\t\tif (sysctlbyname(\"kern.boottime\", &result, &size, nullptr, 0) < 0) {\n\t\t\tLogger::warning(\"Could not get boot time\");\n\t\t} else {\n\t\t\tbootTime = result.tv_sec;\n\t\t}\n\n\t\tsize = sizeof(kfscale);\n\t\tif (sysctlbyname(\"kern.fscale\", &kfscale, &size, nullptr, 0) == -1) {\n\t\t\tkfscale = 2048;\n\t\t}\n\n\t\t//* Get maximum length of process arguments\n\t\targ_max = sysconf(_SC_ARG_MAX);\n\n\t\t//? Init for namespace Cpu\n\t\tCpu::current_cpu.core_percent.insert(Cpu::current_cpu.core_percent.begin(), Shared::coreCount, {});\n\t\tCpu::current_cpu.temp.insert(Cpu::current_cpu.temp.begin(), Shared::coreCount + 1, {});\n\t\tCpu::core_old_totals.insert(Cpu::core_old_totals.begin(), Shared::coreCount, 0);\n\t\tCpu::core_old_idles.insert(Cpu::core_old_idles.begin(), Shared::coreCount, 0);\n\t\tCpu::collect();\n\t\tfor (auto &[field, vec] : Cpu::current_cpu.cpu_percent) {\n\t\t\tif (not vec.empty() and not v_contains(Cpu::available_fields, field)) Cpu::available_fields.push_back(field);\n\t\t}\n\t\tCpu::cpuName = Cpu::get_cpuName();\n\t\tCpu::got_sensors = Cpu::get_sensors();\n\t\tCpu::core_mapping = Cpu::get_core_mapping();\n\n\t\t//? Init for namespace Mem\n\t\tMem::old_uptime = system_uptime();\n\t\tMem::collect();\n\t}\n}  // namespace Shared\n\nnamespace Cpu {\n\tstring cpuName;\n\tstring cpuHz;\n\tbool has_battery = true;\n\ttuple<int, float, long, string> current_bat;\n\n\tconst array<string, 10> time_names = {\"user\", \"nice\", \"system\", \"idle\"};\n\n\tstd::unordered_map<string, long long> cpu_old = {\n\t\t{\"totals\", 0},\n\t\t{\"idles\", 0},\n\t\t{\"user\", 0},\n\t\t{\"nice\", 0},\n\t\t{\"system\", 0},\n\t\t{\"idle\", 0}\n\t};\n\n\tstring get_cpuName() {\n\t\tstring name;\n\t\tchar buffer[1024];\n\t\tsize_t size = sizeof(buffer);\n\t\tif (sysctlbyname(\"hw.model\", &buffer, &size, nullptr, 0) < 0) {\n\t\t\tLogger::error(\"Failed to get CPU name\");\n\t\t\treturn name;\n\t\t}\n\t\treturn trim_name(string(buffer));\n\t}\n\n\tint64_t get_sensor(string device, vector<sensor_type> types, int num) {\n\t\tstruct sensordev sensordev;\n\t\tstruct sensor sensor;\n\t\tsize_t sdlen, slen;\n\t\tint dev;\n\t\tint mib[] = {CTL_HW, HW_SENSORS, 0, 0, 0};\n\n\t\tsdlen = sizeof(sensordev);\n\t\tslen = sizeof(sensor);\n\t\tfor (dev = 0;; dev++) {\n\t\t\tmib[2] = dev;\n\t\t\tif (sysctl(mib, 3, &sensordev, &sdlen, NULL, 0) == -1) {\n\t\t\t\tif (errno == ENXIO)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (errno == ENOENT)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (strstr(sensordev.xname, device.c_str())) {\n\t\t\t\tmib[4] = num;\n\t\t\t\tfor (sensor_type type : types) {\n\t\t\t\t\tmib[3] = type;\n\t\t\t\t\tif (sysctl(mib, 5, &sensor, &slen, NULL, 0) == -1) {\n\t\t\t\t\t\tif (errno != ENOENT) {\n\t\t\t\t\t\t\tLogger::warning(\"sysctl\");\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else\n\t\t\t\t\t\treturn sensor.value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\n\tbool get_sensors() {\n\t\tgot_sensors = false;\n\t\tif (Config::getB(\"show_coretemp\") and Config::getB(\"check_temp\")) {\n\t\t\tif (get_sensor(string(\"cpu0\"), { SENSOR_TEMP }, 0) > 0) {\n\t\t\t\tgot_sensors = true;\n\t\t\t\tcurrent_cpu.temp_max = 100; // we don't have this info\n\t\t\t} else {\n\t\t\t\tLogger::warning(\"Could not get temp sensor\");\n\t\t\t}\n\t\t}\n\t\treturn got_sensors;\n\t}\n\n#define MUKTOC(v) ((v - 273150000) / 1000000.0)\n\n\tvoid update_sensors() {\n\t\tint temp = 0;\n\t\tint p_temp = 0;\n\n\t\ttemp = get_sensor(string(\"cpu0\"), { SENSOR_TEMP }, 0);\n\t\tif (temp > -1) {\n\t\t\ttemp = MUKTOC(temp);\n\t\t\tp_temp = temp;\n\t\t\tfor (int i = 0; i < Shared::coreCount; i++) {\n\t\t\t\tif (cmp_less(i + 1, current_cpu.temp.size())) {\n\t\t\t\t\tcurrent_cpu.temp.at(i + 1).push_back(temp);\n\t\t\t\t\tif (current_cpu.temp.at(i + 1).size() > 20)\n\t\t\t\t\t\tcurrent_cpu.temp.at(i + 1).pop_front();\n\t\t\t\t}\n\t\t\t}\n\t\t\tcurrent_cpu.temp.at(0).push_back(p_temp);\n\t\t\tif (current_cpu.temp.at(0).size() > 20)\n\t\t\t\tcurrent_cpu.temp.at(0).pop_front();\n\t\t}\n\n\t}\n\n\tstring get_cpuHz() {\n\t\tunsigned int freq = 1;\n\t\tsize_t size = sizeof(freq);\n\n\t\tif (sysctlbyname(\"hw.cpuspeed\", &freq, &size, nullptr, 0) < 0) {\n\t\t\treturn \"\";\n\t\t}\n\t\treturn std::to_string(freq / 1000.0 ).substr(0, 3); // seems to be in MHz\n\t}\n\n\tauto get_core_mapping() -> std::unordered_map<int, int> {\n\t\tstd::unordered_map<int, int> core_map;\n\t\tif (cpu_temp_only) return core_map;\n\n\t\tfor (long i = 0; i < Shared::coreCount; i++) {\n\t\t\tcore_map[i] = i;\n\t\t}\n\n\t\t//? If core mapping from cpuinfo was incomplete try to guess remainder, if missing completely, map 0-0 1-1 2-2 etc.\n\t\tif (cmp_less(core_map.size(), Shared::coreCount)) {\n\t\t\tif (Shared::coreCount % 2 == 0 and (long) core_map.size() == Shared::coreCount / 2) {\n\t\t\t\tfor (int i = 0, n = 0; i < Shared::coreCount / 2; i++) {\n\t\t\t\t\tif (std::cmp_greater_equal(n, core_sensors.size())) n = 0;\n\t\t\t\t\tcore_map[Shared::coreCount / 2 + i] = n++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcore_map.clear();\n\t\t\t\tfor (int i = 0, n = 0; i < Shared::coreCount; i++) {\n\t\t\t\t\tif (std::cmp_greater_equal(n, core_sensors.size())) n = 0;\n\t\t\t\t\tcore_map[i] = n++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//? Apply user set custom mapping if any\n\t\tconst auto &custom_map = Config::getS(\"cpu_core_map\");\n\t\tif (not custom_map.empty()) {\n\t\t\ttry {\n\t\t\t\tfor (const auto &split : ssplit(custom_map)) {\n\t\t\t\t\tconst auto vals = ssplit(split, ':');\n\t\t\t\t\tif (vals.size() != 2) continue;\n\t\t\t\t\tint change_id = std::stoi(vals.at(0));\n\t\t\t\t\tint new_id = std::stoi(vals.at(1));\n\t\t\t\t\tif (not core_map.contains(change_id) or cmp_greater(new_id, core_sensors.size())) continue;\n\t\t\t\t\tcore_map.at(change_id) = new_id;\n\t\t\t\t}\n\t\t\t} catch (...) {\n\t\t\t}\n\t\t}\n\n\t\treturn core_map;\n\t}\n\n\tauto get_battery() -> tuple<int, float, long, string> {\n\t\tif (not has_battery) return {0, 0, 0, \"\"};\n\n\t\tlong seconds = -1;\n\t\tuint32_t percent = -1;\n\t\tfloat rate = -1.0f;\n\t\tstring status = \"discharging\";\n\t\tint64_t full, remaining, watts;\n\t\tfull = get_sensor(\"acpibat0\", { SENSOR_AMPHOUR, SENSOR_WATTHOUR }, 0);\n\t\tremaining = get_sensor(\"acpibat0\", { SENSOR_AMPHOUR, SENSOR_WATTHOUR }, 3);\n\t\twatts = get_sensor(\"acpibat0\", { SENSOR_WATTS }, 0);\n\t\tint64_t state = get_sensor(\"acpibat0\", { SENSOR_INTEGER }, 0);\n\t\tif (full < 0) {\n\t\t\thas_battery = false;\n\t\t\tLogger::warning(\"failed to get battery\");\n\t\t} else {\n\t\t\tfloat_t f = full / 1000;\n\t\t\tfloat_t r = remaining / 1000;\n\t\t\tif (watts > 0) {\n\t\t\t\tsupports_watts = true;\n\t\t\t\trate = watts / 1000000.0f; // watts is given in µW\n\t\t\t}\n\t\t\thas_battery = true;\n\t\t\tpercent = r / f * 100;\n\t\t\tif (percent == 100) {\n\t\t\t\tstatus = \"full\";\n\t\t\t}\n\t\t\tswitch (state) {\n\t\t\t\tcase 0:\n\t\t\t\t\tstatus = \"full\";\n\t\t\t\t\tpercent = 100;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 2:\n\t\t\t\t\tstatus = \"charging\";\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn {percent, rate, seconds, status};\n\t}\n\n\tauto collect(bool no_update) -> cpu_info & {\n\t\tif (Runner::stopping or (no_update and not current_cpu.cpu_percent.at(\"total\").empty()))\n\t\t\treturn current_cpu;\n\t\tauto &cpu = current_cpu;\n\n\t\tif (getloadavg(cpu.load_avg.data(), cpu.load_avg.size()) < 0) {\n\t\t\tLogger::error(\"failed to get load averages\");\n\t\t}\n\n\t\tauto cp_time = std::unique_ptr<struct cpustats[]>{\n\t\t\tnew struct cpustats[Shared::coreCount]\n\t\t};\n\t\tsize_t size = Shared::coreCount * sizeof(struct cpustats);\n\t\tstatic int cpustats_mib[] = {CTL_KERN, KERN_CPUSTATS, /*fillme*/0};\n\t\tfor (int i = 0; i < Shared::coreCount; i++) {\n\t\t\tcpustats_mib[2] = i / 2;\n\t\t\tif (sysctl(cpustats_mib, 3, &cp_time[i], &size, NULL, 0) == -1) {\n\t\t\t\tLogger::error(\"sysctl kern.cpustats failed\");\n\t\t\t}\n\t\t}\n\t\tlong long global_totals = 0;\n\t\tlong long global_idles = 0;\n\t\tvector<long long> times_summed = {0, 0, 0, 0};\n\n\t\tfor (long i = 0; i < Shared::coreCount; i++) {\n\t\t\tvector<long long> times;\n\t\t\t//? 0=user, 1=nice, 2=system, 3=idle\n\t\t\tfor (int x = 0; const unsigned int c_state : {CP_USER, CP_NICE, CP_SYS, CP_IDLE}) {\n\t\t\t\tauto val = cp_time[i].cs_time[c_state];\n\t\t\t\ttimes.push_back(val);\n\t\t\t\ttimes_summed.at(x++) += val;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\t//? All values\n\t\t\t\tconst long long totals = std::accumulate(times.begin(), times.end(), 0ll);\n\n\t\t\t\t//? Idle time\n\t\t\t\tconst long long idles = times.at(3);\n\n\t\t\t\tglobal_totals += totals;\n\t\t\t\tglobal_idles += idles;\n\n\t\t\t\t//? Calculate cpu total for each core\n\t\t\t\tif (i > Shared::coreCount) break;\n\t\t\t\tconst long long calc_totals = max(0ll, totals - core_old_totals.at(i));\n\t\t\t\tconst long long calc_idles = max(0ll, idles - core_old_idles.at(i));\n\t\t\t\tcore_old_totals.at(i) = totals;\n\t\t\t\tcore_old_idles.at(i) = idles;\n\n\t\t\t\tcpu.core_percent.at(i).push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));\n\n\t\t\t\t//? Reduce size if there are more values than needed for graph\n\t\t\t\tif (cpu.core_percent.at(i).size() > 40) cpu.core_percent.at(i).pop_front();\n\n\t\t\t} catch (const std::exception &e) {\n\t\t\t\tLogger::error(\"Cpu::collect() : {}\", e.what());\n\t\t\t\tthrow std::runtime_error(fmt::format(\"collect() : {}\", e.what()));\n\t\t\t}\n\n\t\t}\n\n\t\tconst long long calc_totals = max(1ll, global_totals - cpu_old.at(\"totals\"));\n\t\tconst long long calc_idles = max(1ll, global_idles - cpu_old.at(\"idles\"));\n\n\t\t//? Populate cpu.cpu_percent with all fields from syscall\n\t\tfor (int ii = 0; const auto &val : times_summed) {\n\t\t\tcpu.cpu_percent.at(time_names.at(ii)).push_back(clamp((long long)round((double)(val - cpu_old.at(time_names.at(ii))) * 100 / calc_totals), 0ll, 100ll));\n\t\t\tcpu_old.at(time_names.at(ii)) = val;\n\n\t\t\t//? Reduce size if there are more values than needed for graph\n\t\t\twhile (cmp_greater(cpu.cpu_percent.at(time_names.at(ii)).size(), width * 2)) cpu.cpu_percent.at(time_names.at(ii)).pop_front();\n\n\t\t\tii++;\n\t\t}\n\n\t\tcpu_old.at(\"totals\") = global_totals;\n\t\tcpu_old.at(\"idles\") = global_idles;\n\n\t\t//? Total usage of cpu\n\t\tcpu.cpu_percent.at(\"total\").push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));\n\n\t\t//? Reduce size if there are more values than needed for graph\n\t\twhile (cmp_greater(cpu.cpu_percent.at(\"total\").size(), width * 2)) cpu.cpu_percent.at(\"total\").pop_front();\n\n\t\tif (Config::getB(\"show_cpu_freq\")) {\n\t\t\tauto hz = get_cpuHz();\n\t\t\tif (hz != \"\") {\n\t\t\t\tcpuHz = hz;\n\t\t\t}\n\t\t}\n\n\t\tif (Config::getB(\"check_temp\") and got_sensors)\n\t\t\tupdate_sensors();\n\n\t\tif (Config::getB(\"show_battery\") and has_battery)\n\t\t\tcurrent_bat = get_battery();\n\n\t\treturn cpu;\n\t}\n}  // namespace Cpu\n\nnamespace Mem {\n\tbool has_swap = false;\n\tvector<string> fstab;\n\tfs::file_time_type fstab_time;\n\tint disk_ios = 0;\n\tvector<string> last_found;\n\n\tmem_info current_mem{};\n\n\tuint64_t get_totalMem() {\n\t\treturn Shared::totalMem;\n\t}\n\n\tvoid assign_values(struct disk_info& disk, int64_t readBytes, int64_t writeBytes) {\n\t\tdisk_ios++;\n\t\tif (disk.io_read.empty()) {\n\t\t\tdisk.io_read.push_back(0);\n\t\t} else {\n\t\t\tdisk.io_read.push_back(max((int64_t)0, (readBytes - disk.old_io.at(0))));\n\t\t}\n\t\tdisk.old_io.at(0) = readBytes;\n\t\twhile (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front();\n\n\t\tif (disk.io_write.empty()) {\n\t\t\tdisk.io_write.push_back(0);\n\t\t} else {\n\t\t\tdisk.io_write.push_back(max((int64_t)0, (writeBytes - disk.old_io.at(1))));\n\t\t}\n\t\tdisk.old_io.at(1) = writeBytes;\n\t\twhile (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front();\n\n\t\t// no io times - need to push something anyway or we'll get an ABORT\n\t\tif (disk.io_activity.empty())\n\t\t\tdisk.io_activity.push_back(0);\n\t\telse\n\t\t\tdisk.io_activity.push_back(clamp((long)round((double)(disk.io_write.back() + disk.io_read.back()) / (1 << 20)), 0l, 100l));\n\t\twhile (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();\n\t}\n\n\tvoid collect_disk(std::unordered_map<string, disk_info> &disks, std::unordered_map<string, string> &mapping) {\n\t\tuint64_t total_bytes_read = 0;\n\t\tuint64_t total_bytes_write = 0;\n\n\t\tint num_drives = 0;\n\t\tint mib[2] = { CTL_HW, HW_DISKCOUNT };\n\n\t\tsize_t size;\n\t\tif (sysctl(mib, 2, &num_drives, &size, NULL, 0) >= 0) {\n\t\t\tmib[0] = CTL_HW;\n\t\t\tmib[1] = HW_DISKSTATS;\n\t\t\tsize = num_drives * sizeof(struct diskstats);\n\t\t\tauto p = std::unique_ptr<struct diskstats[], void(*)(void*)> {\n\t\t\t\treinterpret_cast<struct diskstats*>(malloc(size)),\n\t\t\t\tfree\n\t\t\t};\n\t\t\tif (sysctl(mib, 2, p.get(), &size, NULL, 0) == -1) {\n\t\t\t\tLogger::error(\"failed to get disk stats\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor (int i = 0; i < num_drives; i++) {\n\t\t\t\tfor (auto& [ignored, disk] : disks) {\n\t\t\t\t\tif (disk.dev.string().find(p[i].ds_name) != string::npos) {\n\t\t\t\t\t\tstring mountpoint = mapping.at(disk.dev);\n\t\t\t\t\t\ttotal_bytes_read = p[i].ds_rbytes;\n\t\t\t\t\t\ttotal_bytes_write = p[i].ds_wbytes;\n\t\t\t\t\t\tassign_values(disk, total_bytes_read, total_bytes_write);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tauto collect(bool no_update) -> mem_info & {\n\t\tif (Runner::stopping or (no_update and not current_mem.percent.at(\"used\").empty()))\n\t\t\treturn current_mem;\n\n\t\tauto show_swap = Config::getB(\"show_swap\");\n\t\tauto show_disks = Config::getB(\"show_disks\");\n\t\tauto swap_disk = Config::getB(\"swap_disk\");\n\t\tauto &mem = current_mem;\n\t\tstatic bool snapped = (getenv(\"BTOP_SNAPPED\") != nullptr);\n\n\t\tu_int memActive, memWire, cachedMem;\n\t\t// u_int freeMem;\n\t\tsize_t size;\n\t\tstatic int uvmexp_mib[] = {CTL_VM, VM_UVMEXP};\n\t\tstatic int bcstats_mib[] = {CTL_VFS, VFS_GENERIC, VFS_BCACHESTAT};\n\t\tstruct uvmexp uvmexp;\n\t\tstruct bcachestats bcstats;\n\t\tsize = sizeof(uvmexp);\n\t\tif (sysctl(uvmexp_mib, 2, &uvmexp, &size, NULL, 0) == -1) {\n\t\t\tLogger::error(\"sysctl failed\");\n\t\t\tbzero(&uvmexp, sizeof(uvmexp));\n\t\t}\n\t\tsize = sizeof(bcstats);\n\t\tif (sysctl(bcstats_mib, 3, &bcstats, &size, NULL, 0) == -1) {\n\t\t\tLogger::error(\"sysctl failed\");\n\t\t\tbzero(&bcstats, sizeof(bcstats));\n\t\t}\n\t\tmemActive = uvmexp.active * Shared::pageSize;\n\t\tmemWire = uvmexp.wired;\n\t\t// freeMem = uvmexp.free * Shared::pageSize;\n\t\tcachedMem = bcstats.numbufpages * Shared::pageSize;\n\t\tmem.stats.at(\"used\") = memActive;\n\t\tmem.stats.at(\"available\") = Shared::totalMem - memActive - memWire;\n   \t\tmem.stats.at(\"cached\") = cachedMem;\n  \t\tmem.stats.at(\"free\") = Shared::totalMem - memActive - memWire;\n\n\t\tif (show_swap) {\n\t\t\tint total = uvmexp.swpages * Shared::pageSize;\n\t\t\tmem.stats.at(\"swap_total\") = total;\n\t\t\tint swapped = uvmexp.swpgonly * Shared::pageSize;\n\t\t\tmem.stats.at(\"swap_used\") = swapped;\n\t\t\tmem.stats.at(\"swap_free\") = total - swapped;\n\t\t}\n\n\t\tif (show_swap and mem.stats.at(\"swap_total\") > 0) {\n\t\t\tfor (const auto &name : swap_names) {\n\t\t\t\tmem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / mem.stats.at(\"swap_total\")));\n\t\t\t\twhile (cmp_greater(mem.percent.at(name).size(), width * 2))\n\t\t\t\t\tmem.percent.at(name).pop_front();\n\t\t\t}\n\t\t\thas_swap = true;\n\t\t} else\n\t\t\thas_swap = false;\n\t\t//? Calculate percentages\n\t\tfor (const auto &name : mem_names) {\n\t\t\tmem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / Shared::totalMem));\n\t\t\twhile (cmp_greater(mem.percent.at(name).size(), width * 2))\n\t\t\t\tmem.percent.at(name).pop_front();\n\t\t}\n\n\t\tif (show_disks) {\n\t\t\tstd::unordered_map<string, string> mapping;  // keep mapping from device -> mountpoint, since IOKit doesn't give us the mountpoint\n\t\t\tdouble uptime = system_uptime();\n\t\t\tauto &disks_filter = Config::getS(\"disks_filter\");\n\t\t\tbool filter_exclude = false;\n\t\t\t// auto only_physical = Config::getB(\"only_physical\");\n\t\t\tauto &disks = mem.disks;\n\t\t\tvector<string> filter;\n\t\t\tif (not disks_filter.empty()) {\n\t\t\t\tfilter = ssplit(disks_filter);\n\t\t\t\tif (filter.at(0).starts_with(\"exclude=\")) {\n\t\t\t\t\tfilter_exclude = true;\n\t\t\t\t\tfilter.at(0) = filter.at(0).substr(8);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstruct statfs *stfs;\n\t\t\tint count = getmntinfo(&stfs, MNT_WAIT);\n\t\t\tvector<string> found;\n\t\t\tfound.reserve(last_found.size());\n\t\t\tfor (int i = 0; i < count; i++) {\n\t\t\t\tauto fstype = string(stfs[i].f_fstypename);\n\t\t\t\tif (fstype == \"autofs\" || fstype == \"devfs\" || fstype == \"linprocfs\" || fstype == \"procfs\" || fstype == \"tmpfs\" || fstype == \"linsysfs\" ||\n\t\t\t\t\tfstype == \"fdesckfs\") {\n\t\t\t\t\t// in memory filesystems -> not useful to show\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tstd::error_code ec;\n\t\t\t\tstring mountpoint = stfs[i].f_mntonname;\n\t\t\t\tstring dev = stfs[i].f_mntfromname;\n\t\t\t\tmapping[dev] = mountpoint;\n\n\t\t\t\t//? Match filter if not empty\n\t\t\t\tif (not filter.empty()) {\n\t\t\t\t\tbool match = v_contains(filter, mountpoint);\n\t\t\t\t\tif ((filter_exclude and match) or (not filter_exclude and not match))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfound.push_back(mountpoint);\n\t\t\t\tif (not disks.contains(mountpoint)) {\n\t\t\t\t\tdisks[mountpoint] = disk_info{fs::canonical(dev, ec), fs::path(mountpoint).filename()};\n\n\t\t\t\t\tif (disks.at(mountpoint).dev.empty())\n\t\t\t\t\t\tdisks.at(mountpoint).dev = dev;\n\n\t\t\t\t\tif (disks.at(mountpoint).name.empty())\n\t\t\t\t\t\tdisks.at(mountpoint).name = (mountpoint == \"/\" ? \"root\" : mountpoint);\n\t\t\t\t}\n\n\n\t\t\t\tif (not v_contains(last_found, mountpoint))\n\t\t\t\t\tredraw = true;\n\n\t\t\t\tdisks.at(mountpoint).free = stfs[i].f_bfree;\n\t\t\t\tdisks.at(mountpoint).total = stfs[i].f_iosize;\n\t\t\t}\n\n\t\t\t//? Remove disks no longer mounted or filtered out\n\t\t\tif (swap_disk and has_swap) found.push_back(\"swap\");\n\t\t\tfor (auto it = disks.begin(); it != disks.end();) {\n\t\t\t\tif (not v_contains(found, it->first))\n\t\t\t\t\tit = disks.erase(it);\n\t\t\t\telse\n\t\t\t\t\tit++;\n\t\t\t}\n\t\t\tif (found.size() != last_found.size()) redraw = true;\n\t\t\tlast_found = std::move(found);\n\n\t\t\t//? Get disk/partition stats\n\t\t\tfor (auto &[mountpoint, disk] : disks) {\n\t\t\t\tif (std::error_code ec; not fs::exists(mountpoint, ec))\n\t\t\t\t\tcontinue;\n\t\t\t\tstruct statvfs vfs;\n\t\t\t\tif (statvfs(mountpoint.c_str(), &vfs) < 0) {\n\t\t\t\t\tLogger::warning(\"Failed to get disk/partition stats with statvfs() for: {}\", mountpoint);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tdisk.total = vfs.f_blocks * vfs.f_frsize;\n\t\t\t\tdisk.free = vfs.f_bfree * vfs.f_frsize;\n\t\t\t\tdisk.used = disk.total - disk.free;\n\t\t\t\tif (disk.total != 0) {\n\t\t\t\t\tdisk.used_percent = round((double)disk.used * 100 / disk.total);\n\t\t\t\t\tdisk.free_percent = 100 - disk.used_percent;\n\t\t\t\t} else {\n\t\t\t\t\tdisk.used_percent = 0;\n\t\t\t\t\tdisk.free_percent = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Setup disks order in UI and add swap if enabled\n\t\t\tmem.disks_order.clear();\n\t\t\tif (snapped and disks.contains(\"/mnt\"))\n\t\t\t\tmem.disks_order.push_back(\"/mnt\");\n\t\t\telse if (disks.contains(\"/\"))\n\t\t\t\tmem.disks_order.push_back(\"/\");\n\t\t\tif (swap_disk and has_swap) {\n\t\t\t\tmem.disks_order.push_back(\"swap\");\n\t\t\t\tif (not disks.contains(\"swap\"))\n\t\t\t\t\tdisks[\"swap\"] = {\"\", \"swap\"};\n\t\t\t\tdisks.at(\"swap\").total = mem.stats.at(\"swap_total\");\n\t\t\t\tdisks.at(\"swap\").used = mem.stats.at(\"swap_used\");\n\t\t\t\tdisks.at(\"swap\").free = mem.stats.at(\"swap_free\");\n\t\t\t\tdisks.at(\"swap\").used_percent = mem.percent.at(\"swap_used\").back();\n\t\t\t\tdisks.at(\"swap\").free_percent = mem.percent.at(\"swap_free\").back();\n\t\t\t}\n\t\t\tfor (const auto &name : last_found)\n\t\t\t\tif (not is_in(name, \"/\", \"swap\", \"/dev\"))\n\t\t\t\t\tmem.disks_order.push_back(name);\n\n\t\t\tdisk_ios = 0;\n\t\t\tcollect_disk(disks, mapping);\n\n\t\t\told_uptime = uptime;\n\t\t}\n\t\treturn mem;\n\t}\n\n}  // namespace Mem\n\nnamespace Net {\n\tstd::unordered_map<string, net_info> current_net;\n\tnet_info empty_net = {};\n\tvector<string> interfaces;\n\tstring selected_iface;\n\tint errors = 0;\n\tstd::unordered_map<string, uint64_t> graph_max = {{\"download\", {}}, {\"upload\", {}}};\n\tstd::unordered_map<string, array<int, 2>> max_count = {{\"download\", {}}, {\"upload\", {}}};\n\tbool rescale = true;\n\tuint64_t timestamp = 0;\n\n\tauto collect(bool no_update) -> net_info & {\n\t\tauto &net = current_net;\n\t\tauto &config_iface = Config::getS(\"net_iface\");\n\t\tauto net_sync = Config::getB(\"net_sync\");\n\t\tauto net_auto = Config::getB(\"net_auto\");\n\t\tauto new_timestamp = time_ms();\n\n\t\tif (not no_update and errors < 3) {\n\t\t\t//? Get interface list using getifaddrs() wrapper\n\t\t\tIfAddrsPtr if_addrs {};\n\t\t\tif (if_addrs.get_status() != 0) {\n\t\t\t\terrors++;\n\t\t\t\tLogger::error(\"Net::collect() -> getifaddrs() failed with id {}\", if_addrs.get_status());\n\t\t\t\tredraw = true;\n\t\t\t\treturn empty_net;\n\t\t\t}\n\t\t\tint family = 0;\n\t\t\tstatic_assert(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN); // 46 >= 16, compile-time assurance.\n\t\t\tenum { IPBUFFER_MAXSIZE = INET6_ADDRSTRLEN }; // manually using the known biggest value, guarded by the above static_assert\n\t\t\tchar ip[IPBUFFER_MAXSIZE];\n\t\t\tinterfaces.clear();\n\t\t\tstring ipv4, ipv6;\n\n\t\t\t//? Iteration over all items in getifaddrs() list\n\t\t\tfor (auto *ifa = if_addrs.get(); ifa != nullptr; ifa = ifa->ifa_next) {\n\t\t\t\tif (ifa->ifa_addr == nullptr) continue;\n\t\t\t\tfamily = ifa->ifa_addr->sa_family;\n\t\t\t\tconst auto &iface = ifa->ifa_name;\n\t\t\t\t//? Update available interfaces vector and get status of interface\n\t\t\t\tif (not v_contains(interfaces, iface)) {\n\t\t\t\t\tinterfaces.push_back(iface);\n\t\t\t\t\tnet[iface].connected = (ifa->ifa_flags & IFF_RUNNING);\n\n\t\t\t\t\t// An interface can have more than one IP of the same family associated with it,\n\t\t\t\t\t// but we pick only the first one to show in the NET box.\n\t\t\t\t\t// Note: Interfaces without any IPv4 and IPv6 set are still valid and monitorable!\n\t\t\t\t\tnet[iface].ipv4.clear();\n\t\t\t\t\tnet[iface].ipv6.clear();\n\t\t\t\t}\n\t\t\t\t//? Get IPv4 address\n\t\t\t\tif (family == AF_INET) {\n\t\t\t\t\tif (net[iface].ipv4.empty()) {\n\t\t\t\t\t\tif (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr)->sin_addr), ip, IPBUFFER_MAXSIZE)) {\n\n\t\t\t\t\t\t\tnet[iface].ipv4 = ip;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tint errsv = errno;\n\t\t\t\t\t\t\tLogger::error(\"Net::collect() -> Failed to convert IPv4 to string for iface {}, errno: {}\", iface, strerror(errsv));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? Get IPv6 address\n\t\t\t\telse if (family == AF_INET6) {\n\t\t\t\t\tif (net[iface].ipv6.empty()) {\n\t\t\t\t\t\tif (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr)->sin6_addr), ip, IPBUFFER_MAXSIZE)) {\n\t\t\t\t\t\t\tnet[iface].ipv6 = ip;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tint errsv = errno;\n\t\t\t\t\t\t\tLogger::error(\"Net::collect() -> Failed to convert IPv6 to string for iface {}, errno: {}\", iface, strerror(errsv));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}  //else, ignoring family==AF_LINK (see man 3 getifaddrs)\n\t\t\t}\n\n\t\t\tstd::unordered_map<string, std::tuple<uint64_t, uint64_t>> ifstats;\n\t\t\tint mib[] = {CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, 0};\n\t\t\tsize_t len;\n\t\t\tif (sysctl(mib, 6, nullptr, &len, nullptr, 0) < 0) {\n\t\t\t\tLogger::error(\"failed getting network interfaces\");\n\t\t\t} else {\n\t\t\t\tstd::unique_ptr<char[]> buf(new char[len]);\n\t\t\t\tif (sysctl(mib, 6, buf.get(), &len, nullptr, 0) < 0) {\n\t\t\t\t\tLogger::error(\"failed getting network interfaces\");\n\t\t\t\t} else {\n\t\t\t\t\tchar *lim = buf.get() + len;\n\t\t\t\t\tchar *next = nullptr;\n\t\t\t\t\tfor (next = buf.get(); next < lim;) {\n\t\t\t\t\t\tstruct if_msghdr *ifm = (struct if_msghdr *)next;\n\t\t\t\t\t\tnext += ifm->ifm_msglen;\n\t\t\t\t\t\tstruct if_data ifm_data = ifm->ifm_data;\n\t\t\t\t\t\tif (ifm->ifm_addrs & RTA_IFP) {\n\t\t\t\t\t\t\tstruct sockaddr_dl *sdl = (struct sockaddr_dl *)(ifm + 1);\n\t\t\t\t\t\t\tchar iface[32];\n\t\t\t\t\t\t\tstrncpy(iface, sdl->sdl_data, sdl->sdl_nlen);\n\t\t\t\t\t\t\tiface[sdl->sdl_nlen] = 0;\n\t\t\t\t\t\t\tifstats[iface] = std::tuple(ifm_data.ifi_ibytes, ifm_data.ifi_obytes);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Get total received and transmitted bytes + device address if no ip was found\n\t\t\tfor (const auto &iface : interfaces) {\n\t\t\t\tfor (const string dir : {\"download\", \"upload\"}) {\n\t\t\t\t\tauto &saved_stat = net.at(iface).stat.at(dir);\n\t\t\t\t\tauto &bandwidth = net.at(iface).bandwidth.at(dir);\n\t\t\t\t\tuint64_t val = dir == \"download\" ? std::get<0>(ifstats[iface]) : std::get<1>(ifstats[iface]);\n\n\t\t\t\t\t//? Update speed, total and top values\n\t\t\t\t\tif (val < saved_stat.last) {\n\t\t\t\t\t\tsaved_stat.rollover += saved_stat.last;\n\t\t\t\t\t\tsaved_stat.last = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (cmp_greater((unsigned long long)saved_stat.rollover + (unsigned long long)val, numeric_limits<uint64_t>::max())) {\n\t\t\t\t\t\tsaved_stat.rollover = 0;\n\t\t\t\t\t\tsaved_stat.last = 0;\n\t\t\t\t\t}\n\t\t\t\t\tsaved_stat.speed = round((double)(val - saved_stat.last) / ((double)(new_timestamp - timestamp) / 1000));\n\t\t\t\t\tif (saved_stat.speed > saved_stat.top) saved_stat.top = saved_stat.speed;\n\t\t\t\t\tif (saved_stat.offset > val + saved_stat.rollover) saved_stat.offset = 0;\n\t\t\t\t\tsaved_stat.total = (val + saved_stat.rollover) - saved_stat.offset;\n\t\t\t\t\tsaved_stat.last = val;\n\n\t\t\t\t\t//? Add values to graph\n\t\t\t\t\tbandwidth.push_back(saved_stat.speed);\n\t\t\t\t\twhile (cmp_greater(bandwidth.size(), width * 2)) bandwidth.pop_front();\n\n\t\t\t\t\t//? Set counters for auto scaling\n\t\t\t\t\tif (net_auto and selected_iface == iface) {\n\t\t\t\t\t\tif (saved_stat.speed > graph_max[dir]) {\n\t\t\t\t\t\t\t++max_count[dir][0];\n\t\t\t\t\t\t\tif (max_count[dir][1] > 0) --max_count[dir][1];\n\t\t\t\t\t\t} else if (graph_max[dir] > 10 << 10 and saved_stat.speed < graph_max[dir] / 10) {\n\t\t\t\t\t\t\t++max_count[dir][1];\n\t\t\t\t\t\t\tif (max_count[dir][0] > 0) --max_count[dir][0];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Clean up net map if needed\n\t\t\tif (net.size() > interfaces.size()) {\n\t\t\t\tfor (auto it = net.begin(); it != net.end();) {\n\t\t\t\t\tif (not v_contains(interfaces, it->first))\n\t\t\t\t\t\tit = net.erase(it);\n\t\t\t\t\telse\n\t\t\t\t\t\tit++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttimestamp = new_timestamp;\n\t\t}\n\t\t//? Return empty net_info struct if no interfaces was found\n\t\tif (net.empty())\n\t\t\treturn empty_net;\n\n\t\t//? Find an interface to display if selected isn't set or valid\n\t\tif (selected_iface.empty() or not v_contains(interfaces, selected_iface)) {\n\t\t\tmax_count[\"download\"][0] = max_count[\"download\"][1] = max_count[\"upload\"][0] = max_count[\"upload\"][1] = 0;\n\t\t\tredraw = true;\n\t\t\tif (net_auto) rescale = true;\n\t\t\tif (not config_iface.empty() and v_contains(interfaces, config_iface))\n\t\t\t\tselected_iface = config_iface;\n\t\t\telse {\n\t\t\t\t//? Sort interfaces by total upload + download bytes\n\t\t\t\tauto sorted_interfaces = interfaces;\n\t\t\t\trng::sort(sorted_interfaces, [&](const auto &a, const auto &b) {\n\t\t\t\t\treturn cmp_greater(net.at(a).stat[\"download\"].total + net.at(a).stat[\"upload\"].total,\n\t\t\t\t\t\t\t\t\t   net.at(b).stat[\"download\"].total + net.at(b).stat[\"upload\"].total);\n\t\t\t\t});\n\t\t\t\tselected_iface.clear();\n\t\t\t\t//? Try to set to a connected interface\n\t\t\t\tfor (const auto &iface : sorted_interfaces) {\n\t\t\t\t\tif (net.at(iface).connected) selected_iface = iface;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t//? If no interface is connected set to first available\n\t\t\t\tif (selected_iface.empty() and not sorted_interfaces.empty())\n\t\t\t\t\tselected_iface = sorted_interfaces.at(0);\n\t\t\t\telse if (sorted_interfaces.empty())\n\t\t\t\t\treturn empty_net;\n\t\t\t}\n\t\t}\n\n\t\t//? Calculate max scale for graphs if needed\n\t\tif (net_auto) {\n\t\t\tbool sync = false;\n\t\t\tfor (const auto &dir : {\"download\", \"upload\"}) {\n\t\t\t\tfor (const auto &sel : {0, 1}) {\n\t\t\t\t\tif (rescale or max_count[dir][sel] >= 5) {\n\t\t\t\t\t\tconst long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: net[selected_iface].stat[dir].speed);\n\t\t\t\t\t\tgraph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10);\n\t\t\t\t\t\tmax_count[dir][0] = max_count[dir][1] = 0;\n\t\t\t\t\t\tredraw = true;\n\t\t\t\t\t\tif (net_sync) sync = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? Sync download/upload graphs if enabled\n\t\t\t\tif (sync) {\n\t\t\t\t\tconst auto other = (string(dir) == \"upload\" ? \"download\" : \"upload\");\n\t\t\t\t\tgraph_max[other] = graph_max[dir];\n\t\t\t\t\tmax_count[other][0] = max_count[other][1] = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trescale = false;\n\t\treturn net.at(selected_iface);\n\t}\n}  // namespace Net\n\nnamespace Proc {\n\n\tvector<proc_info> current_procs;\n\tstd::unordered_map<string, string> uid_user;\n\tstring current_sort;\n\tstring current_filter;\n\tbool current_rev = false;\n\tbool is_tree_mode;\n\n\tfs::file_time_type passwd_time;\n\n\tuint64_t cputimes;\n\tint collapse = -1, expand = -1, toggle_children = -1;\n\tuint64_t old_cputimes = 0;\n\tatomic<int> numpids = 0;\n\tint filter_found = 0;\n\n\tdetail_container detailed;\n\tstatic std::unordered_set<size_t> dead_procs;\n\n\tstring get_status(char s) {\n\t\tif (s & SRUN) return \"Running\";\n\t\tif (s & SSLEEP) return \"Sleeping\";\n\t\tif (s & SIDL) return \"Idle\";\n\t\tif (s & SSTOP) return \"Stopped\";\n\t\tif (s & SZOMB) return \"Zombie\";\n\t\treturn \"Unknown\";\n\t}\n\n\t//* Get detailed info for selected process\n\tvoid _collect_details(const size_t pid, vector<proc_info> &procs) {\n\t\tif (pid != detailed.last_pid) {\n\t\t\tdetailed = {};\n\t\t\tdetailed.last_pid = pid;\n\t\t\tdetailed.skip_smaps = not Config::getB(\"proc_info_smaps\");\n\t\t}\n\n\t\t//? Copy proc_info for process from proc vector\n\t\tauto p_info = rng::find(procs, pid, &proc_info::pid);\n\t\tdetailed.entry = *p_info;\n\n\t\t//? Update cpu percent deque for process cpu graph\n\t\tif (not Config::getB(\"proc_per_core\")) detailed.entry.cpu_p *= Shared::coreCount;\n\t\tdetailed.cpu_percent.push_back(clamp((long long)round(detailed.entry.cpu_p), 0ll, 100ll));\n\t\twhile (cmp_greater(detailed.cpu_percent.size(), width)) detailed.cpu_percent.pop_front();\n\n\t\t//? Process runtime : current time - start time (both in unix time - seconds since epoch)\n\t\tstruct timeval currentTime;\n\t\tgettimeofday(&currentTime, nullptr);\n\t\t// only interested in second granularity, so ignoring tc_usec\n\t\tif (detailed.entry.state != 'X') detailed.elapsed = sec_to_dhms(currentTime.tv_sec - detailed.entry.cpu_s);\n\t\telse detailed.elapsed = sec_to_dhms(detailed.entry.death_time);\n\t\tif (detailed.elapsed.size() > 8) detailed.elapsed.resize(detailed.elapsed.size() - 3);\n\n\t\t//? Get parent process name\n\t\tif (detailed.parent.empty()) {\n\t\t\tauto p_entry = rng::find(procs, detailed.entry.ppid, &proc_info::pid);\n\t\t\tif (p_entry != procs.end()) detailed.parent = p_entry->name;\n\t\t}\n\n\t\t//? Expand process status from single char to explanative string\n\t\tdetailed.status = get_status(detailed.entry.state);\n\n\t\tdetailed.mem_bytes.push_back(detailed.entry.mem);\n\t\tdetailed.memory = floating_humanizer(detailed.entry.mem);\n\n\t\tif (detailed.first_mem == -1 or detailed.first_mem < detailed.mem_bytes.back() / 2 or detailed.first_mem > detailed.mem_bytes.back() * 4) {\n\t\t\tdetailed.first_mem = min((uint64_t)detailed.mem_bytes.back() * 2, Mem::get_totalMem());\n\t\t\tredraw = true;\n\t\t}\n\n\t\twhile (cmp_greater(detailed.mem_bytes.size(), width)) detailed.mem_bytes.pop_front();\n\t}\n\n\t//* Collects and sorts process information from /proc\n\tauto collect(bool no_update) -> vector<proc_info> & {\n\t\tconst auto &sorting = Config::getS(\"proc_sorting\");\n\t\tauto reverse = Config::getB(\"proc_reversed\");\n\t\tconst auto &filter = Config::getS(\"proc_filter\");\n\t\tauto per_core = Config::getB(\"proc_per_core\");\n\t\tauto tree = Config::getB(\"proc_tree\");\n\t\tauto show_detailed = Config::getB(\"show_detailed\");\n\t\tconst auto pause_proc_list = Config::getB(\"pause_proc_list\");\n\t\tconst size_t detailed_pid = Config::getI(\"detailed_pid\");\n\t\tbool should_filter = current_filter != filter;\n\t\tif (should_filter) current_filter = filter;\n\t\tbool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter);\n\t\tbool tree_mode_change = tree != is_tree_mode;\n\t\tif (sorted_change) {\n\t\t\tcurrent_sort = sorting;\n\t\t\tcurrent_rev = reverse;\n\t\t}\n\t\tif (tree_mode_change) is_tree_mode = tree;\n\n\t\tconst int cmult = (per_core) ? Shared::coreCount : 1;\n\t\tbool got_detailed = false;\n\n\t\tstatic vector<size_t> found;\n\n\t\t//* Use pids from last update if only changing filter, sorting or tree options\n\t\tif (no_update and not current_procs.empty()) {\n\t\t\tif (show_detailed and detailed_pid != detailed.last_pid) _collect_details(detailed_pid, current_procs);\n\t\t} else {\n\t\t\t//* ---------------------------------------------Collection start----------------------------------------------\n\n\t\t\tshould_filter = true;\n\t\t\tfound.clear();\n\t\t\tstruct timeval currentTime;\n\t\t\tgettimeofday(&currentTime, nullptr);\n\t\t\tconst double timeNow = currentTime.tv_sec + (currentTime.tv_usec / 1'000'000);\n\n\t\t\tint count = 0;\n\t\t\tchar buf[_POSIX2_LINE_MAX];\n\t\t\tShared::KvmPtr kd {kvm_openfiles(nullptr, nullptr, nullptr, KVM_NO_FILES, buf)};\n\t\t\tconst struct kinfo_proc* kprocs = kvm_getprocs(kd.get() , KERN_PROC_ALL, 0, sizeof(struct kinfo_proc), &count);\n\n\t\t\tfor (int i = 0; i < count; i++) {\n\t\t\t\tconst struct kinfo_proc* kproc = &kprocs[i];\n\t\t\t\tconst size_t pid = (size_t)kproc->p_pid;\n\t\t\t\tif (pid < 1) continue;\n\t\t\t\tfound.push_back(pid);\n\n\t\t\t\t//? Check if pid already exists in current_procs\n\t\t\t\tbool no_cache = false;\n\t\t\t\tauto find_old = rng::find(current_procs, pid, &proc_info::pid);\n\t\t\t\t//? Only add new processes if not paused\n\t\t\t\tif (find_old == current_procs.end()) {\n\t\t\t\t\tif (not pause_proc_list) {\n\t\t\t\t\t\tcurrent_procs.push_back({pid});\n\t\t\t\t\t\tfind_old = current_procs.end() - 1;\n\t\t\t\t\t\tno_cache = true;\n\t\t\t\t\t}\n\t\t\t\t\telse continue;\n\t\t\t\t}\n\t\t\t\telse if (dead_procs.contains(pid)) continue;\n\n\t\t\t\tauto &new_proc = *find_old;\n\n\t\t\t\t//? Get program name, command, username, parent pid, nice and status\n\t\t\t\tif (no_cache) {\n\t\t\t\t\tif (string(kproc->p_comm) == \"idle\"s) {\n\t\t\t\t\t\tcurrent_procs.pop_back();\n\t\t\t\t\t\tfound.pop_back();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tnew_proc.name = kproc->p_comm;\n\t\t\t\t\tchar** argv = kvm_getargv(kd.get(), kproc, 0);\n\t\t\t\t\tif (argv) {\n\t\t\t\t\t\tfor (int i = 0; argv[i] and cmp_less(new_proc.cmd.size(), 1000); i++) {\n\t\t\t\t\t\t\tnew_proc.cmd += argv[i] + \" \"s;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (not new_proc.cmd.empty()) new_proc.cmd.pop_back();\n\t\t\t\t\t}\n\t\t\t\t\tif (new_proc.cmd.empty()) new_proc.cmd = new_proc.name;\n\t\t\t\t\tif (new_proc.cmd.size() > 1000) {\n\t\t\t\t\t\tnew_proc.cmd.resize(1000);\n\t\t\t\t\t\tnew_proc.cmd.shrink_to_fit();\n\t\t\t\t\t}\n\t\t\t\t\tnew_proc.ppid = kproc->p_ppid;\n\t\t\t\t\tnew_proc.cpu_s = round(kproc->p_ustart_sec);\n\t\t\t\t\tstruct passwd *pwd = getpwuid(kproc->p_uid);\n\t\t\t\t\tif (pwd)\n\t\t\t\t\t\tnew_proc.user = pwd->pw_name;\n\t\t\t\t}\n\t\t\t\tnew_proc.p_nice = kproc->p_nice;\n\t\t\t\tnew_proc.state = kproc->p_stat;\n\n\t\t\t\tint cpu_t = 0;\n\t\t\t\tcpu_t \t= kproc->p_uctime_usec * 1'000'000 + kproc->p_uctime_sec;\n\n\t\t\t\tnew_proc.mem = kproc->p_vm_rssize * Shared::pageSize;\n\t\t\t\tnew_proc.threads = 1; // can't seem to find this in kinfo_proc\n\n\t\t\t\t//? Process cpu usage since last update\n\t\t\t\tnew_proc.cpu_p = clamp((100.0 * kproc->p_pctcpu / Shared::kfscale) * cmult, 0.0, 100.0 * Shared::coreCount);\n\n\t\t\t\t//? Process cumulative cpu usage since process start\n\t\t\t\tnew_proc.cpu_c = (double)(cpu_t * Shared::clkTck / 1'000'000) / max(1.0, timeNow - new_proc.cpu_s);\n\n\t\t\t\t//? Update cached value with latest cpu times\n\t\t\t\tnew_proc.cpu_t = cpu_t;\n\n\t\t\t\tif (show_detailed and not got_detailed and new_proc.pid == detailed_pid) {\n\t\t\t\t\tgot_detailed = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Clear dead processes from current_procs if not paused\n\t\t\tif (not pause_proc_list) {\n\t\t\t\tauto eraser = rng::remove_if(current_procs, [&](const auto& element) { return not v_contains(found, element.pid); });\n\t\t\t\tcurrent_procs.erase(eraser.begin(), eraser.end());\n\t\t\t\tif (!dead_procs.empty()) dead_procs.clear();\n\t\t\t}\n\t\t\t//? Set correct state of dead processes if paused\n\t\t\telse {\n\t\t\t\tconst bool keep_dead_proc_usage = Config::getB(\"keep_dead_proc_usage\");\n\t\t\t\tfor (auto& r : current_procs) {\n\t\t\t\t\tif (rng::find(found, r.pid) == found.end()) {\n\t\t\t\t\t\tif (r.state != 'X') {\n\t\t\t\t\t\t\tstruct timeval currentTime;\n\t\t\t\t\t\t\tgettimeofday(&currentTime, nullptr);\n\t\t\t\t\t\t\tr.death_time = currentTime.tv_sec - r.cpu_s;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tr.state = 'X';\n\t\t\t\t\t\tdead_procs.emplace(r.pid);\n\t\t\t\t\t\t//? Reset cpu usage for dead processes if paused and option is set\n\t\t\t\t\t\tif (!keep_dead_proc_usage) {\n\t\t\t\t\t\t\tr.cpu_p = 0.0;\n\t\t\t\t\t\t\tr.mem = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Update the details info box for process if active\n\t\t\tif (show_detailed and got_detailed) {\n\t\t\t\t_collect_details(detailed_pid, current_procs);\n\t\t\t} else if (show_detailed and not got_detailed and detailed.status != \"Dead\") {\n\t\t\t\tdetailed.status = \"Dead\";\n\t\t\t\tredraw = true;\n\t\t\t}\n\n\t\t\told_cputimes = cputimes;\n\n\t\t}\n\n\t\t//* ---------------------------------------------Collection done-----------------------------------------------\n\n\t\t//* Match filter if defined\n\t\tif (should_filter) {\n\t\t\tfilter_found = 0;\n\t\t\tfor (auto& p : current_procs) {\n\t\t\t\tif (not tree and not filter.empty()) {\n\t\t\t\t\tif (!matches_filter(p, filter)) {\n\t\t\t\t\t\tp.filtered = true;\n\t\t\t\t\t\tfilter_found++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tp.filtered = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tp.filtered = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//* Sort processes\n\t\tif ((sorted_change or tree_mode_change) or (not no_update and not pause_proc_list)) {\n\t\t\tproc_sorter(current_procs, sorting, reverse, tree);\n\t\t}\n\n\t\t//* Generate tree view if enabled\n\t\tif (tree and (not no_update or should_filter or sorted_change)) {\n\t\t\tbool locate_selection = false;\n\n\t\t\tif (toggle_children != -1) {\n\t\t\t\tauto collapser = rng::find(current_procs, toggle_children, &proc_info::pid);\n\t\t\t\tif (collapser != current_procs.end()){\n\t\t\t\t\tfor (auto& p : current_procs) {\n\t\t\t\t\t\tif (p.ppid == collapser->pid) {\n\t\t\t\t\t\t\tauto child = rng::find(current_procs, p.pid, &proc_info::pid);\n\t\t\t\t\t\t\tif (child != current_procs.end()){\n\t\t\t\t\t\t\t\tchild->collapsed = not child->collapsed;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (Config::ints.at(\"proc_selected\") > 0) locate_selection = true;\n\t\t\t\t}\n\t\t\t\ttoggle_children = -1;\n\t\t\t}\n\t\t\t\n\t\t\tif (auto find_pid = (collapse != -1 ? collapse : expand); find_pid != -1) {\n\t\t\t\tauto collapser = rng::find(current_procs, find_pid, &proc_info::pid);\n\t\t\t\tif (collapser != current_procs.end()) {\n\t\t\t\t\tif (collapse == expand) {\n\t\t\t\t\t\tcollapser->collapsed = not collapser->collapsed;\n\t\t\t\t\t}\n\t\t\t\t\telse if (collapse > -1) {\n\t\t\t\t\t\tcollapser->collapsed = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (expand > -1) {\n\t\t\t\t\t\tcollapser->collapsed = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (Config::ints.at(\"proc_selected\") > 0) locate_selection = true;\n\t\t\t\t}\n\t\t\t\tcollapse = expand = -1;\n\t\t\t}\n\t\t\tif (should_filter or not filter.empty()) filter_found = 0;\n\n\t\t\tvector<tree_proc> tree_procs;\n\t\t\ttree_procs.reserve(current_procs.size());\n\n\t\t\tif (!pause_proc_list) {\n\t\t\t\tfor (auto& p : current_procs) {\n\t\t\t\t\tif (not v_contains(found, p.ppid)) p.ppid = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Stable sort to retain selected sorting among processes with the same parent\n\t\t\trng::stable_sort(current_procs, rng::less{}, & proc_info::ppid);\n\n\t\t\t//? Start recursive iteration over processes with the lowest shared parent pids\n\t\t\tfor (auto& p : rng::equal_range(current_procs, current_procs.at(0).ppid, rng::less{}, &proc_info::ppid)) {\n\t\t\t\t_tree_gen(p, current_procs, tree_procs, 0, false, filter, false, no_update, should_filter);\n\t\t\t}\n\n\t\t\t//? Recursive sort over tree structure to account for collapsed processes in the tree\n\t\t\tint index = 0;\n\t\t\ttree_sort(tree_procs, sorting, reverse, (pause_proc_list and not (sorted_change or tree_mode_change)), index, current_procs.size());\n\n\t\t\t//? Recursive construction of ASCII tree prefixes.\n\t\t\tfor (auto t = tree_procs.begin(); t != tree_procs.end(); ++t) {\n\t\t\t\t_collect_prefixes(*t, t == tree_procs.end() - 1);\n\t\t\t}\n\n\t\t\t//? Final sort based on tree index\n\t\t\trng::stable_sort(current_procs, rng::less {}, &proc_info::tree_index);\n\n\t\t\t//? Move current selection/view to the selected process when collapsing/expanding in the tree\n\t\t\tif (locate_selection) {\n\t\t\t\tint loc = rng::find(current_procs, Proc::selected_pid, &proc_info::pid)->tree_index;\n\t\t\t\tif (Config::ints.at(\"proc_start\") >= loc or Config::ints.at(\"proc_start\") <= loc - Proc::select_max)\n\t\t\t\t\tConfig::ints.at(\"proc_start\") = max(0, loc - 1);\n\t\t\t\tConfig::ints.at(\"proc_selected\") = loc - Config::ints.at(\"proc_start\") + 1;\n\t\t\t}\n\t\t}\n\n\t\tnumpids = (int)current_procs.size() - filter_found;\n\t\treturn current_procs;\n\t}\n}  // namespace Proc\n\nnamespace Tools {\n\tdouble system_uptime() {\n\t\tstruct timeval ts, currTime;\n\t\tstd::size_t len = sizeof(ts);\n\t\tint mib[2] = {CTL_KERN, KERN_BOOTTIME};\n\t\tif (sysctl(mib, 2, &ts, &len, nullptr, 0) != -1) {\n\t\t\tgettimeofday(&currTime, nullptr);\n\t\t\treturn currTime.tv_sec - ts.tv_sec;\n\t\t}\n\t\treturn 0.0;\n\t}\n}  // namespace Tools\n"
  },
  {
    "path": "src/openbsd/internal.h",
    "content": "/*\n * Copyright (c) 2019-2021 Brian Callahan <bcallah@openbsd.org>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\nstruct sysctls {\n\tconst char *name;\n\tint mib0;\n\tint mib1;\n\tint mib2;\n} sysctlnames[] = {\n\t{ \"hw.machine\",\t\tCTL_HW,\t\tHW_MACHINE,\t\t0 },\n\t{ \"hw.model\",\t\tCTL_HW,\t\tHW_MODEL,\t\t0 },\n\t{ \"hw.ncpu\",\t\tCTL_HW,\t\tHW_NCPU,\t\t0 },\n\t{ \"hw.byteorder\",\tCTL_HW,\t\tHW_BYTEORDER,\t\t0 },\n\t{ \"hw.pagesize\",\tCTL_HW,\t\tHW_PAGESIZE,\t\t0 },\n\t{ \"hw.disknames\",\tCTL_HW,\t\tHW_DISKNAMES,\t\t0 },\n\t{ \"hw.diskcount\",\tCTL_HW,\t\tHW_DISKCOUNT,\t\t0 },\n\t{ \"hw.sensors\",\t\tCTL_HW,\t\tHW_SENSORS,\t\t0 },\n\t{ \"hw.model\",\t\tCTL_HW,\t\tHW_MODEL,\t\t0 },\n\t{ \"hw.ncpu\",\t\tCTL_HW,\t\tHW_NCPU,\t\t0 },\n\t{ \"hw.byteorder\",\tCTL_HW,\t\tHW_BYTEORDER,\t\t0 },\n\t{ \"hw.pagesize\",\tCTL_HW,\t\tHW_PAGESIZE,\t\t0 },\n\t{ \"hw.disknames\",\tCTL_HW,\t\tHW_DISKNAMES,\t\t0 },\n\t{ \"hw.diskcount\",\tCTL_HW,\t\tHW_DISKCOUNT,\t\t0 },\n\t{ \"hw.sensors\",\t\tCTL_HW,\t\tHW_SENSORS,\t\t0 },\n\t{ \"hw.cpuspeed\",\tCTL_HW,\t\tHW_CPUSPEED,\t\t0 },\n\t{ \"hw.setperf\",\t\tCTL_HW,\t\tHW_SETPERF,\t\t0 },\n\t{ \"hw.vendor\",\t\tCTL_HW,\t\tHW_VENDOR,\t\t0 },\n\t{ \"hw.product\",\t\tCTL_HW,\t\tHW_PRODUCT,\t\t0 },\n\t{ \"hw.serialno\",\tCTL_HW,\t\tHW_SERIALNO,\t\t0 },\n\t{ \"hw.uuid\",\t\tCTL_HW,\t\tHW_UUID,\t\t0 },\n\t{ \"hw.physmem\",\t\tCTL_HW,\t\tHW_PHYSMEM64,\t\t0 },\n\t{ \"hw.usermem\",\t\tCTL_HW,\t\tHW_USERMEM64,\t\t0 },\n\t{ \"hw.ncpufound\",\tCTL_HW,\t\tHW_NCPUFOUND,\t\t0 },\n\t{ \"hw.allowpowerdown\",\tCTL_HW,\t\tHW_ALLOWPOWERDOWN,\t0 },\n\t{ \"hw.perfpolicy\",\tCTL_HW,\t\tHW_PERFPOLICY,\t\t0 },\n\t{ \"hw.smt\",\t\tCTL_HW,\t\tHW_SMT,\t\t\t0 },\n\t{ \"hw.ncpuonline\",\tCTL_HW,\t\tHW_NCPUONLINE,\t\t0 },\n\t{ \"hw.cpuspeed\",\tCTL_HW,\t\tHW_CPUSPEED,\t\t0 },\n\t{ \"hw.setperf\",\t\tCTL_HW,\t\tHW_SETPERF,\t\t0 },\n\t{ \"hw.vendor\",\t\tCTL_HW,\t\tHW_VENDOR,\t\t0 },\n\t{ \"hw.product\",\t\tCTL_HW,\t\tHW_PRODUCT,\t\t0 },\n\t{ \"hw.serialno\",\tCTL_HW,\t\tHW_SERIALNO,\t\t0 },\n\t{ \"hw.uuid\",\t\tCTL_HW,\t\tHW_UUID,\t\t0 },\n\t{ \"hw.physmem\",\t\tCTL_HW,\t\tHW_PHYSMEM64,\t\t0 },\n\t{ \"hw.usermem\",\t\tCTL_HW,\t\tHW_USERMEM64,\t\t0 },\n\t{ \"hw.ncpufound\",\tCTL_HW,\t\tHW_NCPUFOUND,\t\t0 },\n\t{ \"hw.allowpowerdown\",\tCTL_HW,\t\tHW_ALLOWPOWERDOWN,\t0 },\n\t{ \"hw.perfpolicy\",\tCTL_HW,\t\tHW_PERFPOLICY,\t\t0 },\n\t{ \"hw.smt\",\t\tCTL_HW,\t\tHW_SMT,\t\t\t0 },\n\t{ \"hw.ncpuonline\",\tCTL_HW,\t\tHW_NCPUONLINE,\t\t0 },\n\t{ \"kern.ostype\",\tCTL_KERN,\tKERN_OSTYPE,\t\t0 },\n\t{ \"kern.osrelease\",\tCTL_KERN,\tKERN_OSRELEASE,\t\t0 },\n\t{ \"kern.osrevision\",\tCTL_KERN,\tKERN_OSREV,\t\t0 },\n\t{ \"kern.version\",\tCTL_KERN,\tKERN_VERSION,\t\t0 },\n\t{ \"kern.maxvnodes\",\tCTL_KERN,\tKERN_MAXVNODES,\t\t0 },\n\t{ \"kern.maxproc\",\tCTL_KERN,\tKERN_MAXPROC,\t\t0 },\n\t{ \"kern.maxfiles\",\tCTL_KERN,\tKERN_MAXFILES,\t\t0 },\n\t{ \"kern.argmax\",\tCTL_KERN,\tKERN_ARGMAX,\t\t0 },\n\t{ \"kern.securelevel\",\tCTL_KERN,\tKERN_SECURELVL,\t\t0 },\n\t{ \"kern.hostname\",\tCTL_KERN,\tKERN_HOSTNAME,\t\t0 },\n\t{ \"kern.hostid\",\tCTL_KERN,\tKERN_HOSTID,\t\t0 },\n\t{ \"kern.clockrate\",\tCTL_KERN,\tKERN_CLOCKRATE,\t\t0 },\n\t{ \"kern.profiling\",\tCTL_KERN,\tKERN_PROF,\t\t0 },\n\t{ \"kern.posix1version\",\tCTL_KERN,\tKERN_POSIX1,\t\t0 },\n\t{ \"kern.ngroups\",\tCTL_KERN,\tKERN_NGROUPS,\t\t0 },\n\t{ \"kern.job_control\",\tCTL_KERN,\tKERN_JOB_CONTROL,\t0 },\n\t{ \"kern.saved_ids\",\tCTL_KERN,\tKERN_SAVED_IDS,\t\t0 },\n\t{ \"kern.boottime\",\tCTL_KERN,\tKERN_BOOTTIME,\t\t0 },\n\t{ \"kern.domainname\",\tCTL_KERN,\tKERN_DOMAINNAME,\t0 },\n\t{ \"kern.maxpartitions\",\tCTL_KERN,\tKERN_MAXPARTITIONS,\t0 },\n\t{ \"kern.rawpartition\",\tCTL_KERN,\tKERN_RAWPARTITION,\t0 },\n\t{ \"kern.maxthread\",\tCTL_KERN,\tKERN_MAXTHREAD,\t\t0 },\n\t{ \"kern.nthreads\",\tCTL_KERN,\tKERN_NTHREADS,\t\t0 },\n\t{ \"kern.osversion\",\tCTL_KERN,\tKERN_OSVERSION,\t\t0 },\n\t{ \"kern.somaxconn\",\tCTL_KERN,\tKERN_SOMAXCONN,\t\t0 },\n\t{ \"kern.sominconn\",\tCTL_KERN,\tKERN_SOMINCONN,\t\t0 },\n\t{ \"kern.nosuidcoredump\", CTL_KERN,\tKERN_NOSUIDCOREDUMP,\t0 },\n\t{ \"kern.fsync\",\t\tCTL_KERN,\tKERN_FSYNC,\t\t0 },\n\t{ \"kern.sysvmsg\",\tCTL_KERN,\tKERN_SYSVMSG,\t\t0 },\n\t{ \"kern.sysvsem\",\tCTL_KERN,\tKERN_SYSVSEM,\t\t0 },\n\t{ \"kern.sysvshm\",\tCTL_KERN,\tKERN_SYSVSHM,\t\t0 },\n\t{ \"kern.msgbufsize\",\tCTL_KERN,\tKERN_MSGBUFSIZE,\t0 },\n\t{ \"kern.malloc\",\tCTL_KERN,\tKERN_MALLOCSTATS,\t0 },\n\t{ \"kern.cp_time\",\tCTL_KERN,\tKERN_CPTIME,\t\t0 },\n\t{ \"kern.nchstats\",\tCTL_KERN,\tKERN_NCHSTATS,\t\t0 },\n\t{ \"kern.forkstat\",\tCTL_KERN,\tKERN_FORKSTAT,\t\t0 },\n\t{ \"kern.tty\",\t\tCTL_KERN,\tKERN_TTY,\t\t0 },\n\t{ \"kern.ccpu\",\t\tCTL_KERN,\tKERN_CCPU,\t\t0 },\n\t{ \"kern.fscale\",\tCTL_KERN,\tKERN_FSCALE,\t\t0 },\n\t{ \"kern.nprocs\",\tCTL_KERN,\tKERN_NPROCS,\t\t0 },\n\t{ \"kern.msgbuf\",\tCTL_KERN,\tKERN_MSGBUF,\t\t0 },\n\t{ \"kern.pool\",\t\tCTL_KERN,\tKERN_POOL,\t\t0 },\n\t{ \"kern.stackgap_random\", CTL_KERN,\tKERN_STACKGAPRANDOM,\t0 },\n\t{ \"kern.sysvipc_info\",\tCTL_KERN,\tKERN_SYSVIPC_INFO,\t0 },\n\t{ \"kern.allowkmem\",\tCTL_KERN,\tKERN_ALLOWKMEM,\t\t0 },\n\t{ \"kern.witnesswatch\",\tCTL_KERN,\tKERN_WITNESSWATCH,\t0 },\n\t{ \"kern.splassert\",\tCTL_KERN,\tKERN_SPLASSERT,\t\t0 },\n\t{ \"kern.procargs\",\tCTL_KERN,\tKERN_PROC_ARGS,\t\t0 },\n\t{ \"kern.nfiles\",\tCTL_KERN,\tKERN_NFILES,\t\t0 },\n\t{ \"kern.ttycount\",\tCTL_KERN,\tKERN_TTYCOUNT,\t\t0 },\n\t{ \"kern.numvnodes\",\tCTL_KERN,\tKERN_NUMVNODES,\t\t0 },\n\t{ \"kern.mbstat\",\tCTL_KERN,\tKERN_MBSTAT,\t\t0 },\n\t{ \"kern.witness\",\tCTL_KERN,\tKERN_WITNESS,\t\t0 },\n\t{ \"kern.seminfo\",\tCTL_KERN,\tKERN_SEMINFO,\t\t0 },\n\t{ \"kern.shminfo\",\tCTL_KERN,\tKERN_SHMINFO,\t\t0 },\n\t{ \"kern.intrcnt\",\tCTL_KERN,\tKERN_INTRCNT,\t\t0 },\n\t{ \"kern.watchdog\",\tCTL_KERN,\tKERN_WATCHDOG,\t\t0 },\n\t{ \"kern.proc\",\t\tCTL_KERN,\tKERN_PROC,\t\t0 },\n\t{ \"kern.maxclusters\",\tCTL_KERN,\tKERN_MAXCLUSTERS,\t0 },\n\t{ \"kern.evcount\",\tCTL_KERN,\tKERN_EVCOUNT,\t\t0 },\n\t{ \"kern.timecounter\",\tCTL_KERN,\tKERN_TIMECOUNTER,\t0 },\n\t{ \"kern.maxlocksperuid\", CTL_KERN,\tKERN_MAXLOCKSPERUID,\t0 },\n\t{ \"kern.cp_time2\",\t CTL_KERN,\tKERN_CPTIME2,\t\t0 },\n\t{ \"kern.bufcachepercent\", CTL_KERN,\tKERN_CACHEPCT,\t\t0 },\n\t{ \"kern.file\",\t\tCTL_KERN,\tKERN_FILE,\t\t0 },\n\t{ \"kern.wxabort\",\tCTL_KERN,\tKERN_WXABORT,\t\t0 },\n\t{ \"kern.consdev\",\tCTL_KERN,\tKERN_CONSDEV,\t\t0 },\n\t{ \"kern.netlivelocks\",\tCTL_KERN,\tKERN_NETLIVELOCKS,\t0 },\n\t{ \"kern.pool_debug\",\tCTL_KERN,\tKERN_POOL_DEBUG,\t0 },\n\t{ \"kern.proc_cwd\",\tCTL_KERN,\tKERN_PROC_CWD,\t\t0 },\n\t{ \"kern.proc_nobroadcastkill\", CTL_KERN, KERN_PROC_NOBROADCASTKILL, 0 },\n\t{ \"kern.proc_vmap\",\tCTL_KERN,\tKERN_PROC_VMMAP,\t0 },\n\t{ \"kern.global_ptrace\",\tCTL_KERN,\tKERN_GLOBAL_PTRACE,\t0 },\n\t{ \"kern.consbufsize\",\tCTL_KERN,\tKERN_CONSBUFSIZE,\t0 },\n\t{ \"kern.consbuf\",\tCTL_KERN,\tKERN_CONSBUF,\t\t0 },\n\t{ \"kern.audio\",\t\tCTL_KERN,\tKERN_AUDIO,\t\t0 },\n\t{ \"kern.cpustats\",\tCTL_KERN,\tKERN_CPUSTATS,\t\t0 },\n\t{ \"kern.pfstatus\",\tCTL_KERN,\tKERN_PFSTATUS,\t\t0 },\n\t{ \"kern.timeout_stats\",\tCTL_KERN,\tKERN_TIMEOUT_STATS,\t0 },\n\t{ \"kern.utc_offset\",\tCTL_KERN,\tKERN_UTC_OFFSET,\t0 },\n\t{ \"vm.vmmeter\",\t\tCTL_VM,\t\tVM_METER,\t\t0 },\n\t{ \"vm.loadavg\",\t\tCTL_VM,\t\tVM_LOADAVG,\t\t0 },\n\t{ \"vm.psstrings\",\tCTL_VM,\t\tVM_PSSTRINGS,\t\t0 },\n\t{ \"vm.uvmexp\",\t\tCTL_VM,\t\tVM_UVMEXP,\t\t0 },\n\t{ \"vm.swapencrypt\",\tCTL_VM,\t\tVM_SWAPENCRYPT,\t\t0 },\n\t{ \"vm.nkmempages\",\tCTL_VM,\t\tVM_NKMEMPAGES,\t\t0 },\n\t{ \"vm.anonmin\",\t\tCTL_VM,\t\tVM_ANONMIN,\t\t0 },\n\t{ \"vm.vtextmin\",\tCTL_VM,\t\tVM_VTEXTMIN,\t\t0 },\n\t{ \"vm.vnodemin\",\tCTL_VM,\t\tVM_VNODEMIN,\t\t0 },\n\t{ \"vm.maxslp\",\t\tCTL_VM,\t\tVM_MAXSLP,\t\t0 },\n\t{ \"vm.uspace\",\t\tCTL_VM,\t\tVM_USPACE,\t\t0 },\n\t{ \"vm.malloc_conf\",\tCTL_VM,\t\tVM_MALLOC_CONF,\t\t0 },\n\t{ NULL,\t\t\t0,\t\t0,\t\t\t0 },\n};\n"
  },
  {
    "path": "src/openbsd/sysctlbyname.cpp",
    "content": "/*\n * Copyright (c) 2019-2021 Brian Callahan <bcallah@openbsd.org>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n#include <sys/types.h>\n#include <sys/sysctl.h>\n\n#include <errno.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"internal.h\"\n#include \"../btop_tools.hpp\"\n\nint\nsysctlbyname(const char *name, void *oldp, size_t *oldlenp,\n    void *newp, size_t newlen)\n{\n\tint i, mib[2];\n\n\tfor (i = 0; i < 132; i++) {\n\t// for (i = 0; i < sizeof(sysctlnames) / sizeof(sysctlnames[0]); i++) {\n\t\tif (!strcmp(name, sysctlnames[i].name)) {\n\t\t\tmib[0] = sysctlnames[i].mib0;\n\t\t\tmib[1] = sysctlnames[i].mib1;\n\n\t\t\treturn sysctl(mib, 2, oldp, oldlenp, newp, newlen);\n\t\t}\n\t}\n\n\terrno = ENOENT;\n\n\treturn (-1);\n}\n"
  },
  {
    "path": "src/openbsd/sysctlbyname.h",
    "content": "/*\n * Copyright (c) 2019 Brian Callahan <bcallah@openbsd.org>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n#include <sys/types.h>\n#include <sys/sysctl.h>\n\nextern int sysctlbyname(const char *, void *, size_t *, void *, size_t);\n"
  },
  {
    "path": "src/osx/btop_collect.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include <Availability.h>\n#include <CoreFoundation/CoreFoundation.h>\n#include <IOKit/IOKitLib.h>\n#include <arpa/inet.h>\n#include <libproc.h>\n#include <mach/mach.h>\n#include <mach/mach_host.h>\n#include <mach/mach_init.h>\n#include <mach/mach_types.h>\n#include <mach/processor_info.h>\n#include <mach/vm_statistics.h>\n#include <mach/mach_time.h>\n// BUGS\n//     If both <net/if.h> and <ifaddrs.h> are being included, <net/if.h> must be\n//     included before <ifaddrs.h>.\n// from: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/getifaddrs.3.html\n#include <net/if.h>\n#include <ifaddrs.h>\n#include <net/if_dl.h>\n#include <netdb.h>\n#include <netinet/tcp_fsm.h>\n#include <pwd.h>\n#include <sys/socket.h>\n#include <sys/statvfs.h>\n#include <sys/sysctl.h>\n#include <sys/types.h>\n#include <netinet/in.h> // for inet_ntop\n#include <unistd.h>\n#include <stdexcept>\n#include <utility>\n\n#include <cmath>\n#include <fstream>\n#include <mutex>\n#include <numeric>\n#include <ranges>\n#include <regex>\n#include <string>\n#include <unordered_set>\n\n#include <fmt/format.h>\n\n#include \"../btop_config.hpp\"\n#include \"../btop_log.hpp\"\n#include \"../btop_shared.hpp\"\n#include \"../btop_tools.hpp\"\n\n#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504\n#include \"sensors.hpp\"\n#endif\n#include \"smc.hpp\"\n\n#if defined(GPU_SUPPORT)\n#include <dlfcn.h>\n#include <mach/mach_time.h>\n\n//? IOReport C function declarations for Apple Silicon GPU metrics\nextern \"C\" {\n\ttypedef struct IOReportSubscription* IOReportSubscriptionRef;\n\n\tCFDictionaryRef IOReportCopyChannelsInGroup(CFStringRef group, CFStringRef subgroup,\n\t\tuint64_t a, uint64_t b, uint64_t c);\n\tvoid IOReportMergeChannels(CFDictionaryRef a, CFDictionaryRef b, CFTypeRef cfnull);\n\tIOReportSubscriptionRef IOReportCreateSubscription(void* a, CFMutableDictionaryRef b,\n\t\tCFMutableDictionaryRef* c, uint64_t d, CFTypeRef cfnull);\n\tCFDictionaryRef IOReportCreateSamples(IOReportSubscriptionRef sub,\n\t\tCFMutableDictionaryRef chan, CFTypeRef cfnull);\n\tCFDictionaryRef IOReportCreateSamplesDelta(CFDictionaryRef a, CFDictionaryRef b, CFTypeRef cfnull);\n\tCFStringRef IOReportChannelGetGroup(CFDictionaryRef item);\n\tCFStringRef IOReportChannelGetSubGroup(CFDictionaryRef item);\n\tCFStringRef IOReportChannelGetChannelName(CFDictionaryRef item);\n\tint64_t IOReportSimpleGetIntegerValue(CFDictionaryRef item, int32_t idx);\n\tCFStringRef IOReportChannelGetUnitLabel(CFDictionaryRef item);\n\tint32_t IOReportStateGetCount(CFDictionaryRef item);\n\tCFStringRef IOReportStateGetNameForIndex(CFDictionaryRef item, int32_t idx);\n\tint64_t IOReportStateGetResidency(CFDictionaryRef item, int32_t idx);\n\n\t//? IOHIDEvent declarations for GPU temperature\n\ttypedef struct __IOHIDEvent* IOHIDEventRef;\n\ttypedef struct __IOHIDServiceClient* IOHIDServiceClientRef;\n\ttypedef struct __IOHIDEventSystemClient* IOHIDEventSystemClientRef;\n\t#ifdef __LP64__\n\ttypedef double IOHIDFloat;\n\t#else\n\ttypedef float IOHIDFloat;\n\t#endif\n\tIOHIDEventSystemClientRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator);\n\tint IOHIDEventSystemClientSetMatching(IOHIDEventSystemClientRef client, CFDictionaryRef match);\n\tCFArrayRef IOHIDEventSystemClientCopyServices(IOHIDEventSystemClientRef client);\n\tIOHIDEventRef IOHIDServiceClientCopyEvent(IOHIDServiceClientRef sc, int64_t type, int32_t a, int64_t b);\n\tCFStringRef IOHIDServiceClientCopyProperty(IOHIDServiceClientRef service, CFStringRef property);\n\tIOHIDFloat IOHIDEventGetFloatValue(IOHIDEventRef event, int32_t field);\n}\n#endif // GPU_SUPPORT\n\n#if __MAC_OS_X_VERSION_MIN_REQUIRED < 120000\n#define kIOMainPortDefault kIOMasterPortDefault\n#endif\n\nusing std::clamp, std::string_literals::operator\"\"s, std::cmp_equal, std::cmp_less, std::cmp_greater;\nusing std::ifstream, std::numeric_limits, std::streamsize, std::round, std::max, std::min;\nnamespace fs = std::filesystem;\nnamespace rng = std::ranges;\nusing namespace Tools;\n\n//? RAII wrapper for CoreFoundation types — releases via CFRelease() on destruction\ntemplate <typename T>\nstruct CFRef {\n\tT ref;\n\tCFRef() : ref(nullptr) {}\n\tCFRef(T ref) : ref(ref) {}\n\t~CFRef() { if (ref) CFRelease((CFTypeRef)ref); }\n\tCFRef(const CFRef&) = delete;\n\tCFRef& operator=(const CFRef&) = delete;\n\tCFRef(CFRef&& other) noexcept : ref(other.ref) { other.ref = nullptr; }\n\tCFRef& operator=(CFRef&& other) noexcept {\n\t\tif (this != &other) { reset(); ref = other.ref; other.ref = nullptr; }\n\t\treturn *this;\n\t}\n\toperator T() const { return ref; }\n\tT get() const { return ref; }\n\tT* ptr() { return &ref; }\n\tvoid reset(T new_ref = nullptr) {\n\t\tif (ref) CFRelease((CFTypeRef)ref);\n\t\tref = new_ref;\n\t}\n\tT release() { T r = ref; ref = nullptr; return r; }\n};\n\n//? RAII wrapper for IOKit object types — releases via IOObjectRelease() on destruction\nstruct IORef {\n\tio_object_t ref;\n\tIORef() : ref(0) {}\n\tIORef(io_object_t ref) : ref(ref) {}\n\t~IORef() { if (ref) IOObjectRelease(ref); }\n\tIORef(const IORef&) = delete;\n\tIORef& operator=(const IORef&) = delete;\n\toperator io_object_t() const { return ref; }\n\tio_object_t get() const { return ref; }\n\tio_object_t* ptr() { return &ref; }\n};\n\n//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------\n\nnamespace Cpu {\n\tvector<long long> core_old_totals;\n\tvector<long long> core_old_idles;\n\tvector<string> available_fields = {\"Auto\", \"total\"};\n\tvector<string> available_sensors = {\"Auto\"};\n\tcpu_info current_cpu;\n\tbool got_sensors = false, cpu_temp_only = false, supports_watts = false;\n\tint core_offset = 0;\n\n\t//* Populate found_sensors map\n\tbool get_sensors();\n\n\t//* Get current cpu clock speed\n\tstring get_cpuHz();\n\n\t//* Search /proc/cpuinfo for a cpu name\n\tstring get_cpuName();\n\n\tstruct Sensor {\n\t\tfs::path path;\n\t\tstring label;\n\t\tint64_t temp = 0;\n\t\tint64_t high = 0;\n\t\tint64_t crit = 0;\n\t};\n\n\tstring cpu_sensor;\n\tvector<string> core_sensors;\n\tstd::unordered_map<int, int> core_mapping;\n}  // namespace Cpu\n\nnamespace Mem {\n\tdouble old_uptime;\n}\n\n#if defined(GPU_SUPPORT)\nnamespace Gpu {\n\tvector<gpu_info> gpus;\n\n\t//? Stub shutdown for backends not available on macOS\n\tnamespace Nvml { bool shutdown() { return false; } }\n\tnamespace Rsmi { bool shutdown() { return false; } }\n\n\t//? Apple Silicon GPU data collection via IOReport\n\tnamespace AppleSilicon {\n\t\tbool initialized = false;\n\t\tunsigned int device_count = 0;\n\n\t\t//? Forward declaration\n\t\ttemplate <bool is_init>\n\t\tbool collect(gpu_info* gpus_slice);\n\n\t\t//? IOReport subscription state\n\t\tIOReportSubscriptionRef ior_sub = nullptr;\n\t\tCFMutableDictionaryRef ior_chan = nullptr;\n\t\tCFDictionaryRef prev_sample = nullptr;\n\t\tuint64_t prev_sample_time = 0;\n\n\t\t//? GPU frequency table from DVFS\n\t\tvector<uint32_t> gpu_freqs;\n\n\t\tstatic string cfstring_to_string(CFStringRef cfstr) {\n\t\t\tif (not cfstr) return \"\";\n\t\t\tchar buf[256];\n\t\t\tif (CFStringGetCString(cfstr, buf, sizeof(buf), kCFStringEncodingUTF8))\n\t\t\t\treturn string(buf);\n\t\t\treturn \"\";\n\t\t}\n\n\t\tstatic string get_chip_name() {\n\t\t\tchar buf[256];\n\t\t\tsize_t size = sizeof(buf);\n\t\t\tif (sysctlbyname(\"machdep.cpu.brand_string\", buf, &size, nullptr, 0) == 0)\n\t\t\t\treturn string(buf);\n\t\t\treturn \"Apple Silicon GPU\";\n\t\t}\n\n\t\tstatic uint64_t get_mach_time_ms() {\n\t\t\tstatic mach_timebase_info_data_t timebase = {0, 0};\n\t\t\tif (timebase.denom == 0) mach_timebase_info(&timebase);\n\t\t\treturn (mach_absolute_time() * timebase.numer / timebase.denom) / 1000000;\n\t\t}\n\n\t\t//? Read GPU DVFS frequency table from IORegistry pmgr node\n\t\tstatic void get_gpu_freqs_from_pmgr() {\n\t\t\tio_iterator_t iter_raw;\n\t\t\t//? matchDict ownership is consumed by IOServiceGetMatchingServices\n\t\t\tCFMutableDictionaryRef matchDict = IOServiceMatching(\"AppleARMIODevice\");\n\t\t\tif (IOServiceGetMatchingServices(kIOMainPortDefault, matchDict, &iter_raw) != kIOReturnSuccess)\n\t\t\t\treturn;\n\t\t\tIORef iter(iter_raw);\n\n\t\t\tio_object_t entry_raw;\n\t\t\twhile ((entry_raw = IOIteratorNext(iter)) != 0) {\n\t\t\t\tIORef entry(entry_raw);\n\t\t\t\tchar name[128];\n\t\t\t\tif (IORegistryEntryGetName(entry, name) == kIOReturnSuccess and string(name) == \"pmgr\") {\n\t\t\t\t\tCFMutableDictionaryRef props_raw = nullptr;\n\t\t\t\t\tif (IORegistryEntryCreateCFProperties(entry, &props_raw, kCFAllocatorDefault, 0) == kIOReturnSuccess and props_raw) {\n\t\t\t\t\t\tCFRef<CFMutableDictionaryRef> props(props_raw);\n\t\t\t\t\t\tCFDataRef dvfs_data = (CFDataRef)CFDictionaryGetValue(props, CFSTR(\"voltage-states9\"));\n\t\t\t\t\t\tif (dvfs_data) {\n\t\t\t\t\t\t\tauto len = CFDataGetLength(dvfs_data);\n\t\t\t\t\t\t\tauto ptr = CFDataGetBytePtr(dvfs_data);\n\t\t\t\t\t\t\t//? Pairs of (freq, voltage), 4 bytes each\n\t\t\t\t\t\t\tfor (CFIndex i = 0; i + 7 < len; i += 8) {\n\t\t\t\t\t\t\t\tuint32_t freq = 0;\n\t\t\t\t\t\t\t\tmemcpy(&freq, ptr + i, 4);\n\t\t\t\t\t\t\t\tif (freq > 0) gpu_freqs.push_back(freq / (1000 * 1000)); // Hz -> MHz\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tbool init() {\n\t\t\tif (initialized) return false;\n\n\t\t\t//? Get GPU frequency table\n\t\t\tget_gpu_freqs_from_pmgr();\n\n\t\t\t//? Set up IOReport channels for GPU Stats and Energy Model\n\t\t\tCFRef<CFStringRef> gpu_stats_group(CFStringCreateWithCString(kCFAllocatorDefault, \"GPU Stats\", kCFStringEncodingUTF8));\n\t\t\tCFRef<CFStringRef> gpu_perf_subgroup(CFStringCreateWithCString(kCFAllocatorDefault, \"GPU Performance States\", kCFStringEncodingUTF8));\n\t\t\tCFRef<CFStringRef> energy_group(CFStringCreateWithCString(kCFAllocatorDefault, \"Energy Model\", kCFStringEncodingUTF8));\n\n\t\t\tCFRef<CFDictionaryRef> gpu_chan(IOReportCopyChannelsInGroup(gpu_stats_group, gpu_perf_subgroup, 0, 0, 0));\n\t\t\tCFRef<CFDictionaryRef> energy_chan(IOReportCopyChannelsInGroup(energy_group, nullptr, 0, 0, 0));\n\n\t\t\tif (not gpu_chan.get() and not energy_chan.get()) {\n\t\t\t\tLogger::info(\"Apple Silicon GPU: No IOReport channels found, GPU monitoring unavailable\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t//? Merge channels into a single subscription\n\t\t\tif (gpu_chan.get() and energy_chan.get()) {\n\t\t\t\tIOReportMergeChannels(gpu_chan, energy_chan, nullptr);\n\t\t\t}\n\t\t\tCFDictionaryRef base_chan = gpu_chan.get() ? gpu_chan.get() : energy_chan.get();\n\n\t\t\tauto size = CFDictionaryGetCount(base_chan);\n\t\t\tior_chan = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, size, base_chan);\n\n\t\t\t//? Create IOReport subscription\n\t\t\tCFMutableDictionaryRef sub_dict = nullptr;\n\t\t\tior_sub = IOReportCreateSubscription(nullptr, ior_chan, &sub_dict, 0, nullptr);\n\t\t\tif (not ior_sub) {\n\t\t\t\tLogger::warning(\"Apple Silicon GPU: Failed to create IOReport subscription\");\n\t\t\t\tCFRelease(ior_chan);\n\t\t\t\tior_chan = nullptr;\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tdevice_count = 1; //? Apple Silicon has one integrated GPU\n\t\t\tgpus.resize(gpus.size() + device_count);\n\t\t\tgpu_names.resize(gpu_names.size() + device_count);\n\n\t\t\tinitialized = true;\n\n\t\t\t//? Take initial sample for delta computation\n\t\t\tprev_sample = IOReportCreateSamples(ior_sub, ior_chan, nullptr);\n\t\t\tprev_sample_time = get_mach_time_ms();\n\n\t\t\t//? Run init collect to populate names and supported functions\n\t\t\tcollect<1>(gpus.data());\n\n\t\t\treturn true;\n\t\t}\n\n\t\tbool shutdown() {\n\t\t\tif (not initialized) return false;\n\t\t\tif (prev_sample) { CFRelease(prev_sample); prev_sample = nullptr; }\n\t\t\tif (ior_chan) { CFRelease(ior_chan); ior_chan = nullptr; }\n\t\t\tif (ior_sub) { CFRelease((CFTypeRef)ior_sub); ior_sub = nullptr; }\n\t\t\tinitialized = false;\n\t\t\treturn true;\n\t\t}\n\n\t\t//? Read GPU temperature via IOHIDEventSystem thermal sensors\n\t\tstatic long long get_gpu_temp_iohid() {\n\t\t\t#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504\n\t\t\tconstexpr int kHIDPage_AppleVendor = 0xff00;\n\t\t\tconstexpr int kHIDUsage_TemperatureSensor = 5;\n\t\t\tconstexpr int64_t kIOHIDEventTypeTemperature = 15;\n\n\t\t\tCFStringRef keys[2] = { CFSTR(\"PrimaryUsagePage\"), CFSTR(\"PrimaryUsage\") };\n\t\t\tint page = kHIDPage_AppleVendor, usage = kHIDUsage_TemperatureSensor;\n\t\t\tCFRef<CFNumberRef> num0(CFNumberCreate(nullptr, kCFNumberSInt32Type, &page));\n\t\t\tCFRef<CFNumberRef> num1(CFNumberCreate(nullptr, kCFNumberSInt32Type, &usage));\n\t\t\tconst void* values[] = { num0.get(), num1.get() };\n\t\t\tCFRef<CFDictionaryRef> match(CFDictionaryCreate(nullptr,\n\t\t\t\t(const void**)keys, values, 2,\n\t\t\t\t&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));\n\n\t\t\tCFRef<IOHIDEventSystemClientRef> system(IOHIDEventSystemClientCreate(kCFAllocatorDefault));\n\t\t\tif (not system.get()) return -1;\n\t\t\tIOHIDEventSystemClientSetMatching(system, match);\n\t\t\tCFRef<CFArrayRef> services(IOHIDEventSystemClientCopyServices(system));\n\n\t\t\tif (not services.get()) return -1;\n\n\t\t\tdouble gpu_temp_sum = 0;\n\t\t\tint gpu_temp_count = 0;\n\t\t\tlong count = CFArrayGetCount(services);\n\t\t\tfor (long i = 0; i < count; i++) {\n\t\t\t\tauto sc = (IOHIDServiceClientRef)CFArrayGetValueAtIndex(services, i);\n\t\t\t\tif (not sc) continue;\n\t\t\t\tCFRef<CFStringRef> name(IOHIDServiceClientCopyProperty(sc, CFSTR(\"Product\")));\n\t\t\t\tif (not name.get()) continue;\n\t\t\t\tchar buf[200];\n\t\t\t\tCFStringGetCString(name, buf, 200, kCFStringEncodingASCII);\n\t\t\t\tstring n(buf);\n\t\t\t\t//? \"GPU MTR Temp Sensor\" is the standard Apple Silicon GPU temp sensor name\n\t\t\t\tif (n.find(\"GPU\") != string::npos) {\n\t\t\t\t\tCFRef<IOHIDEventRef> event(IOHIDServiceClientCopyEvent(sc, kIOHIDEventTypeTemperature, 0, 0));\n\t\t\t\t\tif (event.get()) {\n\t\t\t\t\t\tdouble temp = IOHIDEventGetFloatValue(event, kIOHIDEventTypeTemperature << 16);\n\t\t\t\t\t\tif (temp > 0 and temp < 150) {\n\t\t\t\t\t\t\tgpu_temp_sum += temp;\n\t\t\t\t\t\t\tgpu_temp_count++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (gpu_temp_count > 0)\n\t\t\t\treturn static_cast<long long>(round(gpu_temp_sum / gpu_temp_count));\n\t\t\t#endif\n\t\t\treturn -1;\n\t\t}\n\n\t\ttemplate <bool is_init>\n\t\tbool collect(gpu_info* gpus_slice) {\n\t\t\tif (not initialized) return false;\n\n\t\t\tif constexpr (is_init) {\n\t\t\t\t//? Device name\n\t\t\t\tstring chip = get_chip_name();\n\t\t\t\tgpu_names[0] = chip + \" GPU\";\n\n\t\t\t\t//? Power max (typical Apple Silicon GPU TDP ~15-20W)\n\t\t\t\tgpus_slice[0].pwr_max_usage = 20000; // 20W in mW\n\t\t\t\tgpu_pwr_total_max += gpus_slice[0].pwr_max_usage;\n\n\t\t\t\t//? Temperature max\n\t\t\t\tgpus_slice[0].temp_max = 110;\n\n\t\t\t\t//? Memory total (unified memory architecture — GPU shares system RAM)\n\t\t\t\tint64_t memsize = 0;\n\t\t\t\tsize_t size = sizeof(memsize);\n\t\t\t\tif (sysctlbyname(\"hw.memsize\", &memsize, &size, nullptr, 0) == 0)\n\t\t\t\t\tgpus_slice[0].mem_total = memsize;\n\n\t\t\t\t//? Supported functions\n\t\t\t\tgpus_slice[0].supported_functions = {\n\t\t\t\t\t.gpu_utilization = true,\n\t\t\t\t\t.mem_utilization = true,\n\t\t\t\t\t.gpu_clock = not gpu_freqs.empty(),\n\t\t\t\t\t.mem_clock = false,\n\t\t\t\t\t.pwr_usage = true,\n\t\t\t\t\t.pwr_state = false,\n\t\t\t\t\t.temp_info = true,\n\t\t\t\t\t.mem_total = true,\n\t\t\t\t\t.mem_used = true,\n\t\t\t\t\t.pcie_txrx = false,\n\t\t\t\t\t.encoder_utilization = false,\n\t\t\t\t\t.decoder_utilization = false\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t//? Take new IOReport sample and compute delta\n\t\t\tCFDictionaryRef cur_sample = IOReportCreateSamples(ior_sub, ior_chan, nullptr);\n\t\t\tif (not cur_sample) return false;\n\n\t\t\tuint64_t cur_time = get_mach_time_ms();\n\t\t\tuint64_t dt = cur_time - prev_sample_time;\n\t\t\tif (dt == 0) dt = 1;\n\n\t\t\tCFRef<CFDictionaryRef> delta;\n\t\t\tif (prev_sample) {\n\t\t\t\tdelta.reset(IOReportCreateSamplesDelta(prev_sample, cur_sample, nullptr));\n\t\t\t\tCFRelease(prev_sample);\n\t\t\t}\n\t\t\tprev_sample = cur_sample;\n\t\t\tprev_sample_time = cur_time;\n\n\t\t\tif (not delta.get()) return false;\n\n\t\t\t//? Parse delta samples\n\t\t\tCFArrayRef channels = (CFArrayRef)CFDictionaryGetValue(delta, CFSTR(\"IOReportChannels\"));\n\t\t\tif (not channels) return false;\n\n\t\t\tlong long gpu_utilization = 0;\n\t\t\tbool got_gpu_util = false;\n\t\t\tdouble gpu_power_watts = 0;\n\t\t\tbool got_gpu_power = false;\n\n\t\t\tlong chan_count = CFArrayGetCount(channels);\n\t\t\tfor (long i = 0; i < chan_count; i++) {\n\t\t\t\tCFDictionaryRef item = (CFDictionaryRef)CFArrayGetValueAtIndex(channels, i);\n\t\t\t\tif (not item) continue;\n\n\t\t\t\tstring group = cfstring_to_string(IOReportChannelGetGroup(item));\n\t\t\t\tstring subgroup = cfstring_to_string(IOReportChannelGetSubGroup(item));\n\t\t\t\tstring channel = cfstring_to_string(IOReportChannelGetChannelName(item));\n\n\t\t\t\t//? GPU utilization from residency states\n\t\t\t\tif (group == \"GPU Stats\" and subgroup == \"GPU Performance States\" and channel == \"GPUPH\") {\n\t\t\t\t\tint32_t state_count = IOReportStateGetCount(item);\n\t\t\t\t\tif (state_count <= 0) continue;\n\n\t\t\t\t\tint64_t total_residency = 0;\n\t\t\t\t\tint64_t active_residency = 0;\n\t\t\t\t\tdouble weighted_freq = 0;\n\n\t\t\t\t\t//? Find offset past IDLE/OFF/DOWN states\n\t\t\t\t\tint offset = 0;\n\t\t\t\t\tfor (int32_t s = 0; s < state_count; s++) {\n\t\t\t\t\t\tstring name = cfstring_to_string(IOReportStateGetNameForIndex(item, s));\n\t\t\t\t\t\tif (name == \"IDLE\" or name == \"OFF\" or name == \"DOWN\")\n\t\t\t\t\t\t\toffset = s + 1;\n\t\t\t\t\t\ttotal_residency += IOReportStateGetResidency(item, s);\n\t\t\t\t\t}\n\n\t\t\t\t\tint freq_count = static_cast<int>(gpu_freqs.size());\n\t\t\t\t\tfor (int32_t s = offset; s < state_count; s++) {\n\t\t\t\t\t\tint64_t res = IOReportStateGetResidency(item, s);\n\t\t\t\t\t\tactive_residency += res;\n\t\t\t\t\t\tint freq_idx = s - offset;\n\t\t\t\t\t\tif (freq_idx < freq_count and active_residency > 0)\n\t\t\t\t\t\t\tweighted_freq += static_cast<double>(res) * gpu_freqs[freq_idx];\n\t\t\t\t\t}\n\n\t\t\t\t\tif (total_residency > 0) {\n\t\t\t\t\t\tdouble usage_ratio = static_cast<double>(active_residency) / static_cast<double>(total_residency);\n\t\t\t\t\t\tgpu_utilization = clamp(static_cast<long long>(round(usage_ratio * 100.0)), 0ll, 100ll);\n\t\t\t\t\t\tgot_gpu_util = true;\n\n\t\t\t\t\t\t//? Calculate average frequency\n\t\t\t\t\t\tif (active_residency > 0 and not gpu_freqs.empty()) {\n\t\t\t\t\t\t\tdouble avg_freq = weighted_freq / static_cast<double>(active_residency);\n\t\t\t\t\t\t\tgpus_slice[0].gpu_clock_speed = static_cast<unsigned int>(round(avg_freq));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//? GPU power from Energy Model\n\t\t\t\tif (group == \"Energy Model\" and channel == \"GPU Energy\") {\n\t\t\t\t\tstring unit = cfstring_to_string(IOReportChannelGetUnitLabel(item));\n\t\t\t\t\tint64_t val = IOReportSimpleGetIntegerValue(item, 0);\n\t\t\t\t\tdouble energy = static_cast<double>(val);\n\t\t\t\t\tdouble divisor = static_cast<double>(dt) / 1000.0; // dt is in ms\n\n\t\t\t\t\tif (unit.find(\"nJ\") != string::npos) energy /= 1e9;\n\t\t\t\t\telse if (unit.find(\"uJ\") != string::npos or unit.find(\"\\xc2\\xb5J\") != string::npos) energy /= 1e6;\n\t\t\t\t\telse if (unit.find(\"mJ\") != string::npos) energy /= 1e3;\n\t\t\t\t\t//? energy is now in Joules\n\n\t\t\t\t\tif (divisor > 0) {\n\t\t\t\t\t\tgpu_power_watts = energy / divisor;\n\t\t\t\t\t\tgot_gpu_power = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Store GPU utilization\n\t\t\tif (got_gpu_util) {\n\t\t\t\tgpus_slice[0].gpu_percent.at(\"gpu-totals\").push_back(gpu_utilization);\n\t\t\t\tgpus_slice[0].mem_utilization_percent.push_back(gpu_utilization);\n\t\t\t}\n\n\t\t\t//? Store power usage (convert W to mW)\n\t\t\tif (got_gpu_power) {\n\t\t\t\tgpus_slice[0].pwr_usage = static_cast<long long>(round(gpu_power_watts * 1000.0));\n\t\t\t\tif (gpus_slice[0].pwr_usage > gpus_slice[0].pwr_max_usage)\n\t\t\t\t\tgpus_slice[0].pwr_max_usage = gpus_slice[0].pwr_usage;\n\t\t\t\tgpus_slice[0].gpu_percent.at(\"gpu-pwr-totals\").push_back(\n\t\t\t\t\tclamp(static_cast<long long>(round(static_cast<double>(gpus_slice[0].pwr_usage) * 100.0 / static_cast<double>(gpus_slice[0].pwr_max_usage))), 0ll, 100ll));\n\t\t\t}\n\n\t\t\t//? GPU temperature\n\t\t\tif (gpus_slice[0].supported_functions.temp_info and Config::getB(\"check_temp\")) {\n\t\t\t\tlong long temp = get_gpu_temp_iohid();\n\t\t\t\tif (temp > 0)\n\t\t\t\t\tgpus_slice[0].temp.push_back(temp);\n\t\t\t}\n\n\t\t\t//? Memory usage (unified memory — report system memory usage)\n\t\t\tif (gpus_slice[0].supported_functions.mem_total) {\n\t\t\t\tvm_size_t page_size;\n\t\t\t\tmach_port_t mach_port = mach_host_self();\n\t\t\t\tvm_statistics64_data_t vm_stats;\n\t\t\t\tmach_msg_type_number_t count = sizeof(vm_stats) / sizeof(natural_t);\n\t\t\t\thost_page_size(mach_port, &page_size);\n\n\t\t\t\tif (host_statistics64(mach_port, HOST_VM_INFO64, (host_info64_t)&vm_stats, &count) == KERN_SUCCESS) {\n\t\t\t\t\tlong long used = (static_cast<int64_t>(vm_stats.active_count)\n\t\t\t\t\t\t+ static_cast<int64_t>(vm_stats.inactive_count)\n\t\t\t\t\t\t+ static_cast<int64_t>(vm_stats.wire_count)\n\t\t\t\t\t\t+ static_cast<int64_t>(vm_stats.speculative_count)\n\t\t\t\t\t\t+ static_cast<int64_t>(vm_stats.compressor_page_count)\n\t\t\t\t\t\t- static_cast<int64_t>(vm_stats.purgeable_count)\n\t\t\t\t\t\t- static_cast<int64_t>(vm_stats.external_page_count)) * static_cast<int64_t>(page_size);\n\t\t\t\t\tif (used < 0) used = 0;\n\t\t\t\t\tgpus_slice[0].mem_used = used;\n\t\t\t\t\tif (gpus_slice[0].mem_total > 0) {\n\t\t\t\t\t\tauto used_pct = static_cast<long long>(round(static_cast<double>(used) * 100.0 / static_cast<double>(gpus_slice[0].mem_total)));\n\t\t\t\t\t\tgpus_slice[0].gpu_percent.at(\"gpu-vram-totals\").push_back(clamp(used_pct, 0ll, 100ll));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\t//? Explicit template instantiations\n\t\ttemplate bool collect<true>(gpu_info*);\n\t\ttemplate bool collect<false>(gpu_info*);\n\t} // namespace AppleSilicon\n\n\t//? Collect data from Apple Silicon GPU\n\tauto collect(bool no_update) -> vector<gpu_info>& {\n\t\tif (Runner::stopping or (no_update and not gpus.empty())) return gpus;\n\n\t\tAppleSilicon::collect<0>(gpus.data());\n\n\t\t//* Calculate averages\n\t\tlong long avg = 0;\n\t\tlong long mem_usage_total = 0;\n\t\tlong long mem_total = 0;\n\t\tlong long pwr_total = 0;\n\t\tfor (auto& gpu : gpus) {\n\t\t\tif (gpu.supported_functions.gpu_utilization and not gpu.gpu_percent.at(\"gpu-totals\").empty())\n\t\t\t\tavg += gpu.gpu_percent.at(\"gpu-totals\").back();\n\t\t\tif (gpu.supported_functions.mem_used)\n\t\t\t\tmem_usage_total += gpu.mem_used;\n\t\t\tif (gpu.supported_functions.mem_total)\n\t\t\t\tmem_total += gpu.mem_total;\n\t\t\tif (gpu.supported_functions.pwr_usage)\n\t\t\t\tpwr_total += gpu.pwr_usage;\n\n\t\t\t//* Trim vectors if there are more values than needed for graphs\n\t\t\tif (width != 0) {\n\t\t\t\twhile (cmp_greater(gpu.gpu_percent.at(\"gpu-totals\").size(), width * 2)) gpu.gpu_percent.at(\"gpu-totals\").pop_front();\n\t\t\t\twhile (cmp_greater(gpu.mem_utilization_percent.size(), width)) gpu.mem_utilization_percent.pop_front();\n\t\t\t\twhile (cmp_greater(gpu.gpu_percent.at(\"gpu-pwr-totals\").size(), width)) gpu.gpu_percent.at(\"gpu-pwr-totals\").pop_front();\n\t\t\t\twhile (cmp_greater(gpu.temp.size(), 18)) gpu.temp.pop_front();\n\t\t\t\twhile (cmp_greater(gpu.gpu_percent.at(\"gpu-vram-totals\").size(), width/2)) gpu.gpu_percent.at(\"gpu-vram-totals\").pop_front();\n\t\t\t}\n\t\t}\n\n\t\tif (not gpus.empty()) {\n\t\t\tshared_gpu_percent.at(\"gpu-average\").push_back(avg / static_cast<long long>(gpus.size()));\n\t\t\tif (mem_total != 0)\n\t\t\t\tshared_gpu_percent.at(\"gpu-vram-total\").push_back(mem_usage_total * 100 / mem_total);\n\t\t\tif (gpu_pwr_total_max != 0)\n\t\t\t\tshared_gpu_percent.at(\"gpu-pwr-total\").push_back(pwr_total * 100 / gpu_pwr_total_max);\n\t\t}\n\n\t\tif (width != 0) {\n\t\t\twhile (cmp_greater(shared_gpu_percent.at(\"gpu-average\").size(), width * 2)) shared_gpu_percent.at(\"gpu-average\").pop_front();\n\t\t\twhile (cmp_greater(shared_gpu_percent.at(\"gpu-vram-total\").size(), width)) shared_gpu_percent.at(\"gpu-vram-total\").pop_front();\n\t\t\twhile (cmp_greater(shared_gpu_percent.at(\"gpu-pwr-total\").size(), width)) shared_gpu_percent.at(\"gpu-pwr-total\").pop_front();\n\t\t}\n\n\t\treturn gpus;\n\t}\n} // namespace Gpu\n#endif // GPU_SUPPORT\n\n\tclass MachProcessorInfo {\n\tpublic:\n\t\tprocessor_info_array_t info_array;\n\t\tmach_msg_type_number_t info_count;\n\t\tMachProcessorInfo() {}\n\t\tvirtual ~MachProcessorInfo() {vm_deallocate(mach_task_self(), (vm_address_t)info_array, (vm_size_t)sizeof(processor_info_array_t) * info_count);}\n\t};\n\nnamespace Shared {\n\n\tfs::path passwd_path;\n\tuint64_t totalMem;\n\tlong pageSize, coreCount, clkTck, physicalCoreCount, arg_max;\n\tdouble machTck;\n\tint totalMem_len;\n\n\tvoid init() {\n\t\t//? Shared global variables init\n\n\t\tcoreCount = sysconf(_SC_NPROCESSORS_ONLN); // this returns all logical cores (threads)\n\t\tif (coreCount < 1) {\n\t\t\tcoreCount = 1;\n\t\t\tLogger::warning(\"Could not determine number of cores, defaulting to 1.\");\n\t\t}\n\n\t\tsize_t physicalCoreCountSize = sizeof(physicalCoreCount);\n\t\tif (sysctlbyname(\"hw.physicalcpu\", &physicalCoreCount, &physicalCoreCountSize, nullptr, 0) < 0) {\n\t\t\tLogger::error(\"Could not get physical core count\");\n\t\t}\n\n\t\tpageSize = sysconf(_SC_PAGE_SIZE);\n\t\tif (pageSize <= 0) {\n\t\t\tpageSize = 4096;\n\t\t\tLogger::warning(\"Could not get system page size. Defaulting to 4096, processes memory usage might be incorrect.\");\n\t\t}\n\n\t\tmach_timebase_info_data_t convf;\n\t\tif (mach_timebase_info(&convf) == KERN_SUCCESS) {\n\t\t\tmachTck = convf.numer / convf.denom;\n\t\t} else {\n\t\t\tLogger::warning(\"Could not get mach clock tick conversion factor. Defaulting to 100, processes cpu usage might be incorrect.\");\n\t\t\tmachTck = 100;\n\t\t}\n\n\t\tclkTck = sysconf(_SC_CLK_TCK);\n\t\tif (clkTck <= 0) {\n\t\t\tclkTck = 100;\n\t\t\tLogger::warning(\"Could not get system clock ticks per second. Defaulting to 100, processes cpu usage might be incorrect.\");\n\t\t}\n\n\t\tint64_t memsize = 0;\n\t\tsize_t size = sizeof(memsize);\n\t\tif (sysctlbyname(\"hw.memsize\", &memsize, &size, nullptr, 0) < 0) {\n\t\t\tLogger::warning(\"Could not get memory size\");\n\t\t}\n\t\ttotalMem = memsize;\n\n\t\t//* Get maximum length of process arguments\n\t\targ_max = sysconf(_SC_ARG_MAX);\n\n\t\t//? Init for namespace Cpu\n\t\tCpu::current_cpu.core_percent.insert(Cpu::current_cpu.core_percent.begin(), Shared::coreCount, {});\n\t\tCpu::current_cpu.temp.insert(Cpu::current_cpu.temp.begin(), Shared::coreCount + 1, {});\n\t\tCpu::core_old_totals.insert(Cpu::core_old_totals.begin(), Shared::coreCount, 0);\n\t\tCpu::core_old_idles.insert(Cpu::core_old_idles.begin(), Shared::coreCount, 0);\n\t\tCpu::collect();\n\t\tfor (auto &[field, vec] : Cpu::current_cpu.cpu_percent) {\n\t\t\tif (not vec.empty() and not v_contains(Cpu::available_fields, field)) Cpu::available_fields.push_back(field);\n\t\t}\n\t\tCpu::cpuName = Cpu::get_cpuName();\n\t\tCpu::got_sensors = Cpu::get_sensors();\n\t\tCpu::core_mapping = Cpu::get_core_mapping();\n\n\t\t//? Init for namespace Gpu\n\t#ifdef GPU_SUPPORT\n\t\tauto shown_gpus = Config::getS(\"shown_gpus\");\n\t\tif (shown_gpus.contains(\"apple\")) {\n\t\t\tGpu::AppleSilicon::init();\n\t\t}\n\n\t\tif (not Gpu::gpu_names.empty()) {\n\t\t\tfor (auto const& [key, _] : Gpu::gpus[0].gpu_percent)\n\t\t\t\tCpu::available_fields.push_back(key);\n\t\t\tfor (auto const& [key, _] : Gpu::shared_gpu_percent)\n\t\t\t\tCpu::available_fields.push_back(key);\n\n\t\t\tusing namespace Gpu;\n\t\t\tcount = gpus.size();\n\t\t\tgpu_b_height_offsets.resize(gpus.size());\n\t\t\tfor (size_t i = 0; i < gpu_b_height_offsets.size(); ++i)\n\t\t\t\tgpu_b_height_offsets[i] = gpus[i].supported_functions.gpu_utilization\n\t\t\t\t\t+ gpus[i].supported_functions.pwr_usage\n\t\t\t\t\t+ (gpus[i].supported_functions.encoder_utilization or gpus[i].supported_functions.decoder_utilization)\n\t\t\t\t\t+ (gpus[i].supported_functions.mem_total or gpus[i].supported_functions.mem_used)\n\t\t\t\t\t\t* (1 + 2*(gpus[i].supported_functions.mem_total and gpus[i].supported_functions.mem_used) + 2*gpus[i].supported_functions.mem_utilization);\n\t\t}\n\t#endif\n\n\t\t//? Init for namespace Mem\n\t\tMem::old_uptime = system_uptime();\n\t\tMem::collect();\n\t}\n\n}  // namespace Shared\n\nnamespace Cpu {\n\tstring cpuName;\n\tstring cpuHz;\n\tbool has_battery = true;\n\tbool macM1 = false;\n\ttuple<int, float, long, string> current_bat;\n\n\tconst array<string, 10> time_names = {\"user\", \"nice\", \"system\", \"idle\"};\n\n\tstd::unordered_map<string, long long> cpu_old = {\n\t\t{\"totals\", 0},\n\t\t{\"idles\", 0},\n\t\t{\"user\", 0},\n\t\t{\"nice\", 0},\n\t\t{\"system\", 0},\n\t\t{\"idle\", 0}\n\t};\n\n\tstring get_cpuName() {\n\t\tstring name;\n\t\tchar buffer[1024];\n\t\tsize_t size = sizeof(buffer);\n\t\tif (sysctlbyname(\"machdep.cpu.brand_string\", &buffer, &size, nullptr, 0) < 0) {\n\t\t\tLogger::error(\"Failed to get CPU name\");\n\t\t\treturn name;\n\t\t}\n\t\treturn trim_name(string(buffer));\n\t}\n\n\tbool get_sensors() {\n\t\tLogger::debug(\"get_sensors(): show_coretemp={} check_temp={}\", Config::getB(\"show_coretemp\"), Config::getB(\"check_temp\"));\n\t\tgot_sensors = false;\n\t\tif (Config::getB(\"show_coretemp\") and Config::getB(\"check_temp\")) {\n#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504\n\t\t\tThermalSensors sensors;\n\t\t\tif (sensors.getSensors() > 0) {\n\t\t\t\tLogger::debug(\"M1 sensors found\");\n\t\t\t\tgot_sensors = true;\n\t\t\t\tcpu_temp_only = true;\n\t\t\t\tmacM1 = true;\n\t\t\t} else {\n#endif\n\t\t\t\t// try SMC (intel)\n\t\t\t\tLogger::debug(\"checking intel\");\n\t\t\t\ttry {\n\t\t\t\t\tSMCConnection smcCon;\n\t\t\t\t\tLogger::debug(\"SMC connection established\");\n\t\t\t\t\tlong long t = smcCon.getTemp(-1);  // check if we have package T\n\t\t\t\t\tif (t > -1) {\n\t\t\t\t\t\tLogger::debug(\"intel sensors found\");\n\t\t\t\t\t\tgot_sensors = true;\n\t\t\t\t\t\tt = smcCon.getTemp(0);\n\t\t\t\t\t\tif (t == -1) {\n\t\t\t\t\t\t\t// for some macs the core offset is 1 - check if we get a sane value with 1\n\t\t\t\t\t\t\tif (smcCon.getTemp(1) > -1) {\n\t\t\t\t\t\t\t\tLogger::debug(\"intel sensors with offset 1\");\n\t\t\t\t\t\t\t\tcore_offset = 1;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tLogger::debug(\"no intel sensors found\");\n\t\t\t\t\t\tgot_sensors = false;\n\t\t\t\t\t}\n\t\t\t\t} catch (std::runtime_error &e) {\n\t\t\t\t\tLogger::debug(\"SMC not available: {}\", e.what());\n\t\t\t\t\t// ignore, we don't have temp (common in VMs)\n\t\t\t\t\tgot_sensors = false;\n\t\t\t\t}\n#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504\n\t\t\t}\n#endif\n\t\t}\n\t\treturn got_sensors;\n\t}\n\n\tvoid update_sensors() {\n\t\tcurrent_cpu.temp_max = 95;  // we have no idea how to get the critical temp\n\t\ttry {\n\t\t\tif (macM1) {\n#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504\n\t\t\t\tThermalSensors sensors;\n\t\t\t\tcurrent_cpu.temp.at(0).push_back(sensors.getSensors());\n\t\t\t\tif (current_cpu.temp.at(0).size() > 20)\n\t\t\t\t\tcurrent_cpu.temp.at(0).pop_front();\n#endif\n\t\t\t} else {\n\t\t\t\tSMCConnection smcCon;\n\t\t\t\tint threadsPerCore = Shared::coreCount / Shared::physicalCoreCount;\n\t\t\t\tlong long packageT = smcCon.getTemp(-1); // -1 returns package T\n\t\t\t\tcurrent_cpu.temp.at(0).push_back(packageT);\n\n\t\t\t\tfor (int core = 0; core < Shared::coreCount; core++) {\n\t\t\t\t\tlong long temp = smcCon.getTemp((core / threadsPerCore) + core_offset); // same temp for all threads of same physical core\n\t\t\t\t\tif (cmp_less(core + 1, current_cpu.temp.size())) {\n\t\t\t\t\t\tcurrent_cpu.temp.at(core + 1).push_back(temp);\n\t\t\t\t\t\tif (current_cpu.temp.at(core + 1).size() > 20)\n\t\t\t\t\t\t\tcurrent_cpu.temp.at(core + 1).pop_front();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (std::runtime_error &e) {\n\t\t\tgot_sensors = false;\n\t\t\tLogger::error(\"failed getting CPU temp\");\n\t\t}\n\t}\n\n\tstring get_cpuHz() {\n\t\tunsigned int freq = 1;\n\t\tsize_t size = sizeof(freq);\n\n\t\tint mib[] = {CTL_HW, HW_CPU_FREQ};\n\n\t\tif (sysctl(mib, 2, &freq, &size, nullptr, 0) < 0) {\n\t\t\t// this fails on Apple Silicon macs. Apparently you're not allowed to know\n\t\t\treturn \"\";\n\t\t}\n\t\treturn std::to_string(freq / 1000.0 / 1000.0 / 1000.0).substr(0, 3);\n\t}\n\n\tauto get_core_mapping() -> std::unordered_map<int, int> {\n\t\tstd::unordered_map<int, int> core_map;\n\t\tif (cpu_temp_only) return core_map;\n\n\t\tnatural_t cpu_count;\n\t\tnatural_t i;\n\t\tMachProcessorInfo info {};\n\t\tkern_return_t error;\n\n\t\terror = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cpu_count, &info.info_array, &info.info_count);\n\t\tif (error != KERN_SUCCESS) {\n\t\t\tLogger::error(\"Failed getting CPU info\");\n\t\t\treturn core_map;\n\t\t}\n\t\tfor (i = 0; i < cpu_count; i++) {\n\t\t\tcore_map[i] = i;\n\t\t}\n\n\t\t//? If core mapping from cpuinfo was incomplete try to guess remainder, if missing completely, map 0-0 1-1 2-2 etc.\n\t\tif (cmp_less(core_map.size(), Shared::coreCount)) {\n\t\t\tif (Shared::coreCount % 2 == 0 and (long) core_map.size() == Shared::coreCount / 2) {\n\t\t\t\tfor (int i = 0, n = 0; i < Shared::coreCount / 2; i++) {\n\t\t\t\t\tif (std::cmp_greater_equal(n, core_sensors.size())) n = 0;\n\t\t\t\t\tcore_map[Shared::coreCount / 2 + i] = n++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcore_map.clear();\n\t\t\t\tfor (int i = 0, n = 0; i < Shared::coreCount; i++) {\n\t\t\t\t\tif (std::cmp_greater_equal(n, core_sensors.size())) n = 0;\n\t\t\t\t\tcore_map[i] = n++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//? Apply user set custom mapping if any\n\t\tconst auto &custom_map = Config::getS(\"cpu_core_map\");\n\t\tif (not custom_map.empty()) {\n\t\t\ttry {\n\t\t\t\tfor (const auto &split : ssplit(custom_map)) {\n\t\t\t\t\tconst auto vals = ssplit(split, ':');\n\t\t\t\t\tif (vals.size() != 2) continue;\n\t\t\t\t\tint change_id = std::stoi(vals.at(0));\n\t\t\t\t\tint new_id = std::stoi(vals.at(1));\n\t\t\t\t\tif (not core_map.contains(change_id) or cmp_greater(new_id, core_sensors.size())) continue;\n\t\t\t\t\tcore_map.at(change_id) = new_id;\n\t\t\t\t}\n\t\t\t} catch (...) {\n\t\t\t}\n\t\t}\n\n\t\treturn core_map;\n\t}\n\n\tclass IOPSInfo_Wrap {\n\t\tCFTypeRef data;\n\tpublic:\n\t\tIOPSInfo_Wrap() { data = IOPSCopyPowerSourcesInfo(); }\n\t\tCFTypeRef& operator()() { return data; }\n\t\t~IOPSInfo_Wrap() { CFRelease(data); }\n\t};\n\n\tclass IOPSList_Wrap {\n\t\tCFArrayRef data;\n\tpublic:\n\t\tIOPSList_Wrap(CFTypeRef cft_ref) { data = IOPSCopyPowerSourcesList(cft_ref); }\n\t\tCFArrayRef& operator()() { return data; }\n\t\t~IOPSList_Wrap() { CFRelease(data); }\n\t};\n\n\tauto get_battery() -> tuple<int, float, long, string> {\n\t\tif (not has_battery) return {0, 0, 0, \"\"};\n\n\t\tuint32_t percent = -1;\n\t\tlong seconds = -1;\n\t\tstring status = \"discharging\";\n\t\tIOPSInfo_Wrap ps_info{};\n\t\tif (ps_info()) {\n\t\t\tIOPSList_Wrap one_ps_descriptor(ps_info());\n\t\t\tif (one_ps_descriptor()) {\n\t\t\t\tif (CFArrayGetCount(one_ps_descriptor())) {\n\t\t\t\t\tCFDictionaryRef one_ps = IOPSGetPowerSourceDescription(ps_info(), CFArrayGetValueAtIndex(one_ps_descriptor(), 0));\n\t\t\t\t\thas_battery = true;\n\t\t\t\t\tCFNumberRef remaining = (CFNumberRef)CFDictionaryGetValue(one_ps, CFSTR(kIOPSTimeToEmptyKey));\n\t\t\t\t\tint32_t estimatedMinutesRemaining;\n\t\t\t\t\tif (remaining) {\n\t\t\t\t\t\tCFNumberGetValue(remaining, kCFNumberSInt32Type, &estimatedMinutesRemaining);\n\t\t\t\t\t\tseconds = estimatedMinutesRemaining * 60;\n\t\t\t\t\t}\n\t\t\t\t\tCFNumberRef charge = (CFNumberRef)CFDictionaryGetValue(one_ps, CFSTR(kIOPSCurrentCapacityKey));\n\t\t\t\t\tif (charge) {\n\t\t\t\t\t\tCFNumberGetValue(charge, kCFNumberSInt32Type, &percent);\n\t\t\t\t\t}\n\t\t\t\t\tCFBooleanRef charging = (CFBooleanRef)CFDictionaryGetValue(one_ps, CFSTR(kIOPSIsChargingKey));\n\t\t\t\t\tif (charging) {\n\t\t\t\t\t\tbool isCharging = CFBooleanGetValue(charging);\n\t\t\t\t\t\tif (isCharging) {\n\t\t\t\t\t\t\tstatus = \"charging\";\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (percent == 100) {\n\t\t\t\t\t\tstatus = \"full\";\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\thas_battery = false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thas_battery = false;\n\t\t\t}\n\t\t}\n\t\treturn {percent, -1, seconds, status};\n\t}\n\n\tauto collect(bool no_update) -> cpu_info & {\n\t\tif (Runner::stopping or (no_update and not current_cpu.cpu_percent.at(\"total\").empty()))\n\t\t\treturn current_cpu;\n\t\tauto &cpu = current_cpu;\n\n\t\tif (getloadavg(cpu.load_avg.data(), cpu.load_avg.size()) < 0) {\n\t\t\tLogger::error(\"failed to get load averages\");\n\t\t}\n\n\t\tnatural_t cpu_count;\n\t\tnatural_t i;\n\t\tkern_return_t error;\n\t\tprocessor_cpu_load_info_data_t *cpu_load_info = nullptr;\n\n\t\tMachProcessorInfo info{};\n\t\terror = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cpu_count, &info.info_array, &info.info_count);\n\t\tif (error != KERN_SUCCESS) {\n\t\t\tLogger::error(\"Failed getting CPU load info\");\n\t\t}\n\t\tcpu_load_info = (processor_cpu_load_info_data_t *)info.info_array;\n\t\tlong long global_totals = 0;\n\t\tlong long global_idles = 0;\n\t\tvector<long long> times_summed = {0, 0, 0, 0};\n\t\tfor (i = 0; i < cpu_count; i++) {\n\t\t\tvector<long long> times;\n\t\t\t//? 0=user, 1=nice, 2=system, 3=idle\n\t\t\tfor (int x = 0; const unsigned int c_state : {CPU_STATE_USER, CPU_STATE_NICE, CPU_STATE_SYSTEM, CPU_STATE_IDLE}) {\n\t\t\t\tauto val = cpu_load_info[i].cpu_ticks[c_state];\n\t\t\t\ttimes.push_back(val);\n\t\t\t\ttimes_summed.at(x++) += val;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t//? All values\n\t\t\t\tconst long long totals = std::accumulate(times.begin(), times.end(), 0ll);\n\n\t\t\t\t//? Idle time\n\t\t\t\tconst long long idles = times.at(3);\n\n\t\t\t\tglobal_totals += totals;\n\t\t\t\tglobal_idles += idles;\n\n\t\t\t\t//? Calculate cpu total for each core\n\t\t\t\tif (i > Shared::coreCount) break;\n\t\t\t\tconst long long calc_totals = max(0ll, totals - core_old_totals.at(i));\n\t\t\t\tconst long long calc_idles = max(0ll, idles - core_old_idles.at(i));\n\t\t\t\tcore_old_totals.at(i) = totals;\n\t\t\t\tcore_old_idles.at(i) = idles;\n\n\t\t\t\tcpu.core_percent.at(i).push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));\n\n\t\t\t\t//? Reduce size if there are more values than needed for graph\n\t\t\t\tif (cpu.core_percent.at(i).size() > 40) cpu.core_percent.at(i).pop_front();\n\n\t\t\t} catch (const std::exception &e) {\n\t\t\t\tLogger::error(\"Cpu::collect() : {}\", e.what());\n\t\t\t\tthrow std::runtime_error(fmt::format(\"collect() : {}\", e.what()));\n\t\t\t}\n\t\t}\n\n\t\tconst long long calc_totals = max(1ll, global_totals - cpu_old.at(\"totals\"));\n\t\tconst long long calc_idles = max(1ll, global_idles - cpu_old.at(\"idles\"));\n\n\t\t//? Populate cpu.cpu_percent with all fields from syscall\n\t\tfor (int ii = 0; const auto &val : times_summed) {\n\t\t\tcpu.cpu_percent.at(time_names.at(ii)).push_back(clamp((long long)round((double)(val - cpu_old.at(time_names.at(ii))) * 100 / calc_totals), 0ll, 100ll));\n\t\t\tcpu_old.at(time_names.at(ii)) = val;\n\n\t\t\t//? Reduce size if there are more values than needed for graph\n\t\t\twhile (cmp_greater(cpu.cpu_percent.at(time_names.at(ii)).size(), width * 2)) cpu.cpu_percent.at(time_names.at(ii)).pop_front();\n\n\t\t\tii++;\n\t\t}\n\n\t\tcpu_old.at(\"totals\") = global_totals;\n\t\tcpu_old.at(\"idles\") = global_idles;\n\n\t\t//? Total usage of cpu\n\t\tcpu.cpu_percent.at(\"total\").push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));\n\n\t\t//? Reduce size if there are more values than needed for graph\n\t\twhile (cmp_greater(cpu.cpu_percent.at(\"total\").size(), width * 2)) cpu.cpu_percent.at(\"total\").pop_front();\n\n\t\tif (Config::getB(\"show_cpu_freq\")) {\n\t\t\tauto hz = get_cpuHz();\n\t\t\tif (hz != \"\") {\n\t\t\t\tcpuHz = hz;\n\t\t\t}\n\t\t}\n\n\t\tif (Config::getB(\"check_temp\") and got_sensors)\n\t\t\tupdate_sensors();\n\n\t\tif (Config::getB(\"show_battery\") and has_battery)\n\t\t\tcurrent_bat = get_battery();\n\n\t\treturn cpu;\n\t}\n}  // namespace Cpu\n\nnamespace Mem {\n\tbool has_swap = false;\n\tvector<string> fstab;\n\tfs::file_time_type fstab_time;\n\tint disk_ios = 0;\n\tvector<string> last_found;\n\tstatic std::mutex iokit_mutex;  // Protect concurrent IOKit calls\n\tstatic std::mutex interface_mutex;  // Protect concurrent interface access during USB device changes\n\n\tmem_info current_mem{};\n\n\tuint64_t get_totalMem() {\n\t\treturn Shared::totalMem;\n\t}\n\n\tint64_t getCFNumber(CFDictionaryRef dict, const void *key) {\n\t\tCFNumberRef ref = (CFNumberRef)CFDictionaryGetValue(dict, key);\n\t\tif (ref) {\n\t\t\tint64_t value;\n\t\t\tCFNumberGetValue(ref, kCFNumberSInt64Type, &value);\n\t\t\treturn value;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tstring getCFString(io_registry_entry_t volumeRef, CFStringRef key) {\n\t\tCFStringRef bsdNameRef = (CFStringRef)IORegistryEntryCreateCFProperty(volumeRef, key, kCFAllocatorDefault, 0);\n\t\tif (bsdNameRef) {\n\t\t\tchar buf[200];\n\t\t\tCFStringGetCString(bsdNameRef, buf, 200, kCFStringEncodingASCII);\n\t\t\tCFRelease(bsdNameRef);\n\t\t\treturn string(buf);\n\t\t}\n\t\treturn \"\";\n\t}\n\n\tbool isWhole(io_registry_entry_t volumeRef) {\n\t\tCFBooleanRef isWhole = (CFBooleanRef)IORegistryEntryCreateCFProperty(volumeRef, CFSTR(\"Whole\"), kCFAllocatorDefault, 0);\n\t\tBoolean val = CFBooleanGetValue(isWhole);\n\t\tCFRelease(isWhole);\n\t\treturn bool(val);\n\t}\n\n\tclass IOObject {\n\t\tpublic:\n\t\t\tIOObject(string name, io_object_t& obj) : name(name), object(obj) {}\n\t\t\tvirtual ~IOObject() { IOObjectRelease(object); }\n\t\tprivate:\n\t\t\tstring name;\n\t\t\tio_object_t &object;\n\t};\n\n\tvoid collect_disk(std::unordered_map<string, disk_info> &disks, std::unordered_map<string, string> &mapping) {\n\t\t// Lock mutex to prevent concurrent IOKit access\n\t\tstd::lock_guard<std::mutex> lock(iokit_mutex);\n\n\t\tio_registry_entry_t drive;\n\t\tio_iterator_t drive_list;\n\n\t\t/* Get the list of all drive objects. */\n\t\tif (IOServiceGetMatchingServices(kIOMainPortDefault,\n\t\t\t\t\t\t\t\t\t\t IOServiceMatching(\"IOMediaBSDClient\"), &drive_list)) {\n\t\t\tLogger::error(\"Error in IOServiceGetMatchingServices()\");\n\t\t\treturn;\n\t\t}\n\t\tauto d = IOObject(\"drive list\", drive_list); // dummy var so it gets destroyed\n\t\twhile ((drive = IOIteratorNext(drive_list)) != 0) {\n\t\t\tauto dr = IOObject(\"drive\", drive);\n\t\t\tio_registry_entry_t volumeRef;\n\t\t\tIORegistryEntryGetParentEntry(drive, kIOServicePlane, &volumeRef);\n\t\t\tif (volumeRef) {\n\t\t\t\tif (!isWhole(volumeRef)) {\n\t\t\t\t\tstring bsdName = getCFString(volumeRef, CFSTR(\"BSD Name\"));\n\t\t\t\t\tstring device = getCFString(volumeRef, CFSTR(\"VolGroupMntFromName\"));\n\t\t\t\t\tif (!mapping.contains(device)) {\n\t\t\t\t\t\tdevice = \"/dev/\" + bsdName; // try again with BSD name - not all volumes seem to have VolGroupMntFromName property\n\t\t\t\t\t}\n\t\t\t\t\tif (device != \"\") {\n\t\t\t\t\t\tif (mapping.contains(device)) {\n\t\t\t\t\t\t\tstring mountpoint = mapping.at(device);\n\t\t\t\t\t\t\tif (disks.contains(mountpoint)) {\n\t\t\t\t\t\t\t\tauto& disk = disks.at(mountpoint);\n\t\t\t\t\t\t\t\tCFDictionaryRef properties;\n\t\t\t\t\t\t\t\tIORegistryEntryCreateCFProperties(volumeRef, (CFMutableDictionaryRef *)&properties, kCFAllocatorDefault, 0);\n\t\t\t\t\t\t\t\tif (properties) {\n\t\t\t\t\t\t\t\t\tCFDictionaryRef statistics = (CFDictionaryRef)CFDictionaryGetValue(properties, CFSTR(\"Statistics\"));\n\t\t\t\t\t\t\t\t\tif (statistics) {\n\t\t\t\t\t\t\t\t\t\tdisk_ios++;\n\t\t\t\t\t\t\t\t\t\tint64_t readBytes = getCFNumber(statistics, CFSTR(\"Bytes read from block device\"));\n\t\t\t\t\t\t\t\t\t\tif (disk.io_read.empty())\n\t\t\t\t\t\t\t\t\t\t\tdisk.io_read.push_back(0);\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\tdisk.io_read.push_back(max((int64_t)0, (readBytes - disk.old_io.at(0))));\n\t\t\t\t\t\t\t\t\t\tdisk.old_io.at(0) = readBytes;\n\t\t\t\t\t\t\t\t\t\twhile (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front();\n\n\t\t\t\t\t\t\t\t\t\tint64_t writeBytes = getCFNumber(statistics, CFSTR(\"Bytes written to block device\"));\n\t\t\t\t\t\t\t\t\t\tif (disk.io_write.empty())\n\t\t\t\t\t\t\t\t\t\t\tdisk.io_write.push_back(0);\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\tdisk.io_write.push_back(max((int64_t)0, (writeBytes - disk.old_io.at(1))));\n\t\t\t\t\t\t\t\t\t\tdisk.old_io.at(1) = writeBytes;\n\t\t\t\t\t\t\t\t\t\twhile (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front();\n\n\t\t\t\t\t\t\t\t\t\t// IOKit does not give us IO times, (use IO read + IO write with 1 MiB being 100% to get some activity indication)\n\t\t\t\t\t\t\t\t\t\tif (disk.io_activity.empty())\n\t\t\t\t\t\t\t\t\t\t\tdisk.io_activity.push_back(0);\n\t\t\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\t\t\tdisk.io_activity.push_back(clamp((long)round((double)(disk.io_write.back() + disk.io_read.back()) / (1 << 20)), 0l, 100l));\n\t\t\t\t\t\t\t\t\t\twhile (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tCFRelease(properties);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tauto collect(bool no_update) -> mem_info & {\n\t\tif (Runner::stopping or (no_update and not current_mem.percent.at(\"used\").empty()))\n\t\t\treturn current_mem;\n\n\t\tauto show_swap = Config::getB(\"show_swap\");\n\t\tauto show_disks = Config::getB(\"show_disks\");\n\t\tauto swap_disk = Config::getB(\"swap_disk\");\n\t\tauto &mem = current_mem;\n\t\tstatic bool snapped = (getenv(\"BTOP_SNAPPED\") != nullptr);\n\n\t\tvm_statistics64 p;\n\t\tmach_msg_type_number_t info_size = HOST_VM_INFO64_COUNT;\n\t\tif (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&p, &info_size) == 0) {\n\t\t\tmem.stats.at(\"free\") = p.free_count * Shared::pageSize;\n\t\t\tmem.stats.at(\"cached\") = p.external_page_count * Shared::pageSize;\n\t\t\tmem.stats.at(\"used\") = (p.active_count + p.wire_count) * Shared::pageSize;\n\t\t\tmem.stats.at(\"available\") = Shared::totalMem - mem.stats.at(\"used\");\n\t\t}\n\n\t\tint mib[2] = {CTL_VM, VM_SWAPUSAGE};\n\n\t\tstruct xsw_usage swap;\n\t\tsize_t len = sizeof(struct xsw_usage);\n\t\tif (sysctl(mib, 2, &swap, &len, nullptr, 0) == 0) {\n\t\t\tmem.stats.at(\"swap_total\") = swap.xsu_total;\n\t\t\tmem.stats.at(\"swap_free\") = swap.xsu_avail;\n\t\t\tmem.stats.at(\"swap_used\") = swap.xsu_used;\n\t\t}\n\n\t\tif (show_swap and mem.stats.at(\"swap_total\") > 0) {\n\t\t\tfor (const auto &name : swap_names) {\n\t\t\t\tmem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / mem.stats.at(\"swap_total\")));\n\t\t\t\twhile (cmp_greater(mem.percent.at(name).size(), width * 2))\n\t\t\t\t\tmem.percent.at(name).pop_front();\n\t\t\t}\n\t\t\thas_swap = true;\n\t\t} else\n\t\t\thas_swap = false;\n\t\t//? Calculate percentages\n\t\tfor (const auto &name : mem_names) {\n\t\t\tmem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / Shared::totalMem));\n\t\t\twhile (cmp_greater(mem.percent.at(name).size(), width * 2))\n\t\t\t\tmem.percent.at(name).pop_front();\n\t\t}\n\n\t\tif (show_disks) {\n\t\t\tstd::unordered_map<string, string> mapping;  // keep mapping from device -> mountpoint, since IOKit doesn't give us the mountpoint\n\t\t\tdouble uptime = system_uptime();\n\t\t\tauto &disks_filter = Config::getS(\"disks_filter\");\n\t\t\tbool filter_exclude = false;\n\t\t\t// auto only_physical = Config::getB(\"only_physical\");\n\t\t\tauto &disks = mem.disks;\n\t\t\tvector<string> filter;\n\t\t\tif (not disks_filter.empty()) {\n\t\t\t\tfilter = ssplit(disks_filter);\n\t\t\t\tif (filter.at(0).starts_with(\"exclude=\")) {\n\t\t\t\t\tfilter_exclude = true;\n\t\t\t\t\tfilter.at(0) = filter.at(0).substr(8);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstruct statfs *stfs;\n\t\t\tint count = getmntinfo(&stfs, MNT_WAIT);\n\t\t\tvector<string> found;\n\t\t\tfound.reserve(last_found.size());\n\t\t\tfor (int i = 0; i < count; i++) {\n\t\t\t\tstd::error_code ec;\n\t\t\t\tstring mountpoint = stfs[i].f_mntonname;\n\t\t\t\tstring dev = stfs[i].f_mntfromname;\n\t\t\t\tmapping[dev] = mountpoint;\n\n\t\t\t\tif (string(stfs[i].f_fstypename) == \"autofs\") {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t//? Match filter if not empty\n\t\t\t\tif (not filter.empty()) {\n\t\t\t\t\tbool match = v_contains(filter, mountpoint);\n\t\t\t\t\tif ((filter_exclude and match) or (not filter_exclude and not match))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tfound.push_back(mountpoint);\n\t\t\t\tif (not disks.contains(mountpoint)) {\n\t\t\t\t\tdisks[mountpoint] = disk_info{fs::canonical(dev, ec), fs::path(mountpoint).filename()};\n\n\t\t\t\t\tif (disks.at(mountpoint).dev.empty())\n\t\t\t\t\t\tdisks.at(mountpoint).dev = dev;\n\n\t\t\t\t\tif (disks.at(mountpoint).name.empty())\n\t\t\t\t\t\tdisks.at(mountpoint).name = (mountpoint == \"/\" ? \"root\" : mountpoint);\n\t\t\t\t}\n\n\n\t\t\t\tif (not v_contains(last_found, mountpoint))\n\t\t\t\t\tredraw = true;\n\n\t\t\t\tdisks.at(mountpoint).free = stfs[i].f_bfree;\n\t\t\t\tdisks.at(mountpoint).total = stfs[i].f_iosize;\n\t\t\t}\n\n\t\t\t//? Remove disks no longer mounted or filtered out\n\t\t\tif (swap_disk and has_swap) found.push_back(\"swap\");\n\t\t\tfor (auto it = disks.begin(); it != disks.end();) {\n\t\t\t\tif (not v_contains(found, it->first))\n\t\t\t\t\tit = disks.erase(it);\n\t\t\t\telse\n\t\t\t\t\tit++;\n\t\t\t}\n\t\t\tif (found.size() != last_found.size()) redraw = true;\n\t\t\tlast_found = std::move(found);\n\n\t\t\t//? Get disk/partition stats\n\t\t\tfor (auto &[mountpoint, disk] : disks) {\n\t\t\t\tif (std::error_code ec; not fs::exists(mountpoint, ec))\n\t\t\t\t\tcontinue;\n\t\t\t\tstruct statvfs vfs;\n\t\t\t\tif (statvfs(mountpoint.c_str(), &vfs) < 0) {\n\t\t\t\t\tLogger::warning(\"Failed to get disk/partition stats with statvfs() for: {}\", mountpoint);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tdisk.total = vfs.f_blocks * vfs.f_frsize;\n\t\t\t\tdisk.free = vfs.f_bfree * vfs.f_frsize;\n\t\t\t\tdisk.used = disk.total - disk.free;\n\t\t\t\tif (disk.total != 0) {\n\t\t\t\t\tdisk.used_percent = round((double)disk.used * 100 / disk.total);\n\t\t\t\t\tdisk.free_percent = 100 - disk.used_percent;\n\t\t\t\t} else {\n\t\t\t\t\tdisk.used_percent = 0;\n\t\t\t\t\tdisk.free_percent = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Setup disks order in UI and add swap if enabled\n\t\t\tmem.disks_order.clear();\n\t\t\tif (snapped and disks.contains(\"/mnt\"))\n\t\t\t\tmem.disks_order.push_back(\"/mnt\");\n\t\t\telse if (disks.contains(\"/\"))\n\t\t\t\tmem.disks_order.push_back(\"/\");\n\t\t\tif (swap_disk and has_swap) {\n\t\t\t\tmem.disks_order.push_back(\"swap\");\n\t\t\t\tif (not disks.contains(\"swap\"))\n\t\t\t\t\tdisks[\"swap\"] = {\"\", \"swap\"};\n\t\t\t\tdisks.at(\"swap\").total = mem.stats.at(\"swap_total\");\n\t\t\t\tdisks.at(\"swap\").used = mem.stats.at(\"swap_used\");\n\t\t\t\tdisks.at(\"swap\").free = mem.stats.at(\"swap_free\");\n\t\t\t\tdisks.at(\"swap\").used_percent = mem.percent.at(\"swap_used\").back();\n\t\t\t\tdisks.at(\"swap\").free_percent = mem.percent.at(\"swap_free\").back();\n\t\t\t}\n\t\t\tfor (const auto &name : last_found)\n\t\t\t\tif (not is_in(name, \"/\", \"swap\", \"/dev\"))\n\t\t\t\t\tmem.disks_order.push_back(name);\n\n\t\t\tdisk_ios = 0;\n\t\t\tcollect_disk(disks, mapping);\n\n\t\t\told_uptime = uptime;\n\t\t}\n\t\treturn mem;\n\t}\n\n}  // namespace Mem\n\nnamespace Net {\n\tstd::unordered_map<string, net_info> current_net;\n\tnet_info empty_net = {};\n\tvector<string> interfaces;\n\tstring selected_iface;\n\tint errors = 0;\n\tstd::unordered_map<string, uint64_t> graph_max = {{\"download\", {}}, {\"upload\", {}}};\n\tstd::unordered_map<string, array<int, 2>> max_count = {{\"download\", {}}, {\"upload\", {}}};\n\tbool rescale = true;\n\tuint64_t timestamp = 0;\n\n\t//* RAII wrapper for getifaddrs\n\tclass getifaddr_wrapper {\n\t\tstruct ifaddrs *ifaddr;\n\n\t   public:\n\t\tint status;\n\t\tgetifaddr_wrapper() { status = getifaddrs(&ifaddr); }\n\t\t~getifaddr_wrapper() { freeifaddrs(ifaddr); }\n\t\tauto operator()() -> struct ifaddrs * { return ifaddr; }\n\t};\n\n\tauto collect(bool no_update) -> net_info & {\n\t\t// Lock mutex to prevent concurrent interface access during USB device changes\n\t\tstd::lock_guard<std::mutex> lock(Mem::interface_mutex);\n\t\tauto &net = current_net;\n\t\tauto &config_iface = Config::getS(\"net_iface\");\n\t\tauto net_sync = Config::getB(\"net_sync\");\n\t\tauto net_auto = Config::getB(\"net_auto\");\n\t\tauto new_timestamp = time_ms();\n\n\t\tif (not no_update and errors < 3) {\n\t\t\t//? Get interface list using getifaddrs() wrapper\n\t\t\tgetifaddr_wrapper if_wrap{};\n\t\t\tif (if_wrap.status != 0) {\n\t\t\t\terrors++;\n\t\t\t\tLogger::error(\"Net::collect() -> getifaddrs() failed with id {}\", if_wrap.status);\n\t\t\t\tredraw = true;\n\t\t\t\treturn empty_net;\n\t\t\t}\n\t\t\tint family = 0;\n\t\t\tstatic_assert(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN); // 46 >= 16, compile-time assurance.\n\t\t\tenum { IPBUFFER_MAXSIZE = INET6_ADDRSTRLEN }; // manually using the known biggest value, guarded by the above static_assert\n\t\t\tchar ip[IPBUFFER_MAXSIZE];\n\t\t\tinterfaces.clear();\n\t\t\tstring ipv4, ipv6;\n\n\t\t\t//? Iteration over all items in getifaddrs() list\n\t\t\tfor (auto *ifa = if_wrap(); ifa != nullptr; ifa = ifa->ifa_next) {\n\t\t\t\tif (ifa->ifa_addr == nullptr) continue;\n\t\t\t\tfamily = ifa->ifa_addr->sa_family;\n\t\t\t\tconst auto &iface = ifa->ifa_name;\n\t\t\t\t//? Update available interfaces vector and get status of interface\n\t\t\t\tif (not v_contains(interfaces, iface)) {\n\t\t\t\t\tinterfaces.push_back(iface);\n\t\t\t\t\tnet[iface].connected = (ifa->ifa_flags & IFF_RUNNING);\n\t\t\t\t\t// An interface can have more than one IP of the same family associated with it,\n\t\t\t\t\t// but we pick only the first one to show in the NET box.\n\t\t\t\t\t// Note: Interfaces without any IPv4 and IPv6 set are still valid and monitorable!\n\t\t\t\t\tnet[iface].ipv4.clear();\n\t\t\t\t\tnet[iface].ipv6.clear();\n\t\t\t\t}\n\t\t\t\t//? Get IPv4 address\n\t\t\t\tif (family == AF_INET) {\n\t\t\t\t\tif (net[iface].ipv4.empty()) {\n\t\t\t\t\t\tif (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr)->sin_addr), ip, IPBUFFER_MAXSIZE)) {\n\t\t\t\t\t\t\tnet[iface].ipv4 = ip;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tint errsv = errno;\n\t\t\t\t\t\t\tLogger::error(\"Net::collect() -> Failed to convert IPv4 to string for iface {}, errno: {}\", iface, strerror(errsv));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? Get IPv6 address\n\t\t\t\telse if (family == AF_INET6) {\n\t\t\t\t\tif (net[iface].ipv6.empty()) {\n\t\t\t\t\t\tif (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr)->sin6_addr), ip, IPBUFFER_MAXSIZE)) {\n\t\t\t\t\t\t\tnet[iface].ipv6 = ip;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tint errsv = errno;\n\t\t\t\t\t\t\tLogger::error(\"Net::collect() -> Failed to convert IPv6 to string for iface {}, errno: {}\", iface, strerror(errsv));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} // else, ignoring family==AF_LINK (see man 3 getifaddrs)\n\t\t\t}\n\n\t\t\tstd::unordered_map<string, std::tuple<uint64_t, uint64_t>> ifstats;\n\t\t\tint mib[] = {CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0};\n\t\t\tsize_t len;\n\t\t\tif (sysctl(mib, 6, nullptr, &len, nullptr, 0) < 0) {\n\t\t\t\tLogger::error(\"failed getting network interfaces\");\n\t\t\t} else {\n\t\t\t\tstd::unique_ptr<char[]> buf(new char[len]);\n\t\t\t\tif (sysctl(mib, 6, buf.get(), &len, nullptr, 0) < 0) {\n\t\t\t\t\tLogger::error(\"failed getting network interfaces\");\n\t\t\t\t} else {\n\t\t\t\t\tchar *lim = buf.get() + len;\n\t\t\t\t\tchar *next = nullptr;\n\t\t\t\t\tfor (next = buf.get(); next < lim;) {\n\t\t\t\t\t\tstruct if_msghdr *ifm = (struct if_msghdr *)next;\n\t\t\t\t\t\tnext += ifm->ifm_msglen;\n\t\t\t\t\t\tif (ifm->ifm_type == RTM_IFINFO2) {\n\t\t\t\t\t\t\tstruct if_msghdr2 *if2m = (struct if_msghdr2 *)ifm;\n\t\t\t\t\t\t\tstruct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1);\n\t\t\t\t\t\t\tchar iface[32];\n\t\t\t\t\t\t\tstrncpy(iface, sdl->sdl_data, sdl->sdl_nlen);\n\t\t\t\t\t\t\tiface[sdl->sdl_nlen] = 0;\n\t\t\t\t\t\t\tifstats[iface] = std::tuple(if2m->ifm_data.ifi_ibytes, if2m->ifm_data.ifi_obytes);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Get total received and transmitted bytes + device address if no ip was found\n\t\t\tfor (const auto &iface : interfaces) {\n\t\t\t\tfor (const string dir : {\"download\", \"upload\"}) {\n\t\t\t\t\tauto &saved_stat = net.at(iface).stat.at(dir);\n\t\t\t\t\tauto &bandwidth = net.at(iface).bandwidth.at(dir);\n\t\t\t\t\tuint64_t val = dir == \"download\" ? std::get<0>(ifstats[iface]) : std::get<1>(ifstats[iface]);\n\n\t\t\t\t\t//? Update speed, total and top values\n\t\t\t\t\tif (val < saved_stat.last) {\n\t\t\t\t\t\tsaved_stat.rollover += saved_stat.last;\n\t\t\t\t\t\tsaved_stat.last = 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (cmp_greater((unsigned long long)saved_stat.rollover + (unsigned long long)val, numeric_limits<uint64_t>::max())) {\n\t\t\t\t\t\tsaved_stat.rollover = 0;\n\t\t\t\t\t\tsaved_stat.last = 0;\n\t\t\t\t\t}\n\t\t\t\t\tsaved_stat.speed = round((double)(val - saved_stat.last) / ((double)(new_timestamp - timestamp) / 1000));\n\t\t\t\t\tif (saved_stat.speed > saved_stat.top) saved_stat.top = saved_stat.speed;\n\t\t\t\t\tif (saved_stat.offset > val + saved_stat.rollover) saved_stat.offset = 0;\n\t\t\t\t\tsaved_stat.total = (val + saved_stat.rollover) - saved_stat.offset;\n\t\t\t\t\tsaved_stat.last = val;\n\n\t\t\t\t\t//? Add values to graph\n\t\t\t\t\tbandwidth.push_back(saved_stat.speed);\n\t\t\t\t\twhile (cmp_greater(bandwidth.size(), width * 2)) bandwidth.pop_front();\n\n\t\t\t\t\t//? Set counters for auto scaling\n\t\t\t\t\tif (net_auto and selected_iface == iface) {\n\t\t\t\t\t\tif (saved_stat.speed > graph_max[dir]) {\n\t\t\t\t\t\t\t++max_count[dir][0];\n\t\t\t\t\t\t\tif (max_count[dir][1] > 0) --max_count[dir][1];\n\t\t\t\t\t\t} else if (graph_max[dir] > 10 << 10 and saved_stat.speed < graph_max[dir] / 10) {\n\t\t\t\t\t\t\t++max_count[dir][1];\n\t\t\t\t\t\t\tif (max_count[dir][0] > 0) --max_count[dir][0];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Clean up net map if needed\n\t\t\tif (net.size() > interfaces.size()) {\n\t\t\t\tfor (auto it = net.begin(); it != net.end();) {\n\t\t\t\t\tif (not v_contains(interfaces, it->first))\n\t\t\t\t\t\tit = net.erase(it);\n\t\t\t\t\telse\n\t\t\t\t\t\tit++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttimestamp = new_timestamp;\n\t\t}\n\t\t//? Return empty net_info struct if no interfaces was found\n\t\tif (net.empty())\n\t\t\treturn empty_net;\n\n\t\t//? Find an interface to display if selected isn't set or valid\n\t\tif (selected_iface.empty() or not v_contains(interfaces, selected_iface)) {\n\t\t\tmax_count[\"download\"][0] = max_count[\"download\"][1] = max_count[\"upload\"][0] = max_count[\"upload\"][1] = 0;\n\t\t\tredraw = true;\n\t\t\tif (net_auto) rescale = true;\n\t\t\tif (not config_iface.empty() and v_contains(interfaces, config_iface))\n\t\t\t\tselected_iface = config_iface;\n\t\t\telse {\n\t\t\t\t//? Sort interfaces by total upload + download bytes\n\t\t\t\tauto sorted_interfaces = interfaces;\n\t\t\t\trng::sort(sorted_interfaces, [&](const auto &a, const auto &b) {\n\t\t\t\t\treturn cmp_greater(net.at(a).stat[\"download\"].total + net.at(a).stat[\"upload\"].total,\n\t\t\t\t\t\t\t\t\t   net.at(b).stat[\"download\"].total + net.at(b).stat[\"upload\"].total);\n\t\t\t\t});\n\t\t\t\tselected_iface.clear();\n\t\t\t\t//? Try to set to a connected interface\n\t\t\t\tfor (const auto &iface : sorted_interfaces) {\n\t\t\t\t\tif (net.at(iface).connected) selected_iface = iface;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t//? If no interface is connected set to first available\n\t\t\t\tif (selected_iface.empty() and not sorted_interfaces.empty())\n\t\t\t\t\tselected_iface = sorted_interfaces.at(0);\n\t\t\t\telse if (sorted_interfaces.empty())\n\t\t\t\t\treturn empty_net;\n\t\t\t}\n\t\t}\n\n\t\t//? Calculate max scale for graphs if needed\n\t\tif (net_auto) {\n\t\t\tbool sync = false;\n\t\t\tfor (const auto &dir : {\"download\", \"upload\"}) {\n\t\t\t\tfor (const auto &sel : {0, 1}) {\n\t\t\t\t\tif (rescale or max_count[dir][sel] >= 5) {\n\t\t\t\t\t\tconst long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t: net[selected_iface].stat[dir].speed);\n\t\t\t\t\t\tgraph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10);\n\t\t\t\t\t\tmax_count[dir][0] = max_count[dir][1] = 0;\n\t\t\t\t\t\tredraw = true;\n\t\t\t\t\t\tif (net_sync) sync = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//? Sync download/upload graphs if enabled\n\t\t\t\tif (sync) {\n\t\t\t\t\tconst auto other = (string(dir) == \"upload\" ? \"download\" : \"upload\");\n\t\t\t\t\tgraph_max[other] = graph_max[dir];\n\t\t\t\t\tmax_count[other][0] = max_count[other][1] = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\trescale = false;\n\t\treturn net.at(selected_iface);\n\t}\n}  // namespace Net\n\nnamespace Proc {\n\n\tvector<proc_info> current_procs;\n\tstd::unordered_map<string, string> uid_user;\n\tstring current_sort;\n\tstring current_filter;\n\tbool current_rev = false;\n\tbool is_tree_mode;\n\n\tfs::file_time_type passwd_time;\n\n\tuint64_t cputimes;\n\tint collapse = -1, expand = -1, toggle_children = -1;\n\tuint64_t old_cputimes = 0;\n\tatomic<int> numpids = 0;\n\tint filter_found = 0;\n\n\tdetail_container detailed;\n\tstatic std::unordered_set<size_t> dead_procs;\n\n\tstring get_status(char s) {\n\t\tif (s & SRUN) return \"Running\";\n\t\tif (s & SSLEEP) return \"Sleeping\";\n\t\tif (s & SIDL) return \"Idle\";\n\t\tif (s & SSTOP) return \"Stopped\";\n\t\tif (s & SZOMB) return \"Zombie\";\n\t\treturn \"Unknown\";\n\t}\n\n\t//* Get detailed info for selected process\n\tvoid _collect_details(const size_t pid, vector<proc_info> &procs) {\n\t\tif (pid != detailed.last_pid) {\n\t\t\tdetailed = {};\n\t\t\tdetailed.last_pid = pid;\n\t\t\tdetailed.skip_smaps = not Config::getB(\"proc_info_smaps\");\n\t\t}\n\n\t\t//? Copy proc_info for process from proc vector\n\t\tauto p_info = rng::find(procs, pid, &proc_info::pid);\n\t\tdetailed.entry = *p_info;\n\n\t\t//? Update cpu percent deque for process cpu graph\n\t\tif (not Config::getB(\"proc_per_core\")) detailed.entry.cpu_p *= Shared::coreCount;\n\t\tdetailed.cpu_percent.push_back(clamp((long long)round(detailed.entry.cpu_p), 0ll, 100ll));\n\t\twhile (cmp_greater(detailed.cpu_percent.size(), width)) detailed.cpu_percent.pop_front();\n\n\t\t//? Process runtime : current time - start time (both in unix time - seconds since epoch)\n\t\tstruct timeval currentTime;\n\t\tgettimeofday(&currentTime, nullptr);\n\t\t//? Get elapsed time if process isn't dead\n\t\tif (detailed.entry.state != 'X') detailed.elapsed = sec_to_dhms(currentTime.tv_sec - (detailed.entry.cpu_s / 1'000'000));\n\t\telse detailed.elapsed = sec_to_dhms(detailed.entry.death_time);\n\t\tif (detailed.elapsed.size() > 8) detailed.elapsed.resize(detailed.elapsed.size() - 3);\n\n\t\t//? Get parent process name\n\t\tif (detailed.parent.empty()) {\n\t\t\tauto p_entry = rng::find(procs, detailed.entry.ppid, &proc_info::pid);\n\t\t\tif (p_entry != procs.end()) detailed.parent = p_entry->name;\n\t\t}\n\n\t\t//? Expand process status from single char to explanative string\n\t\tdetailed.status = get_status(detailed.entry.state);\n\n\t\tdetailed.mem_bytes.push_back(detailed.entry.mem);\n\t\tdetailed.memory = floating_humanizer(detailed.entry.mem);\n\n\t\tif (detailed.first_mem == -1 or detailed.first_mem < detailed.mem_bytes.back() / 2 or detailed.first_mem > detailed.mem_bytes.back() * 4) {\n\t\t\tdetailed.first_mem = min((uint64_t)detailed.mem_bytes.back() * 2, Mem::get_totalMem());\n\t\t\tredraw = true;\n\t\t}\n\n\t\twhile (cmp_greater(detailed.mem_bytes.size(), width)) detailed.mem_bytes.pop_front();\n\n\t\trusage_info_current rusage;\n\t\tif (proc_pid_rusage(pid, RUSAGE_INFO_CURRENT, (void **)&rusage) == 0) {\n\t\t\t// this fails for processes we don't own - same as in Linux\n\t\t\tdetailed.io_read = floating_humanizer(rusage.ri_diskio_bytesread);\n\t\t\tdetailed.io_write = floating_humanizer(rusage.ri_diskio_byteswritten);\n\t\t}\n\t}\n\n\t//* Collects and sorts process information from /proc\n\tauto collect(bool no_update) -> vector<proc_info> & {\n\t\tconst auto &sorting = Config::getS(\"proc_sorting\");\n\t\tauto reverse = Config::getB(\"proc_reversed\");\n\t\tconst auto &filter = Config::getS(\"proc_filter\");\n\t\tauto per_core = Config::getB(\"proc_per_core\");\n\t\tauto tree = Config::getB(\"proc_tree\");\n\t\tauto show_detailed = Config::getB(\"show_detailed\");\n\t\tconst auto pause_proc_list = Config::getB(\"pause_proc_list\");\n\t\tconst size_t detailed_pid = Config::getI(\"detailed_pid\");\n\t\tbool should_filter = current_filter != filter;\n\t\tif (should_filter) current_filter = filter;\n\t\tbool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter);\n\t\tbool tree_mode_change = tree != is_tree_mode;\n\t\tif (sorted_change) {\n\t\t\tcurrent_sort = sorting;\n\t\t\tcurrent_rev = reverse;\n\t\t}\n\t\tif (tree_mode_change) is_tree_mode = tree;\n\n\t\tconst int cmult = (per_core) ? Shared::coreCount : 1;\n\t\tbool got_detailed = false;\n\n\t\tstatic vector<size_t> found;\n\n\t\t//* Use pids from last update if only changing filter, sorting or tree options\n\t\tif (no_update and not current_procs.empty()) {\n\t\t\tif (show_detailed and detailed_pid != detailed.last_pid) _collect_details(detailed_pid, current_procs);\n\t\t} else {\n\t\t\t//* ---------------------------------------------Collection start----------------------------------------------\n\n\t\t\t{  //* Get CPU totals\n\t\t\t\tnatural_t cpu_count;\n\t\t\t\tkern_return_t error;\n\t\t\t\tprocessor_cpu_load_info_data_t *cpu_load_info = nullptr;\n\t\t\t\tMachProcessorInfo info{};\n\t\t\t\terror = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cpu_count, &info.info_array, &info.info_count);\n\t\t\t\tif (error != KERN_SUCCESS) {\n\t\t\t\t\tLogger::error(\"Failed getting CPU load info\");\n\t\t\t\t}\n\t\t\t\tcpu_load_info = (processor_cpu_load_info_data_t *)info.info_array;\n\t\t\t\tcputimes = 0;\n\t\t\t\tfor (natural_t i = 0; i < cpu_count; i++) {\n\t\t\t\t\tcputimes \t+= (cpu_load_info[i].cpu_ticks[CPU_STATE_USER]\n\t\t\t\t\t\t\t\t+ cpu_load_info[i].cpu_ticks[CPU_STATE_NICE]\n\t\t\t\t\t\t\t\t+ cpu_load_info[i].cpu_ticks[CPU_STATE_SYSTEM]\n\t\t\t\t\t\t\t\t+ cpu_load_info[i].cpu_ticks[CPU_STATE_IDLE]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tshould_filter = true;\n\t\t\tint mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};\n\t\t\tfound.clear();\n\t\t\tsize_t size = 0;\n\t\t\tconst auto timeNow = time_micros();\n\n\t\t\tif (sysctl(mib, 4, nullptr, &size, nullptr, 0) < 0 || size == 0) {\n\t\t\t\tLogger::error(\"Unable to get size of kproc_infos\");\n\t\t\t}\n\t\t\tuint64_t cpu_t = 0;\n\n\t\t\tstd::unique_ptr<kinfo_proc[]> processes(new kinfo_proc[size / sizeof(kinfo_proc)]);\n\t\t\tif (sysctl(mib, 4, processes.get(), &size, nullptr, 0) == 0) {\n\t\t\t\tsize_t count = size / sizeof(struct kinfo_proc);\n\t\t\t\tfor (size_t i = 0; i < count; i++) {  //* iterate over all processes in kinfo_proc\n\t\t\t\t\tstruct kinfo_proc& kproc = processes.get()[i];\n\t\t\t\t\tconst size_t pid = (size_t)kproc.kp_proc.p_pid;\n\t\t\t\t\tif (pid < 1) continue;\n\t\t\t\t\tfound.push_back(pid);\n\n\t\t\t\t\t//? Check if pid already exists in current_procs\n\t\t\t\t\tbool no_cache = false;\n\t\t\t\t\tauto find_old = rng::find(current_procs, pid, &proc_info::pid);\n\t\t\t\t\t//? Only add new processes if not paused\n\t\t\t\t\tif (find_old == current_procs.end()) {\n\t\t\t\t\t\tif (not pause_proc_list) {\n\t\t\t\t\t\t\tcurrent_procs.push_back({pid});\n\t\t\t\t\t\t\tfind_old = current_procs.end() - 1;\n\t\t\t\t\t\t\tno_cache = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse continue;\n\t\t\t\t\t}\n\t\t\t\t\telse if (dead_procs.contains(pid)) continue;\n\n\t\t\t\t\tauto &new_proc = *find_old;\n\n\t\t\t\t\t//? Get program name, command, username, parent pid, nice and status\n\t\t\t\t\tif (no_cache) {\n\t\t\t\t\t\tchar fullname[PROC_PIDPATHINFO_MAXSIZE];\n\t\t\t\t\t\tint rc = proc_pidpath(pid, fullname, sizeof(fullname));\n\t\t\t\t\t\tstring f_name = \"<defunct>\";\n\t\t\t\t\t\tif (rc != 0) {\n\t\t\t\t\t\t\tf_name = std::string(fullname);\n\t\t\t\t\t\t\tsize_t lastSlash = f_name.find_last_of('/');\n\t\t\t\t\t\t\tf_name = f_name.substr(lastSlash + 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnew_proc.name = f_name;\n\t\t\t\t\t\t//? Get process arguments if possible, fallback to process path in case of failure\n\t\t\t\t\t\tif (Shared::arg_max > 0) {\n\t\t\t\t\t\t\tstd::unique_ptr<char[]> proc_chars(new char[Shared::arg_max]);\n\t\t\t\t\t\t\tint mib[] = {CTL_KERN, KERN_PROCARGS2, (int)pid};\n\t\t\t\t\t\t\tsize_t argmax = Shared::arg_max;\n\t\t\t\t\t\t\tif (sysctl(mib, 3, proc_chars.get(), &argmax, nullptr, 0) == 0) {\n\t\t\t\t\t\t\t\tint argc = 0;\n\t\t\t\t\t\t\t\tmemcpy(&argc, &proc_chars.get()[0], sizeof(argc));\n\t\t\t\t\t\t\t\tstd::string_view proc_args(proc_chars.get(), argmax);\n\t\t\t\t\t\t\t\tif (size_t null_pos = proc_args.find('\\0', sizeof(argc)); null_pos != string::npos) {\n\t\t\t\t\t\t\t\t\tif (size_t start_pos = proc_args.find_first_not_of('\\0', null_pos); start_pos != string::npos) {\n\t\t\t\t\t\t\t\t\t\twhile (argc-- > 0 and null_pos != string::npos and cmp_less(new_proc.cmd.size(), 1000)) {\n\t\t\t\t\t\t\t\t\t\t\tnull_pos = proc_args.find('\\0', start_pos);\n\t\t\t\t\t\t\t\t\t\t\tnew_proc.cmd += (string)proc_args.substr(start_pos, null_pos - start_pos) + ' ';\n\t\t\t\t\t\t\t\t\t\t\tstart_pos = null_pos + 1;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (not new_proc.cmd.empty()) new_proc.cmd.pop_back();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (new_proc.cmd.empty()) new_proc.cmd = f_name;\n\t\t\t\t\t\tif (new_proc.cmd.size() > 1000) {\n\t\t\t\t\t\t\tnew_proc.cmd.resize(1000);\n\t\t\t\t\t\t\tnew_proc.cmd.shrink_to_fit();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnew_proc.ppid = kproc.kp_eproc.e_ppid;\n\t\t\t\t\t\tnew_proc.cpu_s = kproc.kp_proc.p_starttime.tv_sec * 1'000'000 + kproc.kp_proc.p_starttime.tv_usec;\n\t\t\t\t\t\tstruct passwd *pwd = getpwuid(kproc.kp_eproc.e_ucred.cr_uid);\n                        if (pwd != nullptr) {\n                            new_proc.user = pwd->pw_name;\n                        } else {\n                            new_proc.user = std::to_string(kproc.kp_eproc.e_ucred.cr_uid);\n                        }\n\t\t\t\t\t}\n\t\t\t\t\tnew_proc.p_nice = kproc.kp_proc.p_nice;\n\t\t\t\t\tnew_proc.state = kproc.kp_proc.p_stat;\n\n\t\t\t\t\t//? Get threads, mem and cpu usage\n\t\t\t\t\tstruct proc_taskinfo pti{};\n\t\t\t\t\tif (sizeof(pti) == proc_pidinfo(new_proc.pid, PROC_PIDTASKINFO, 0, &pti, sizeof(pti))) {\n\t\t\t\t\t\tnew_proc.threads = pti.pti_threadnum;\n\t\t\t\t\t\tnew_proc.mem = pti.pti_resident_size;\n\t\t\t\t\t\tcpu_t = pti.pti_total_user + pti.pti_total_system;\n\n\t\t\t\t\t\tif (new_proc.cpu_t == 0) new_proc.cpu_t = cpu_t;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Reset memory value if process info cannot be accessed (bad permissions or zombie processes)\n\t\t\t\t\t\tnew_proc.threads = 0;\n\t\t\t\t\t\tnew_proc.mem = 0;\n\t\t\t\t\t\tcpu_t = new_proc.cpu_t;\n\t\t\t\t\t}\n\n\t\t\t\t\t//? Process cpu usage since last update\n\t\t\t\t\tnew_proc.cpu_p = clamp(round(((cpu_t - new_proc.cpu_t) * Shared::machTck) / ((cputimes - old_cputimes) * Shared::clkTck)) * cmult / 1000.0, 0.0, 100.0 * Shared::coreCount);\n\n\t\t\t\t\t//? Process cumulative cpu usage since process start\n\t\t\t\t\tnew_proc.cpu_c = (double)(cpu_t * Shared::machTck) / (timeNow - new_proc.cpu_s);\n\n\t\t\t\t\t//? Update cached value with latest cpu times\n\t\t\t\t\tnew_proc.cpu_t = cpu_t;\n\n\t\t\t\t\tif (show_detailed and not got_detailed and new_proc.pid == detailed_pid) {\n\t\t\t\t\t\tgot_detailed = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//? Clear dead processes from current_procs if not paused\n\t\t\t\tif (not pause_proc_list) {\n\t\t\t\t\tauto eraser = rng::remove_if(current_procs, [&](const auto& element) { return not v_contains(found, element.pid); });\n\t\t\t\t\tcurrent_procs.erase(eraser.begin(), eraser.end());\n\t\t\t\t\tif (!dead_procs.empty()) dead_procs.clear();\n\t\t\t\t}\n\t\t\t\t//? Set correct state of dead processes if paused\n\t\t\t\telse {\n\t\t\t\t\tconst bool keep_dead_proc_usage = Config::getB(\"keep_dead_proc_usage\");\n\t\t\t\t\tfor (auto& r : current_procs) {\n\t\t\t\t\t\tif (rng::find(found, r.pid) == found.end()) {\n\t\t\t\t\t\t\tif (r.state != 'X') {\n\t\t\t\t\t\t\t\tstruct timeval currentTime;\n\t\t\t\t\t\t\t\tgettimeofday(&currentTime, nullptr);\n\t\t\t\t\t\t\t\tr.death_time = currentTime.tv_sec - (r.cpu_s / 1'000'000);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tr.state = 'X';\n\t\t\t\t\t\t\tdead_procs.emplace(r.pid);\n\t\t\t\t\t\t\t//? Reset cpu usage for dead processes if paused and option is set\n\t\t\t\t\t\t\tif (!keep_dead_proc_usage) {\n\t\t\t\t\t\t\t\tr.cpu_p = 0.0;\n\t\t\t\t\t\t\t\tr.mem = 0;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t//? Update the details info box for process if active\n\t\t\t\tif (show_detailed and got_detailed) {\n\t\t\t\t\t_collect_details(detailed_pid, current_procs);\n\t\t\t\t} else if (show_detailed and not got_detailed and detailed.status != \"Dead\") {\n\t\t\t\t\tdetailed.status = \"Dead\";\n\t\t\t\t\tredraw = true;\n\t\t\t\t}\n\n\t\t\t\told_cputimes = cputimes;\n\t\t\t}\n\t\t}\n\n\t\t//* ---------------------------------------------Collection done-----------------------------------------------\n\n\t\t//* Match filter if defined\n\t\tif (should_filter) {\n\t\t\tfilter_found = 0;\n\t\t\tfor (auto &p : current_procs) {\n\t\t\t\tif (not tree and not filter.empty()) {\n\t\t\t\t\tif (!matches_filter(p, filter)) {\n\t\t\t\t\t\tp.filtered = true;\n\t\t\t\t\t\tfilter_found++;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tp.filtered = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tp.filtered = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t//* Sort processes\n\t\tif ((sorted_change or tree_mode_change) or (not no_update and not pause_proc_list)) {\n\t\t\tproc_sorter(current_procs, sorting, reverse, tree);\n\t\t}\n\n\t\t//* Generate tree view if enabled\n\t\tif (tree and (not no_update or should_filter or sorted_change)) {\n\t\t\tbool locate_selection = false;\n\n\t\t\tif (toggle_children != -1) {\n\t\t\t\tauto collapser = rng::find(current_procs, toggle_children, &proc_info::pid);\n\t\t\t\tif (collapser != current_procs.end()){\n\t\t\t\t\tfor (auto& p : current_procs) {\n\t\t\t\t\t\tif (p.ppid == collapser->pid) {\n\t\t\t\t\t\t\tauto child = rng::find(current_procs, p.pid, &proc_info::pid);\n\t\t\t\t\t\t\tif (child != current_procs.end()){\n\t\t\t\t\t\t\t\tchild->collapsed = not child->collapsed;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (Config::ints.at(\"proc_selected\") > 0) locate_selection = true;\n\t\t\t\t}\n\t\t\t\ttoggle_children = -1;\n\t\t\t}\n\t\t\t\n\t\t\tif (auto find_pid = (collapse != -1 ? collapse : expand); find_pid != -1) {\n\t\t\t\tauto collapser = rng::find(current_procs, find_pid, &proc_info::pid);\n\t\t\t\tif (collapser != current_procs.end()) {\n\t\t\t\t\tif (collapse == expand) {\n\t\t\t\t\t\tcollapser->collapsed = not collapser->collapsed;\n\t\t\t\t\t}\n\t\t\t\t\telse if (collapse > -1) {\n\t\t\t\t\t\tcollapser->collapsed = true;\n\t\t\t\t\t}\n\t\t\t\t\telse if (expand > -1) {\n\t\t\t\t\t\tcollapser->collapsed = false;\n\t\t\t\t\t}\n\t\t\t\t\tif (Config::ints.at(\"proc_selected\") > 0) locate_selection = true;\n\t\t\t\t}\n\t\t\t\tcollapse = expand = -1;\n\t\t\t}\n\t\t\tif (should_filter or not filter.empty()) filter_found = 0;\n\n\t\t\tvector<tree_proc> tree_procs;\n\t\t\ttree_procs.reserve(current_procs.size());\n\n\t\t\tif (!pause_proc_list) {\n\t\t\t\tfor (auto& p : current_procs) {\n\t\t\t\t\tif (not v_contains(found, p.ppid)) p.ppid = 0;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//? Stable sort to retain selected sorting among processes with the same parent\n\t\t\trng::stable_sort(current_procs, rng::less{}, & proc_info::ppid);\n\n\t\t\t//? Start recursive iteration over processes with the lowest shared parent pids\n\t\t\tfor (auto& p : rng::equal_range(current_procs, current_procs.at(0).ppid, rng::less{}, &proc_info::ppid)) {\n\t\t\t\t_tree_gen(p, current_procs, tree_procs, 0, false, filter, false, no_update, should_filter);\n\t\t\t}\n\n\t\t\t//? Recursive sort over tree structure to account for collapsed processes in the tree\n\t\t\tint index = 0;\n\t\t\ttree_sort(tree_procs, sorting, reverse, (pause_proc_list and not (sorted_change or tree_mode_change)), index, current_procs.size());\n\n\t\t\t//? Recursive construction of ASCII tree prefixes.\n\t\t\tfor (auto t = tree_procs.begin(); t != tree_procs.end(); ++t) {\n\t\t\t\t_collect_prefixes(*t, t == tree_procs.end() - 1);\n\t\t\t}\n\n\t\t\t//? Final sort based on tree index\n\t\t\trng::stable_sort(current_procs, rng::less {}, &proc_info::tree_index);\n\n\t\t\t//? Move current selection/view to the selected process when collapsing/expanding in the tree\n\t\t\tif (locate_selection) {\n\t\t\t\tint loc = rng::find(current_procs, Proc::selected_pid, &proc_info::pid)->tree_index;\n\t\t\t\tif (Config::ints.at(\"proc_start\") >= loc or Config::ints.at(\"proc_start\") <= loc - Proc::select_max)\n\t\t\t\t\tConfig::ints.at(\"proc_start\") = max(0, loc - 1);\n\t\t\t\tConfig::ints.at(\"proc_selected\") = loc - Config::ints.at(\"proc_start\") + 1;\n\t\t\t}\n\t\t}\n\n\t\tnumpids = (int)current_procs.size() - filter_found;\n\t\treturn current_procs;\n\t}\n}  // namespace Proc\n\nnamespace Tools {\n\tdouble system_uptime() {\n\t\tstruct timeval ts, currTime;\n\t\tstd::size_t len = sizeof(ts);\n\t\tint mib[2] = {CTL_KERN, KERN_BOOTTIME};\n\t\tif (sysctl(mib, 2, &ts, &len, nullptr, 0) != -1) {\n\t\t\tgettimeofday(&currTime, nullptr);\n\t\t\treturn currTime.tv_sec - ts.tv_sec;\n\t\t}\n\t\treturn 0.0;\n\t}\n}  // namespace Tools\n"
  },
  {
    "path": "src/osx/sensors.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include <Availability.h>\n#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504\n#include \"sensors.hpp\"\n\n#include <CoreFoundation/CoreFoundation.h>\n#include <IOKit/hidsystem/IOHIDEventSystemClient.h>\n\n#include <string>\n#include <numeric>\n#include <vector>\n\nextern \"C\" {\ntypedef struct __IOHIDEvent *IOHIDEventRef;\ntypedef struct __IOHIDServiceClient *IOHIDServiceClientRef;\n#ifdef __LP64__\ntypedef double IOHIDFloat;\n#else\ntypedef float IOHIDFloat;\n#endif\n\n#define IOHIDEventFieldBase(type) (type << 16)\n#define kIOHIDEventTypeTemperature 15\n\nIOHIDEventSystemClientRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator);\nint IOHIDEventSystemClientSetMatching(IOHIDEventSystemClientRef client, CFDictionaryRef match);\nint IOHIDEventSystemClientSetMatchingMultiple(IOHIDEventSystemClientRef client, CFArrayRef match);\nIOHIDEventRef IOHIDServiceClientCopyEvent(IOHIDServiceClientRef, int64_t, int32_t, int64_t);\nCFStringRef IOHIDServiceClientCopyProperty(IOHIDServiceClientRef service, CFStringRef property);\nIOHIDFloat IOHIDEventGetFloatValue(IOHIDEventRef event, int32_t field);\n\n// create a dict ref, like for temperature sensor {\"PrimaryUsagePage\":0xff00, \"PrimaryUsage\":0x5}\nCFDictionaryRef matching(int page, int usage) {\n\tCFNumberRef nums[2];\n\tCFStringRef keys[2];\n\n\tkeys[0] = CFStringCreateWithCString(0, \"PrimaryUsagePage\", 0);\n\tkeys[1] = CFStringCreateWithCString(0, \"PrimaryUsage\", 0);\n\tnums[0] = CFNumberCreate(0, kCFNumberSInt32Type, &page);\n\tnums[1] = CFNumberCreate(0, kCFNumberSInt32Type, &usage);\n\n\tCFDictionaryRef dict = CFDictionaryCreate(0, (const void **)keys, (const void **)nums, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);\n\tCFRelease(keys[0]);\n\tCFRelease(keys[1]);\n\treturn dict;\n}\n\ndouble getValue(IOHIDServiceClientRef sc) {\n\tIOHIDEventRef event = IOHIDServiceClientCopyEvent(sc, kIOHIDEventTypeTemperature, 0, 0);  // here we use ...CopyEvent\n\tIOHIDFloat temp = 0.0;\n\tif (event != 0) {\n\t\ttemp = IOHIDEventGetFloatValue(event, IOHIDEventFieldBase(kIOHIDEventTypeTemperature));\n\t\tCFRelease(event);\n\t}\n\treturn temp;\n}\n\n}  // extern C\n\nlong long Cpu::ThermalSensors::getSensors() {\n\tCFDictionaryRef thermalSensors = matching(0xff00, 5);  // 65280_10 = FF00_16\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t   // thermalSensors's PrimaryUsagePage should be 0xff00 for M1 chip, instead of 0xff05\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t   // can be checked by ioreg -lfx\n\tIOHIDEventSystemClientRef system = IOHIDEventSystemClientCreate(kCFAllocatorDefault);\n\tIOHIDEventSystemClientSetMatching(system, thermalSensors);\n\tCFArrayRef matchingsrvs = IOHIDEventSystemClientCopyServices(system);\n\tstd::vector<double> temps;\n\tif (matchingsrvs) {\n\t\tlong count = CFArrayGetCount(matchingsrvs);\n\t\tfor (int i = 0; i < count; i++) {\n\t\t\tIOHIDServiceClientRef sc = (IOHIDServiceClientRef)CFArrayGetValueAtIndex(matchingsrvs, i);\n\t\t\tif (sc) {\n\t\t\t\tCFStringRef name = IOHIDServiceClientCopyProperty(sc, CFSTR(\"Product\"));  // here we use ...CopyProperty\n\t\t\t\tif (name) {\n\t\t\t\t\tchar buf[200];\n\t\t\t\t\tCFStringGetCString(name, buf, 200, kCFStringEncodingASCII);\n\t\t\t\t\tstd::string n(buf);\n\t\t\t\t\t// this is just a guess, nobody knows which sensors mean what\n\t\t\t\t\t// on my system PMU tdie 3 and 9 are missing...\n\t\t\t\t\t// there is also PMU tdev1-8 but it has negative values??\n\t\t\t\t\t// there is also eACC for efficiency package but it only has 2 entries\n\t\t\t\t\t// and pACC for performance but it has 7 entries (2 - 9) WTF\n\t\t\t\t\tif (n.starts_with(\"eACC\") or n.starts_with(\"pACC\")) {\n\t\t\t\t\t\ttemps.push_back(getValue(sc));\n\t\t\t\t\t}\n\t\t\t\t\tCFRelease(name);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tCFRelease(matchingsrvs);\n\t}\n\tCFRelease(system);\n\tCFRelease(thermalSensors);\n\tif (temps.empty()) return 0ll;\n\treturn round(std::accumulate(temps.begin(), temps.end(), 0ll) / temps.size());\n}\n#endif\n"
  },
  {
    "path": "src/osx/sensors.hpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include <Availability.h>\n#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504\nnamespace Cpu {\n\tclass ThermalSensors {\n\t   public:\n\t\tlong long getSensors();\n\t};\n}  // namespace Cpu\n#endif\n"
  },
  {
    "path": "src/osx/smc.cpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#include \"smc.hpp\"\n\nstatic constexpr size_t MaxIndexCount = sizeof(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\") - 1;\nstatic constexpr const char *KeyIndexes = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\nstatic UInt32 _strtoul(char *str, int size, int base) {\n\tUInt32 total = 0;\n\tint i;\n\n\tfor (i = 0; i < size; i++) {\n\t\tif (base == 16) {\n\t\t\ttotal += str[i] << (size - 1 - i) * 8;\n\t\t} else {\n\t\t\ttotal += (unsigned char)(str[i] << (size - 1 - i) * 8);\n\t\t}\n\t}\n\treturn total;\n}\n\nstatic void _ultostr(char *str, UInt32 val) {\n\tstr[0] = '\\0';\n\tsnprintf(str, 5, \"%c%c%c%c\",\n\t\t\t(unsigned int)val >> 24,\n\t\t\t(unsigned int)val >> 16,\n\t\t\t(unsigned int)val >> 8,\n\t\t\t(unsigned int)val);\n}\n\nnamespace Cpu {\n\n\tSMCConnection::SMCConnection() {\n\t\tCFMutableDictionaryRef matchingDictionary = IOServiceMatching(\"AppleSMC\");\n\t\tresult = IOServiceGetMatchingServices(0, matchingDictionary, &iterator);\n\t\tif (result != kIOReturnSuccess) {\n\t\t\tthrow std::runtime_error(\"failed to get AppleSMC\");\n\t\t}\n\n\t\tdevice = IOIteratorNext(iterator);\n\t\tIOObjectRelease(iterator);\n\t\tif (device == 0) {\n\t\t\tthrow std::runtime_error(\"failed to get SMC device\");\n\t\t}\n\n\t\tresult = IOServiceOpen(device, mach_task_self(), 0, &conn);\n\t\tIOObjectRelease(device);\n\t\tif (result != kIOReturnSuccess) {\n\t\t\tthrow std::runtime_error(\"failed to get SMC connection\");\n\t\t}\n\t}\n\tSMCConnection::~SMCConnection() {\n\t\tIOServiceClose(conn);\n\t}\n\n\tlong long SMCConnection::getSMCTemp(char *key) {\n\t\tSMCVal_t val;\n\t\tkern_return_t result;\n\t\tresult = SMCReadKey(key, &val);\n\t\tif (result == kIOReturnSuccess) {\n\t\t\tif (val.dataSize > 0) {\n\t\t\t\tif (strcmp(val.dataType, DATATYPE_SP78) == 0) {\n\t\t\t\t\t// convert sp78 value to temperature\n\t\t\t\t\tint intValue = val.bytes[0] * 256 + (unsigned char)val.bytes[1];\n\t\t\t\t\treturn static_cast<long long>(intValue / 256.0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\n\t// core means physical core in SMC, while in core map it's cpu threads :-/ Only an issue on hackintosh?\n\t// this means we can only get the T per physical core\n\t// another issue with the SMC API is that the key is always 4 chars -> what with systems with more than 9 physical cores?\n\t// no Mac models with more than 18 threads are released, so no problem so far\n\t// according to VirtualSMC docs (hackintosh fake SMC) the enumeration follows with alphabetic chars - not implemented yet here (nor in VirtualSMC)\n\tlong long SMCConnection::getTemp(int core) {\n\t\tchar key[] = SMC_KEY_CPU_TEMP;\n\t\tif (core >= 0) {\n\t\t\tif ((size_t)core > MaxIndexCount) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\tsnprintf(key, 5, \"TC%1cc\", KeyIndexes[core]);\n\t\t}\n\t\tlong long result = getSMCTemp(key);\n\t\tif (result == -1) {\n\t\t\t// try again with C\n\t\t\tsnprintf(key, 5, \"TC%1dC\", KeyIndexes[core]);\n\t\t\tresult = getSMCTemp(key);\n\t\t}\n\t\treturn result;\n\t}\n\n\tkern_return_t SMCConnection::SMCReadKey(UInt32Char_t key, SMCVal_t *val) {\n\t\tkern_return_t result;\n\t\tSMCKeyData_t inputStructure;\n\t\tSMCKeyData_t outputStructure;\n\n\t\tmemset(&inputStructure, 0, sizeof(SMCKeyData_t));\n\t\tmemset(&outputStructure, 0, sizeof(SMCKeyData_t));\n\t\tmemset(val, 0, sizeof(SMCVal_t));\n\n\t\tinputStructure.key = _strtoul(key, 4, 16);\n\t\tinputStructure.data8 = SMC_CMD_READ_KEYINFO;\n\n\t\tresult = SMCCall(KERNEL_INDEX_SMC, &inputStructure, &outputStructure);\n\t\tif (result != kIOReturnSuccess)\n\t\t\treturn result;\n\n\t\tval->dataSize = outputStructure.keyInfo.dataSize;\n\t\t_ultostr(val->dataType, outputStructure.keyInfo.dataType);\n\t\tinputStructure.keyInfo.dataSize = val->dataSize;\n\t\tinputStructure.data8 = SMC_CMD_READ_BYTES;\n\n\t\tresult = SMCCall(KERNEL_INDEX_SMC, &inputStructure, &outputStructure);\n\t\tif (result != kIOReturnSuccess)\n\t\t\treturn result;\n\n\t\tmemcpy(val->bytes, outputStructure.bytes, sizeof(outputStructure.bytes));\n\n\t\treturn kIOReturnSuccess;\n\t}\n\n\tkern_return_t SMCConnection::SMCCall(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure) {\n\t\tsize_t structureInputSize;\n\t\tsize_t structureOutputSize;\n\n\t\tstructureInputSize = sizeof(SMCKeyData_t);\n\t\tstructureOutputSize = sizeof(SMCKeyData_t);\n\n\t\treturn IOConnectCallStructMethod(conn, index,\n\t\t\t\t\t\t\t\t\t\t // inputStructure\n\t\t\t\t\t\t\t\t\t\t inputStructure, structureInputSize,\n\t\t\t\t\t\t\t\t\t\t // outputStructure\n\t\t\t\t\t\t\t\t\t\t outputStructure, &structureOutputSize);\n\t}\n\n}  // namespace Cpu\n"
  },
  {
    "path": "src/osx/smc.hpp",
    "content": "/* Copyright 2021 Aristocratos (jakob@qvantnet.com)\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n\t   http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\nindent = tab\ntab-size = 4\n*/\n\n#pragma once\n\n#include <CoreFoundation/CoreFoundation.h>\n#include <IOKit/IOKitLib.h>\n#include <IOKit/ps/IOPSKeys.h>\n#include <IOKit/ps/IOPowerSources.h>\n\n#include <stdexcept>\n\n#define VERSION \"0.01\"\n\n#define KERNEL_INDEX_SMC 2\n\n#define SMC_CMD_READ_BYTES 5\n#define SMC_CMD_WRITE_BYTES 6\n#define SMC_CMD_READ_INDEX 8\n#define SMC_CMD_READ_KEYINFO 9\n#define SMC_CMD_READ_PLIMIT 11\n#define SMC_CMD_READ_VERS 12\n\n#define DATATYPE_FPE2 \"fpe2\"\n#define DATATYPE_UINT8 \"ui8 \"\n#define DATATYPE_UINT16 \"ui16\"\n#define DATATYPE_UINT32 \"ui32\"\n#define DATATYPE_SP78 \"sp78\"\n\n// key values\n#define SMC_KEY_CPU_TEMP \"TC0P\" // proximity temp?\n#define SMC_KEY_CPU_DIODE_TEMP \"TC0D\" // diode temp?\n#define SMC_KEY_CPU_DIE_TEMP \"TC0F\" // die temp?\n#define SMC_KEY_CPU1_TEMP \"TC1C\"\n#define SMC_KEY_CPU2_TEMP \"TC2C\"  // etc\n#define SMC_KEY_FAN0_RPM_CUR \"F0Ac\"\n\ntypedef struct {\n\tchar major;\n\tchar minor;\n\tchar build;\n\tchar reserved[1];\n\tUInt16 release;\n} SMCKeyData_vers_t;\n\ntypedef struct {\n\tUInt16 version;\n\tUInt16 length;\n\tUInt32 cpuPLimit;\n\tUInt32 gpuPLimit;\n\tUInt32 memPLimit;\n} SMCKeyData_pLimitData_t;\n\ntypedef struct {\n\tUInt32 dataSize;\n\tUInt32 dataType;\n\tchar dataAttributes;\n} SMCKeyData_keyInfo_t;\n\ntypedef char SMCBytes_t[32];\n\ntypedef struct {\n\tUInt32 key;\n\tSMCKeyData_vers_t vers;\n\tSMCKeyData_pLimitData_t pLimitData;\n\tSMCKeyData_keyInfo_t keyInfo;\n\tchar result;\n\tchar status;\n\tchar data8;\n\tUInt32 data32;\n\tSMCBytes_t bytes;\n} SMCKeyData_t;\n\ntypedef char UInt32Char_t[5];\n\ntypedef struct {\n\tUInt32Char_t key;\n\tUInt32 dataSize;\n\tUInt32Char_t dataType;\n\tSMCBytes_t bytes;\n} SMCVal_t;\n\nnamespace Cpu {\n\tclass SMCConnection {\n\t   public:\n\t\tSMCConnection();\n\t\tvirtual ~SMCConnection();\n\n\t\tlong long getTemp(int core);\n\n\t   private:\n\t\tkern_return_t SMCReadKey(UInt32Char_t key, SMCVal_t *val);\n\t\tlong long getSMCTemp(char *key);\n\t\tkern_return_t SMCCall(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure);\n\n\t\tio_connect_t conn;\n\t\tkern_return_t result;\n\t\tmach_port_t masterPort;\n\t\tio_iterator_t iterator;\n\t\tio_object_t device;\n\t};\n}  // namespace Cpu\n"
  },
  {
    "path": "tests/CMakeLists.txt",
    "content": "# SPDX-License-Identifier: Apache-2.0\n\ninclude(FetchContent)\nFetchContent_Declare(\n  googletest\n  GIT_REPOSITORY https://github.com/google/googletest.git\n  GIT_TAG v1.17.0\n  FIND_PACKAGE_ARGS NAMES GTest\n)\nFetchContent_MakeAvailable(googletest)\n\nadd_library(libbtop_test)\ntarget_include_directories(libbtop_test PUBLIC ${PROJECT_SOURCE_DIR}/src)\ntarget_link_libraries(libbtop_test libbtop GTest::gtest_main)\n\nadd_executable(btop_test tools.cpp)\ntarget_link_libraries(btop_test libbtop_test)\n\ninclude(GoogleTest)\ngtest_discover_tests(btop_test)\n"
  },
  {
    "path": "tests/tools.cpp",
    "content": "// SPDX-License-Identifier: Apache-2.0\n\n#include <vector>\n\n#include <gtest/gtest.h>\n\n#include \"btop_tools.hpp\"\n\nTEST(tools, string_split) {\n\tEXPECT_EQ(Tools::ssplit(\"\"), std::vector<std::string> {});\n\tEXPECT_EQ(Tools::ssplit(\"foo\"), std::vector<std::string> { \"foo\" });\n\t{\n\t\tauto actual = Tools::ssplit(\"foo       bar         baz    \");\n\t\tauto expected = std::vector<std::string> { \"foo\", \"bar\", \"baz\" };\n\t\tEXPECT_EQ(actual, expected);\n\t}\n\n\t{\n\t\tauto actual = Tools::ssplit(\"foobo  oho  barbo  bo  bazbo\", 'o');\n\t\tauto expected = std::vector<std::string> { \"f\", \"b\", \"  \", \"h\", \"  barb\", \"  b\", \"  bazb\" };\n\t\tEXPECT_EQ(actual, expected);\n\t}\n}\n"
  },
  {
    "path": "themes/HotPurpleTrafficLight.theme",
    "content": "#HotPurpleTrafficLight\n#by Pete Allebone - mess with the best... you know the rest. <catch me at: peter at allebone dot org>\n#Designed to flash up bright red with danger when loads are high and attention is needed.\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#000000\"\n\n# Main text color\ntheme[main_fg]=\"#d1d1e0\"\n\n# Title color for boxes\ntheme[title]=\"#d1d1e0\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#9933ff\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#6666ff\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#d1d1e0\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#9999ff\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#9933ff\"\n\n# Background color of the percentage meters\ntheme[meter_bg]=\"#4d4dff\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#9933ff\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#a64dff\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#a64dff\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#a64dff\"\n\n# Processes box outline color\ntheme[proc_box]=\"#a64dff\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#4d4dff\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#00ff00\"\ntheme[temp_mid]=\"#ff9933\"\ntheme[temp_end]=\"#ff0000\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#00ff00\"\ntheme[cpu_mid]=\"#ccff66\"\ntheme[cpu_end]=\"#ff0000\"\n\n# Mem/Disk free meter\ntheme[free_end]=\"#00ff00\"\ntheme[free_mid]=\"#ccff66\"\ntheme[free_start]=\"#ff0000\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#00ff00\"\ntheme[cached_mid]=\"#ccff66\"\ntheme[cached_end]=\"#ff0000\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#ff0000\"\ntheme[available_mid]=\"#ccff66\"\ntheme[available_end]=\"#00ff00\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#00ff00\"\ntheme[used_mid]=\"#ccff66\"\ntheme[used_end]=\"#ff0000\"\n\n# Download graph colors\ntheme[download_start]=\"#00ff00\"\ntheme[download_mid]=\"#ff9933\"\ntheme[download_end]=\"#ff0000\"\n\n# Upload graph colors\ntheme[upload_start]=\"#00ff00\"\ntheme[upload_mid]=\"#ff9933\"\ntheme[upload_end]=\"#ff0000\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#9999ff\"\ntheme[process_mid]=\"#4d4dff\"\ntheme[process_end]=\"#a64dff\"\n\n"
  },
  {
    "path": "themes/adapta.theme",
    "content": "#Bashtop Adapta theme\n#by olokelo\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#ffffff\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"\"\n\n# Main text color\ntheme[main_fg]=\"#cfd8dc\"\n\n# Title color for boxes\ntheme[title]=\"#ff\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#90\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#bb0040\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#ff\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#40\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#55bcea\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#00bcd4\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#00bcd4\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#00bcd4\"\n\n# Processes box outline color\ntheme[proc_box]=\"#00bcd4\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#50\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#00bcd4\"\ntheme[temp_mid]=\"#d4d400\"\ntheme[temp_end]=\"#ff0040\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#00bcd4\"\ntheme[cpu_mid]=\"#d4d400\"\ntheme[cpu_end]=\"#ff0040\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#00bcd4\"\ntheme[free_mid]=\"#1090a0\"\ntheme[free_end]=\"#206f79\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#991199\"\ntheme[cached_mid]=\"#770a55\"\ntheme[cached_end]=\"#550055\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#00b0ff\"\ntheme[available_mid]=\"#1099cc\"\ntheme[available_end]=\"#2070aa\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#ff0040\"\ntheme[used_mid]=\"#ff2060\"\ntheme[used_end]=\"#ff4080\"\n\n# Download graph colors\ntheme[download_start]=\"#00bcd4\"\ntheme[download_mid]=\"#991199\"\ntheme[download_end]=\"#ff0040\"\n\n# Upload graph colors\ntheme[upload_start]=\"#00bcd4\"\ntheme[upload_mid]=\"#991199\"\ntheme[upload_end]=\"#ff0040\"\n"
  },
  {
    "path": "themes/adwaita-dark.theme",
    "content": "#Bashtop Adwaita Dark theme\n#by k0tran\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#1d1d1d\"\n\n# Main text color\ntheme[main_fg]=\"#deddda\"\n\n# Title color for boxes\ntheme[title]=\"#deddda\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#62a0ea\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#1c71d8\" \n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#ffffff\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#77767b\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#1a5fb4\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#77767b\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#77767b\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#77767b\"\n\n# Processes box outline color\ntheme[proc_box]=\"#77767b\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#77767b\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#62a0ea\"\ntheme[temp_mid]=\"#1c71d8\"\ntheme[temp_end]=\"#e01b24\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#62a0ea\"\ntheme[cpu_mid]=\"#1c71d8\"\ntheme[cpu_end]=\"#e01b24\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#62a0ea\"\ntheme[free_mid]=\"#1c71d8\"\ntheme[free_end]=\"#c01b24\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#62a0ea\"\ntheme[cached_mid]=\"#1c71d8\"\ntheme[cached_end]=\"#c01b24\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#62a0ea\"\ntheme[available_mid]=\"#1c71d8\"\ntheme[available_end]=\"#c01b24\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#62a0ea\"\ntheme[used_mid]=\"#1c71d8\"\ntheme[used_end]=\"#c01b24\"\n\n# Download graph colors\ntheme[download_start]=\"#62a0ea\"\ntheme[download_mid]=\"#1c71d8\"\ntheme[download_end]=\"#c01b24\"\n\n# Upload graph colors\ntheme[upload_start]=\"#62a0ea\"\ntheme[upload_mid]=\"#1c71d8\"\ntheme[upload_end]=\"#c01b24\"\n"
  },
  {
    "path": "themes/adwaita.theme",
    "content": "#Bashtop Adwaita theme\n#by flipflop133\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#FFFFFF\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#f6f5f4\"\n\n# Main text color\ntheme[main_fg]=\"#2e3436\"\n\n# Title color for boxes\ntheme[title]=\"#2e3436\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#1a5fb4\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#1c71d8\" \n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#ffffff\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#5e5c64\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#1a5fb4\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#2e3436\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#3d3c14\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#2e3436\"\n\n# Processes box outline color\ntheme[proc_box]=\"#2e3436\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#2e3436\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#1a5fb4\"\ntheme[temp_mid]=\"#1a5fb4\"\ntheme[temp_end]=\"#c01c28\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#1a5fb4\"\ntheme[cpu_mid]=\"#1a5fb4\"\ntheme[cpu_end]=\"#c01c28\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#1a5fb4\"\ntheme[free_mid]=\"#1a5fb4\"\ntheme[free_end]=\"#c01c28\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#1a5fb4\"\ntheme[cached_mid]=\"#1a5fb4\"\ntheme[cached_end]=\"#c01c28\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#1a5fb4\"\ntheme[available_mid]=\"#1a5fb4\"\ntheme[available_end]=\"#c01c28\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#1a5fb4\"\ntheme[used_mid]=\"#1a5fb4\"\ntheme[used_end]=\"#c01c28\"\n\n# Download graph colors\ntheme[download_start]=\"#1a5fb4\"\ntheme[download_mid]=\"#1a5fb4\"\ntheme[download_end]=\"#c01c28\"\n\n# Upload graph colors\ntheme[upload_start]=\"#1a5fb4\"\ntheme[upload_mid]=\"#1a5fb4\"\ntheme[upload_end]=\"#c01c28\"\n"
  },
  {
    "path": "themes/ayu.theme",
    "content": "# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#0B0E14\"\n\n# Main text color\ntheme[main_fg]=\"#BFBDB6\"\n\n# Title color for boxes\ntheme[title]=\"#BFBDB6\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#E6B450\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#E6B450\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#f8f8f2\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#565B66\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#BFBDB6\"\n\n# Background color of the percentage meters\ntheme[meter_bg]=\"#565B66\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#DFBFFF\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#DFBFFF\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#95E6CB\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#F28779\"\n\n# Processes box outline color\ntheme[proc_box]=\"#E6B673\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#565B66\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#DFBFFF\"\ntheme[temp_mid]=\"#D2A6FF\"\ntheme[temp_end]=\"#A37ACC\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#DFBFFF\"\ntheme[cpu_mid]=\"#D2A6FF\"\ntheme[cpu_end]=\"#A37ACC\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#95E6CB\"\ntheme[free_mid]=\"#95E6CB\"\ntheme[free_end]=\"#4CBF99\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#95E6CB\"\ntheme[cached_mid]=\"#95E6CB\"\ntheme[cached_end]=\"#4CBF99\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#95E6CB\"\ntheme[available_mid]=\"#95E6CB\"\ntheme[available_end]=\"#4CBF99\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#95E6CB\"\ntheme[used_mid]=\"#95E6CB\"\ntheme[used_end]=\"#4CBF99\"\n\n# Download graph colors\ntheme[download_start]=\"#F28779\"\ntheme[download_mid]=\"#F07178\"\ntheme[download_end]=\"#F07171\"\n\n# Upload graph colors\ntheme[upload_start]=\"#73D0FF\"\ntheme[upload_mid]=\"#59C2FF\"\ntheme[upload_end]=\"#399EE6\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#FFCC66\"\ntheme[process_mid]=\"#E6B450\"\ntheme[process_end]=\"#FFAA33\"\n"
  },
  {
    "path": "themes/dracula.theme",
    "content": "# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#282a36\"\n\n# Main text color\ntheme[main_fg]=\"#f8f8f2\"\n\n# Title color for boxes\ntheme[title]=\"#f8f8f2\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#6272a4\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#ff79c6\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#f8f8f2\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#44475a\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#f8f8f2\"\n\n# Background color of the percentage meters\ntheme[meter_bg]=\"#44475a\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#bd93f9\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#bd93f9\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#50fa7b\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#ff5555\"\n\n# Processes box outline color\ntheme[proc_box]=\"#8be9fd\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#44475a\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#bd93f9\"\ntheme[temp_mid]=\"#ff79c6\"\ntheme[temp_end]=\"#ff33a8\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#bd93f9\"\ntheme[cpu_mid]=\"#8be9fd\"\ntheme[cpu_end]=\"#50fa7b\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#ffa6d9\"\ntheme[free_mid]=\"#ff79c6\"\ntheme[free_end]=\"#ff33a8\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#b1f0fd\"\ntheme[cached_mid]=\"#8be9fd\"\ntheme[cached_end]=\"#26d7fd\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#ffd4a6\"\ntheme[available_mid]=\"#ffb86c\"\ntheme[available_end]=\"#ff9c33\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#96faaf\"\ntheme[used_mid]=\"#50fa7b\"\ntheme[used_end]=\"#0dfa49\"\n\n# Download graph colors\ntheme[download_start]=\"#bd93f9\"\ntheme[download_mid]=\"#50fa7b\"\ntheme[download_end]=\"#8be9fd\"\n\n# Upload graph colors\ntheme[upload_start]=\"#8c42ab\"\ntheme[upload_mid]=\"#ff79c6\"\ntheme[upload_end]=\"#ff33a8\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#50fa7b\"\ntheme[process_mid]=\"#59b690\"\ntheme[process_end]=\"#6272a4\"\n"
  },
  {
    "path": "themes/dusklight.theme",
    "content": "#Bpytop theme comprised of blues, oranges, cyan, and yellow.\n#by Drazil100\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#FFFFFF\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#04142E\"\n\n# Main text color\ntheme[main_fg]=\"#99DFFF\"\n\n# Title color for boxes\ntheme[title]=\"#99FFFF\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#FF7F00\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#722B01\" \n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#99FFFF\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#052E51\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#79A1B4\"\n\n# Background color of the percentage meters\ntheme[meter_bg]=\"#052E51\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#B46718\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#00FFFF\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#00FFFF\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#00FFFF\"\n\n# Processes box outline color\ntheme[proc_box]=\"#00FFFF\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#A55800\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#00ADFF\"\ntheme[temp_mid]=\"#00FFFF\"\ntheme[temp_end]=\"#FFF86B\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#00D4FF\"\ntheme[cpu_mid]=\"#FFF86B\"\ntheme[cpu_end]=\"#FF7F00\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#0187CB\"\ntheme[free_mid]=\"\"\ntheme[free_end]=\"\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#B4BB63\"\ntheme[cached_mid]=\"\"\ntheme[cached_end]=\"\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#01C0CB\"\ntheme[available_mid]=\"\"\ntheme[available_end]=\"\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#B46718\"\ntheme[used_mid]=\"\"\ntheme[used_end]=\"\"\n\n# Download graph colors\ntheme[download_start]=\"#009EFF\"\ntheme[download_mid]=\"\"\ntheme[download_end]=\"#00FFFF\"\n\n# Upload graph colors\ntheme[upload_start]=\"#FF7F00\"\ntheme[upload_mid]=\"\"\ntheme[upload_end]=\"#FFF86B\"\n"
  },
  {
    "path": "themes/elementarish.theme",
    "content": "# Theme: Elementarish\n# (inspired by Elementary OS)\n# By: Dennis Mayr\n\n# Main bg\ntheme[main_bg]=\"#333333\"\n\n# Main text color\ntheme[main_fg]=\"#eee8d5\"\n\n# Title color for boxes\ntheme[title]=\"#eee8d5\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#d1302c\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#268ad0\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#eee8d5\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#657b83\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#268ad0\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#657b83\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#657b83\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#657b83\"\n\n# Processes box outline color\ntheme[proc_box]=\"#657b83\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#657b83\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#859900\"\ntheme[temp_mid]=\"#b28602\"\ntheme[temp_end]=\"#d1302c\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#859900\"\ntheme[cpu_mid]=\"#b28602\"\ntheme[cpu_end]=\"#d1302c\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#268ad0\"\ntheme[free_mid]=\"#6c71c4\"\ntheme[free_end]=\"#2a9d95\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#268ad0\"\ntheme[cached_mid]=\"#6c71c4\"\ntheme[cached_end]=\"#d1302c\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#268ad0\"\ntheme[available_mid]=\"#6c71c4\"\ntheme[available_end]=\"#d1302c\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#859900\"\ntheme[used_mid]=\"#b28602\"\ntheme[used_end]=\"#d1302c\"\n\n# Download graph colors\ntheme[download_start]=\"#268ad0\"\ntheme[download_mid]=\"#6c71c4\"\ntheme[download_end]=\"#d1302c\"\n\n# Upload graph colors\ntheme[upload_start]=\"#268ad0\"\ntheme[upload_mid]=\"#6c71c4\"\ntheme[upload_end]=\"#d1302c\"\n"
  },
  {
    "path": "themes/everforest-dark-hard.theme",
    "content": "# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#272e33\"\n\n# Main text color\ntheme[main_fg]=\"#d3c6aa\"\n\n# Title color for boxes\ntheme[title]=\"#d3c6aa\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#e67e80\"\n\n# Background color of selected items\ntheme[selected_bg]=\"#374145\"\n\n# Foreground color of selected items\ntheme[selected_fg]=\"#dbbc7f\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#272e33\"  \n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#d3c6aa\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#a7c080\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#374145\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#374145\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#374145\"\n\n# Processes box outline color\ntheme[proc_box]=\"#374145\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#374145\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#a7c080\"\ntheme[temp_mid]=\"#dbbc7f\"\ntheme[temp_end]=\"#f85552\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#a7c080\"\ntheme[cpu_mid]=\"#dbbc7f\"\ntheme[cpu_end]=\"#f85552\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#f85552\"\ntheme[free_mid]=\"#dbbc7f\"\ntheme[free_end]=\"#a7c080\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#7fbbb3\"\ntheme[cached_mid]=\"#83c092\"\ntheme[cached_end]=\"#a7c080\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#f85552\"\ntheme[available_mid]=\"#dbbc7f\"\ntheme[available_end]=\"#a7c080\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#a7c080\"\ntheme[used_mid]=\"#dbbc7f\"\ntheme[used_end]=\"#f85552\"\n\n# Download graph colors\ntheme[download_start]=\"#a7c080\"\ntheme[download_mid]=\"#83c092\"\ntheme[download_end]=\"#7fbbb3\"\n\n# Upload graph colors\ntheme[upload_start]=\"#dbbc7f\"\ntheme[upload_mid]=\"#e69875\"\ntheme[upload_end]=\"#e67e80\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#a7c080\"\ntheme[process_mid]=\"#f85552\"\ntheme[process_end]=\"#CC241D\"\n"
  },
  {
    "path": "themes/everforest-dark-medium.theme",
    "content": "# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#2d353b\"\n\n# Main text color\ntheme[main_fg]=\"#d3c6aa\"\n\n# Title color for boxes\ntheme[title]=\"#d3c6aa\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#e67e80\"\n\n# Background color of selected items\ntheme[selected_bg]=\"#3d484d\"\n\n# Foreground color of selected items\ntheme[selected_fg]=\"#dbbc7f\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#2d353b\"  \n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#d3c6aa\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#a7c080\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#3d484d\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#3d484d\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#3d484d\"\n\n# Processes box outline color\ntheme[proc_box]=\"#3d484d\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#3d484d\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#a7c080\"\ntheme[temp_mid]=\"#dbbc7f\"\ntheme[temp_end]=\"#f85552\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#a7c080\"\ntheme[cpu_mid]=\"#dbbc7f\"\ntheme[cpu_end]=\"#f85552\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#f85552\"\ntheme[free_mid]=\"#dbbc7f\"\ntheme[free_end]=\"#a7c080\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#7fbbb3\"\ntheme[cached_mid]=\"#83c092\"\ntheme[cached_end]=\"#a7c080\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#f85552\"\ntheme[available_mid]=\"#dbbc7f\"\ntheme[available_end]=\"#a7c080\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#a7c080\"\ntheme[used_mid]=\"#dbbc7f\"\ntheme[used_end]=\"#f85552\"\n\n# Download graph colors\ntheme[download_start]=\"#a7c080\"\ntheme[download_mid]=\"#83c092\"\ntheme[download_end]=\"#7fbbb3\"\n\n# Upload graph colors\ntheme[upload_start]=\"#dbbc7f\"\ntheme[upload_mid]=\"#e69875\"\ntheme[upload_end]=\"#e67e80\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#a7c080\"\ntheme[process_mid]=\"#e67e80\"\ntheme[process_end]=\"#f85552\"\n\n"
  },
  {
    "path": "themes/everforest-light-medium.theme",
    "content": "# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#fdf6e3\"\n\n# Main text color\ntheme[main_fg]=\"#5c6a72\"\n\n# Title color for boxes\ntheme[title]=\"#5c6a72\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#df69ba\"\n\n# Background color of selected items\ntheme[selected_bg]=\"#4F585E\"\n\n# Foreground color of selected items\ntheme[selected_fg]=\"#dfa000\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#9DA9A0\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#5c6a72\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#8da101\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#4F585E\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#4F585E\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#4F585E\"\n\n# Processes box outline color\ntheme[proc_box]=\"#4F585E\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#4F585E\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#8da101\"\ntheme[temp_mid]=\"#dfa000\"\ntheme[temp_end]=\"#f85552\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#8da101\"\ntheme[cpu_mid]=\"#dfa000\"\ntheme[cpu_end]=\"#f85552\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#f85552\"\ntheme[free_mid]=\"#dfa000\"\ntheme[free_end]=\"#8da101\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#3994c5\"\ntheme[cached_mid]=\"#35a77c\"\ntheme[cached_end]=\"#8da101\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#f85552\"\ntheme[available_mid]=\"#dfa000\"\ntheme[available_end]=\"#8da101\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#8da101\"\ntheme[used_mid]=\"#dfa000\"\ntheme[used_end]=\"#f85552\"\n\n# Download graph colors\ntheme[download_start]=\"#8da101\"\ntheme[download_mid]=\"#35a77c\"\ntheme[download_end]=\"#3994c5\"\n\n# Upload graph colors\ntheme[upload_start]=\"#dfa000\"\ntheme[upload_mid]=\"#e66868\"\ntheme[upload_end]=\"#df69ba\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#8da101\"\ntheme[process_mid]=\"#df69ba\"\ntheme[process_end]=\"#f85552\"\n\n"
  },
  {
    "path": "themes/flat-remix-light.theme",
    "content": "#Bashtop theme with flat-remix colors\n#by Daniel Ruiz de Alegría <daniel@drasite.com>\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#ffffff\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#e4e4e7\"\n\n# Main text color\ntheme[main_fg]=\"#737680\"\n\n# Title color for boxes\ntheme[title]=\"#272a34\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#90\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#b8174c\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#ff\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#40\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#367bf0\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#367bf0\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#19a187\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#fd3535\"\n\n# Processes box outline color\ntheme[proc_box]=\"#4aaee6\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#50\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#367bf0\"\ntheme[temp_mid]=\"#b8174c\"\ntheme[temp_end]=\"#d41919\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#367bf0\"\ntheme[cpu_mid]=\"#4aaee6\"\ntheme[cpu_end]=\"#54bd8e\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#811035\"\ntheme[free_mid]=\"#b8174c\"\ntheme[free_end]=\"#d41919\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#2656a8\"\ntheme[cached_mid]=\"#4aaee6\"\ntheme[cached_end]=\"#23bac2\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#fea44c\"\ntheme[available_mid]=\"#fd7d00\"\ntheme[available_end]=\"#fe7171\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#12715f\"\ntheme[used_mid]=\"#19a187\"\ntheme[used_end]=\"#23bac2\"\n\n# Download graph colors\ntheme[download_start]=\"#367bf0\"\ntheme[download_mid]=\"#19a187\"\ntheme[download_end]=\"#4aaee6\"\n\n# Upload graph colors\ntheme[upload_start]=\"#8c42ab\"\ntheme[upload_mid]=\"#b8174c\"\ntheme[upload_end]=\"#d41919\"\n"
  },
  {
    "path": "themes/flat-remix.theme",
    "content": "#Bashtop theme with flat-remix colors\n#by Daniel Ruiz de Alegría <daniel@drasite.com>\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#ffffff\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"\"\n\n# Main text color\ntheme[main_fg]=\"#E6E6E6\"\n\n# Title color for boxes\ntheme[title]=\"#ff\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#90\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#b8174c\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#ff\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#40\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#367bf0\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#367bf0\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#19a187\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#fd3535\"\n\n# Processes box outline color\ntheme[proc_box]=\"#4aaee6\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#50\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#367bf0\"\ntheme[temp_mid]=\"#b8174c\"\ntheme[temp_end]=\"#d41919\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#367bf0\"\ntheme[cpu_mid]=\"#4aaee6\"\ntheme[cpu_end]=\"#54bd8e\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#811035\"\ntheme[free_mid]=\"#b8174c\"\ntheme[free_end]=\"#d41919\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#2656a8\"\ntheme[cached_mid]=\"#4aaee6\"\ntheme[cached_end]=\"#23bac2\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#fea44c\"\ntheme[available_mid]=\"#fd7d00\"\ntheme[available_end]=\"#fe7171\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#12715f\"\ntheme[used_mid]=\"#19a187\"\ntheme[used_end]=\"#23bac2\"\n\n# Download graph colors\ntheme[download_start]=\"#367bf0\"\ntheme[download_mid]=\"#19a187\"\ntheme[download_end]=\"#4aaee6\"\n\n# Upload graph colors\ntheme[upload_start]=\"#8c42ab\"\ntheme[upload_mid]=\"#b8174c\"\ntheme[upload_end]=\"#d41919\"\n"
  },
  {
    "path": "themes/flexoki-dark.theme",
    "content": "# Flexoki Dark theme (https://stephango.com/flexoki)\n# by Steph Ango\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#ffffff\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#100F0F\"\n\n# Main text color\ntheme[main_fg]=\"#CECDC3\"\n\n# Title color for boxes\ntheme[title]=\"#FFFCF0\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#DA702C\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#403E3C\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#FFFCF0\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#575653\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#878580\"\n\n# Background color of the percentage meters\ntheme[meter_bg]=\"#343331\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#879A39\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#4385BE\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#879A39\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#CE5D97\"\n\n# Processes box outline color\ntheme[proc_box]=\"#3AA99F\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#403E3C\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#4385BE\"\ntheme[temp_mid]=\"#8B7EC8\"\ntheme[temp_end]=\"#D14D41\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#3AA99F\"\ntheme[cpu_mid]=\"#D0A215\"\ntheme[cpu_end]=\"#D14D41\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#343331\"\ntheme[free_mid]=\"#575653\"\ntheme[free_end]=\"#879A39\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#205EA6\"\ntheme[cached_mid]=\"#4385BE\"\ntheme[cached_end]=\"#3AA99F\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#AD8301\"\ntheme[available_mid]=\"#D0A215\"\ntheme[available_end]=\"#DA702C\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#879A39\"\ntheme[used_mid]=\"#DA702C\"\ntheme[used_end]=\"#D14D41\"\n\n# Download graph colors\ntheme[download_start]=\"#205EA6\"\ntheme[download_mid]=\"#4385BE\"\ntheme[download_end]=\"#3AA99F\"\n\n# Upload graph colors\ntheme[upload_start]=\"#A02F6F\"\ntheme[upload_mid]=\"#CE5D97\"\ntheme[upload_end]=\"#8B7EC8\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#879A39\"\ntheme[process_mid]=\"#D0A215\"\ntheme[process_end]=\"#D14D41\"\n\n# Process box banner colors\ntheme[proc_pause_bg]=\"#D14D41\"\ntheme[proc_follow_bg]=\"#4385BE\"\ntheme[proc_banner_bg]=\"#8B7EC8\"\ntheme[proc_banner_fg]=\"#FFFCF0\"\n\n# Process following attributes\ntheme[followed_bg]=\"#4385BE\"\ntheme[followed_fg]=\"#FFFCF0\"\n"
  },
  {
    "path": "themes/flexoki-light.theme",
    "content": "# Flexoki Light theme (https://stephango.com/flexoki)\n# by Steph Ango\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#ffffff\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#FFFCF0\"\n\n# Main text color\ntheme[main_fg]=\"#343331\"\n\n# Title color for boxes\ntheme[title]=\"#100F0F\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#BC5215\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#E6E4D9\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#100F0F\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#B7B5AC\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#6F6E69\"\n\n# Background color of the percentage meters\ntheme[meter_bg]=\"#DAD8CE\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#66800B\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#205EA6\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#66800B\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#A02F6F\"\n\n# Processes box outline color\ntheme[proc_box]=\"#24837B\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#CECDC3\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#205EA6\"\ntheme[temp_mid]=\"#5E409D\"\ntheme[temp_end]=\"#AF3029\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#24837B\"\ntheme[cpu_mid]=\"#AD8301\"\ntheme[cpu_end]=\"#AF3029\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#DAD8CE\"\ntheme[free_mid]=\"#B7B5AC\"\ntheme[free_end]=\"#66800B\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#4385BE\"\ntheme[cached_mid]=\"#205EA6\"\ntheme[cached_end]=\"#24837B\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#D0A215\"\ntheme[available_mid]=\"#AD8301\"\ntheme[available_end]=\"#BC5215\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#66800B\"\ntheme[used_mid]=\"#BC5215\"\ntheme[used_end]=\"#AF3029\"\n\n# Download graph colors\ntheme[download_start]=\"#4385BE\"\ntheme[download_mid]=\"#205EA6\"\ntheme[download_end]=\"#24837B\"\n\n# Upload graph colors\ntheme[upload_start]=\"#CE5D97\"\ntheme[upload_mid]=\"#A02F6F\"\ntheme[upload_end]=\"#5E409D\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#66800B\"\ntheme[process_mid]=\"#AD8301\"\ntheme[process_end]=\"#AF3029\"\n\n# Process box banner colors\ntheme[proc_pause_bg]=\"#AF3029\"\ntheme[proc_follow_bg]=\"#205EA6\"\ntheme[proc_banner_bg]=\"#5E409D\"\ntheme[proc_banner_fg]=\"#FFFCF0\"\n\n# Process following attributes\ntheme[followed_bg]=\"#205EA6\"\ntheme[followed_fg]=\"#FFFCF0\"\n"
  },
  {
    "path": "themes/gotham.theme",
    "content": "# btop theme with the Gotham colorscheme for vim/neovim\n# Credit to Andrea Lopardi (https://github.com/whatyouhide/vim-gotham)\n# Adapted by jrebs (https://github.com/jrebs)\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#ffffff\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#2E3440\"\n\n# Main text color\ntheme[main_fg]=\"#99d1ce\"\n\n# Title color for boxes\ntheme[title]=\"#2aa889\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#ffffff\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#0a3749\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#99d1ce\"\n\n# Color of inactive/disabled text\n#theme[inactive_fg]=\"#a89984\"\ntheme[inactive_fg]=\"#403b34\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#a89984\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#99d1ce\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#99d1ce\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#99d1ce\"\n\n# Processes box outline color\ntheme[proc_box]=\"#99d1ce\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#4C566A\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#2aa889\"\ntheme[temp_mid]=\"#99d1ce\"\ntheme[temp_end]=\"#ffffff\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#2aa889\"\ntheme[cpu_mid]=\"#99d1ce\"\ntheme[cpu_end]=\"#ffffff\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#2aa889\"\ntheme[free_mid]=\"#99d1ce\"\ntheme[free_end]=\"#ffffff\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#2aa889\"\ntheme[cached_mid]=\"#99d1ce\"\ntheme[cached_end]=\"#ffffff\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#2aa889\"\ntheme[available_mid]=\"#99d1ce\"\ntheme[available_end]=\"#ffffff\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#2aa889\"\ntheme[used_mid]=\"#99d1ce\"\ntheme[used_end]=\"#ffffff\"\n\n# Download graph colors\ntheme[download_start]=\"#2aa889\"\ntheme[download_mid]=\"#99d1ce\"\ntheme[download_end]=\"#ffffff\"\n\n# Upload graph colors\ntheme[upload_start]=\"#2aa889\"\ntheme[upload_mid]=\"#99d1ce\"\ntheme[upload_end]=\"#ffffff\"\n"
  },
  {
    "path": "themes/greyscale.theme",
    "content": "#Bashtop grayscale theme\n#by aristocratos\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#FFFFFF\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#00\"\n\n# Main text color\ntheme[main_fg]=\"#bb\"\n\n# Title color for boxes\ntheme[title]=\"#cc\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#90\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#ff\" \n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#00\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#30\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#90\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#90\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#90\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#90\"\n\n# Processes box outline color\ntheme[proc_box]=\"#90\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#30\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#50\"\ntheme[temp_mid]=\"\"\ntheme[temp_end]=\"#ff\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#50\"\ntheme[cpu_mid]=\"\"\ntheme[cpu_end]=\"#ff\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#50\"\ntheme[free_mid]=\"\"\ntheme[free_end]=\"#ff\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#50\"\ntheme[cached_mid]=\"\"\ntheme[cached_end]=\"#ff\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#50\"\ntheme[available_mid]=\"\"\ntheme[available_end]=\"#ff\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#50\"\ntheme[used_mid]=\"\"\ntheme[used_end]=\"#ff\"\n\n# Download graph colors\ntheme[download_start]=\"#30\"\ntheme[download_mid]=\"\"\ntheme[download_end]=\"#ff\"\n\n# Upload graph colors\ntheme[upload_start]=\"#30\"\ntheme[upload_mid]=\"\"\ntheme[upload_end]=\"#ff\""
  },
  {
    "path": "themes/gruvbox_dark.theme",
    "content": "#Bashtop gruvbox (https://github.com/morhetz/gruvbox) theme\n#by BachoSeven\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#FFFFFF\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#1d2021\"\n\n# Main text color\ntheme[main_fg]=\"#a89984\"\n\n# Title color for boxes\ntheme[title]=\"#ebdbb2\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#d79921\"\n\n# Background color of selected items\ntheme[selected_bg]=\"#282828\"\n\n# Foreground color of selected items\ntheme[selected_fg]=\"#fabd2f\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#282828\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#585858\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#98971a\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#a89984\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#a89984\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#a89984\"\n\n# Processes box outline color\ntheme[proc_box]=\"#a89984\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#a89984\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#458588\"\ntheme[temp_mid]=\"#d3869b\"\ntheme[temp_end]=\"#fb4394\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#b8bb26\"\ntheme[cpu_mid]=\"#d79921\"\ntheme[cpu_end]=\"#fb4934\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#4e5900\"\ntheme[free_mid]=\"\"\ntheme[free_end]=\"#98971a\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#458588\"\ntheme[cached_mid]=\"\"\ntheme[cached_end]=\"#83a598\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#d79921\"\ntheme[available_mid]=\"\"\ntheme[available_end]=\"#fabd2f\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#cc241d\"\ntheme[used_mid]=\"\"\ntheme[used_end]=\"#fb4934\"\n\n# Download graph colors\ntheme[download_start]=\"#3d4070\"\ntheme[download_mid]=\"#6c71c4\"\ntheme[download_end]=\"#a3a8f7\"\n\n# Upload graph colors\ntheme[upload_start]=\"#701c45\"\ntheme[upload_mid]=\"#b16286\"\ntheme[upload_end]=\"#d3869b\"\n"
  },
  {
    "path": "themes/gruvbox_dark_v2.theme",
    "content": "# Bashtop gruvbox (https://github.com/morhetz/gruvbox) theme\n# First version created By BachoSeven\n# Adjustments to proper colors by Pietryszak (https://github.com/pietryszak/)\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#FFFFFF\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#282828\"\n\n# Main text color\ntheme[main_fg]=\"#EBDBB2\"\n\n# Title color for boxes\ntheme[title]=\"#EBDBB2\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#CC241D\"\n\n# Background color of selected items\ntheme[selected_bg]=\"#32302F\"\n\n# Foreground color of selected items\ntheme[selected_fg]=\"#D3869B\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#3C3836\"  \n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#A89984\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#98971A\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#A89984\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#A89984\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#A89984\"\n\n# Processes box outline color\ntheme[proc_box]=\"#A89984\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#A89984\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#98971A\"\ntheme[temp_mid]=\"\"\ntheme[temp_end]=\"#CC241D\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#8EC07C\"\ntheme[cpu_mid]=\"#D79921\"\ntheme[cpu_end]=\"#CC241D\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#CC241D\"\ntheme[free_mid]=\"#D79921\"\ntheme[free_end]=\"#8EC07C\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#458588\"\ntheme[cached_mid]=\"#83A598\"\ntheme[cached_end]=\"#8EC07C\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#CC241D\"\ntheme[available_mid]=\"#D65D0E\"\ntheme[available_end]=\"#FABD2F\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#8EC07C\"\ntheme[used_mid]=\"#D65D0E\"\ntheme[used_end]=\"#CC241D\"\n\n# Download graph colors\ntheme[download_start]=\"#98971A\"\ntheme[download_mid]=\"#689d6A\"\ntheme[download_end]=\"#B8BB26\"\n\n# Upload graph colors\ntheme[upload_start]=\"#CC241D\"\ntheme[upload_mid]=\"#D65d0E\"\ntheme[upload_end]=\"#FABF2F\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#8EC07C\"\ntheme[process_mid]=\"#FE8019\"\ntheme[process_end]=\"#CC241D\"\n"
  },
  {
    "path": "themes/gruvbox_light.theme",
    "content": "# Btop gruvbox_light theme\n# by kk9uk\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#fbf1c7\"\n\n# Main text color\ntheme[main_fg]=\"#3c3836\"\n\n# Title color for boxes\ntheme[title]=\"#3c3836\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#cc241d\"\n\n# Background color of selected items\ntheme[selected_bg]=\"#f2e5bc\"\n\n# Foreground color of selected items\ntheme[selected_fg]=\"#8f3f71\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#ebdbb2\"  \n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#a89984\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#98971a\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#a89984\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#a89984\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#a89984\"\n\n# Processes box outline color\ntheme[proc_box]=\"#a89984\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#a89984\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#98971a\"\ntheme[temp_mid]=\"\"\ntheme[temp_end]=\"#cc241d\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#427b58\"\ntheme[cpu_mid]=\"#d79921\"\ntheme[cpu_end]=\"#cc241d\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#cc241d\"\ntheme[free_mid]=\"#d79921\"\ntheme[free_end]=\"#427b58\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#458588\"\ntheme[cached_mid]=\"#076678\"\ntheme[cached_end]=\"#427b58\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#cc241d\"\ntheme[available_mid]=\"#d65d0e\"\ntheme[available_end]=\"#b57614\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#427b58\"\ntheme[used_mid]=\"#d65d0e\"\ntheme[used_end]=\"#cc241d\"\n\n# Download graph colors\ntheme[download_start]=\"#98971a\"\ntheme[download_mid]=\"#689d6a\"\ntheme[download_end]=\"#79740e\"\n\n# Upload graph colors\ntheme[upload_start]=\"#cc241d\"\ntheme[upload_mid]=\"#d65d0e\"\ntheme[upload_end]=\"#b57614\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#427b58\"\ntheme[process_mid]=\"#af3a03\"\ntheme[process_end]=\"#cc241d\"\n"
  },
  {
    "path": "themes/gruvbox_material_dark.theme",
    "content": "# Btop gruvbox material dark (https://github.com/sainnhe/gruvbox-material) theme\n# by Marco Radocchia\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#FFFFFF\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#282828\"\n\n# Main text color\ntheme[main_fg]=\"#d4be98\"\n\n# Title color for boxes\ntheme[title]=\"#d4be98\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#ea6962\"\n\n# Background color of selected items\ntheme[selected_bg]=\"#d8a657\"\n\n# Foreground color of selected items\ntheme[selected_fg]=\"#282828\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#282828\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#665c54\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#a9b665\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#7c6f64\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#7c6f64\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#7c6f64\"\n\n# Processes box outline color\ntheme[proc_box]=\"#7c6f64\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#7c6f64\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#7daea3\"\ntheme[temp_mid]=\"#e78a4e\"\ntheme[temp_end]=\"#ea6962\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#a9b665\"\ntheme[cpu_mid]=\"#d8a657\"\ntheme[cpu_end]=\"#ea6962\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#89b482\"\ntheme[free_mid]=\"\"\ntheme[free_end]=\"\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#7daea3\"\ntheme[cached_mid]=\"\"\ntheme[cached_end]=\"\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#d8a657\"\ntheme[available_mid]=\"\"\ntheme[available_end]=\"\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#ea6962\"\ntheme[used_mid]=\"\"\ntheme[used_end]=\"\"\n\n# Download graph colors\ntheme[download_start]=\"#e78a4e\"\ntheme[download_mid]=\"\"\ntheme[download_end]=\"\"\n\n# Upload graph colors\ntheme[upload_start]=\"#d3869b\"\ntheme[upload_mid]=\"\"\ntheme[upload_end]=\"\"\n"
  },
  {
    "path": "themes/horizon.theme",
    "content": "# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#1C1E26\"\n\n# Main text color\ntheme[main_fg]=\"#f8f8f2\"\n\n# Title color for boxes\ntheme[title]=\"#f8f8f2\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#B877DB\"\n\n# Background color of selected items\ntheme[selected_bg]=\"#282b37\"\n\n# Foreground color of selected items\ntheme[selected_fg]=\"#f8f8f2\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#272e33\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#f8f8f2\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#27D796\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#B877DB\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#27D796\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#E95678\"\n\n# Processes box outline color\ntheme[proc_box]=\"#25B2BC\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#272e33\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#27D796\"\ntheme[temp_mid]=\"#FAC29A\"\ntheme[temp_end]=\"#E95678\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#27D796\"\ntheme[cpu_mid]=\"#FAC29A\"\ntheme[cpu_end]=\"#E95678\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#E95678\"\ntheme[free_mid]=\"#FAC29A\"\ntheme[free_end]=\"#27D796\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#27D796\"\ntheme[cached_mid]=\"#FAC29A\"\ntheme[cached_end]=\"#E95678\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#27D796\"\ntheme[available_mid]=\"#FAC29A\"\ntheme[available_end]=\"#E95678\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#27D796\"\ntheme[used_mid]=\"#FAC29A\"\ntheme[used_end]=\"#E95678\"\n\n# Download graph colors\ntheme[download_start]=\"#27D796\"\ntheme[download_mid]=\"#FAC29A\"\ntheme[download_end]=\"#E95678\"\n\n# Upload graph colors\ntheme[upload_start]=\"#27D796\"\ntheme[upload_mid]=\"#FAC29A\"\ntheme[upload_end]=\"#E95678\"\n"
  },
  {
    "path": "themes/kanagawa-lotus.theme",
    "content": "# Bashtop Kanagawa-lotus (https://github.com/rebelot/kanagawa.nvim) theme\n# By: philikarus\n\n# Main bg\ntheme[main_bg]=\"#F2ECBC\"\n\n# Main text color\ntheme[main_fg]=\"#545464\"\n\n# Title color for boxes\ntheme[title]=\"#545464\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#C84053\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#c9cbd1\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#43436c\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#8A8980\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#597B75\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#8A8980\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#8A8980\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#8A8980\"\n\n# Processes box outline color\ntheme[proc_box]=\"#8A8980\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#8A8980\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#6E915F\"\ntheme[temp_mid]=\"#CC6D00\"\ntheme[temp_end]=\"#D7474B\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#6E915F\"\ntheme[cpu_mid]=\"#CC6D00\"\ntheme[cpu_end]=\"#D7474B\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#D7474B\"\ntheme[free_mid]=\"#C84053\"\ntheme[free_end]=\"#FF5D62\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#77713F\"\ntheme[cached_mid]=\"#CC6D00\"\ntheme[cached_end]=\"#FF9E3B\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#766b90\"\ntheme[available_mid]=\"#624c83\"\ntheme[available_end]=\"#9fb5c9\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#B5CBD2\"\ntheme[used_mid]=\"#4d699b\"\ntheme[used_end]=\"#4e8ca2\"\n\n# Download graph colors\ntheme[download_start]=\"#4d699b\"\ntheme[download_mid]=\"#624c83\"\ntheme[download_end]=\"#766b90\"\n\n# Upload graph colors\ntheme[upload_start]=\"#CC6D00\"\ntheme[upload_mid]=\"#E98A00\"\ntheme[upload_end]=\"#D7474B\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#6E915F\"\ntheme[process_mid]=\"#CC6D00\"\ntheme[process_end]=\"#C84053\"\n"
  },
  {
    "path": "themes/kanagawa-wave.theme",
    "content": "# Bashtop Kanagawa-wave (https://github.com/rebelot/kanagawa.nvim) theme\n# By: philikarus\n\n# Main bg\ntheme[main_bg]=\"#16161D\"\n\n# Main text color\ntheme[main_fg]=\"#dcd7ba\"\n\n# Title color for boxes\ntheme[title]=\"#dcd7ba\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#C34043\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#223249\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#dca561\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#727169\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#7aa89f\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#727169\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#727169\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#727169\"\n\n# Processes box outline color\ntheme[proc_box]=\"#727169\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#727169\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#98BB6C\"\ntheme[temp_mid]=\"#DCA561\"\ntheme[temp_end]=\"#E82424\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#98BB6C\"\ntheme[cpu_mid]=\"#DCA561\"\ntheme[cpu_end]=\"#E82424\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#E82424\"\ntheme[free_mid]=\"#C34043\"\ntheme[free_end]=\"#FF5D62\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#C0A36E\"\ntheme[cached_mid]=\"#DCA561\"\ntheme[cached_end]=\"#FF9E3B\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#938AA9\"\ntheme[available_mid]=\"#957FBB\"\ntheme[available_end]=\"#9CABCA\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#658594\"\ntheme[used_mid]=\"#7E9CDB\"\ntheme[used_end]=\"#7FB4CA\"\n\n# Download graph colors\ntheme[download_start]=\"#7E9CDB\"\ntheme[download_mid]=\"#938AA9\"\ntheme[download_end]=\"#957FBB\"\n\n# Upload graph colors\ntheme[upload_start]=\"#DCA561\"\ntheme[upload_mid]=\"#E6C384\"\ntheme[upload_end]=\"#E82424\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#98BB6C\"\ntheme[process_mid]=\"#DCA561\"\ntheme[process_end]=\"#C34043\"\n"
  },
  {
    "path": "themes/kyli0x.theme",
    "content": "#Bashtop Kyli0x Theme\n#by Kyli0x <kyli0x@protonmail.ch>\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#222222\"\n\n# Main text color\ntheme[main_fg]=\"#e8f6f5\"\n\n# Title color for boxes\ntheme[title]=\"#e8f6f5\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#21d6c9\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#1aaba0\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#e8f6f5\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#5ec4bc\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#ba1a84\"\n\n# Background color of the percentage meters\ntheme[meter_bg]=\"#5ec4bc\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#21d6c9\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#d486d4\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#d486d4\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#d486d4\"\n\n# Processes box outline color\ntheme[proc_box]=\"#d486d4\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#80638e\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#21d6c9\"\ntheme[temp_mid]=\"#1aaba0\"\ntheme[temp_end]=\"#5ec4bc\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#21d6c9\"\ntheme[cpu_mid]=\"#1aaba0\"\ntheme[cpu_end]=\"#5ec4bc\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#21d6c9\"\ntheme[free_mid]=\"#1aaba0\"\ntheme[free_end]=\"#5ec4bc\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#21d6c9\"\ntheme[cached_mid]=\"#1aaba0\"\ntheme[cached_end]=\"#5ec4bc\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#21d6c9\"\ntheme[available_mid]=\"#1aaba0\"\ntheme[available_end]=\"#5ec4bc\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#21d6c9\"\ntheme[used_mid]=\"#1aaba0\"\ntheme[used_end]=\"#5ec4bc\"\n\n# Download graph colors\ntheme[download_start]=\"#21d6c9\"\ntheme[download_mid]=\"#1aaba0\"\ntheme[download_end]=\"#5ec4bc\"\n\n# Upload graph colors\ntheme[upload_start]=\"#ec95ec\"\ntheme[upload_mid]=\"#1aaba0\"\ntheme[upload_end]=\"#5ec4bc\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#21d6c9\"\ntheme[process_mid]=\"#1aaba0\"\ntheme[process_end]=\"#ba1a84\"\n"
  },
  {
    "path": "themes/matcha-dark-sea.theme",
    "content": "#Bashtop matcha-dark-sea theme\n#by TheCynicalTeam\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#FFFFFF\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"\"\n\n# Main text color\ntheme[main_fg]=\"#F8F8F2\"\n\n# Title color for boxes\ntheme[title]=\"#F8F8F2\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#2eb398\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#0d493d\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#F8F8F2\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#595647\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#797667\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#33b165\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#75715E\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#75715E\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#75715E\"\n\n# Processes box outline color\ntheme[proc_box]=\"#75715E\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#595647\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#7976B7\"\ntheme[temp_mid]=\"#D8B8B2\"\ntheme[temp_end]=\"#33b165\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#33b165\"\ntheme[cpu_mid]=\"#F8F8F2\" #2eb398\"\ntheme[cpu_end]=\"#2eb398\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#75715E\"\ntheme[free_mid]=\"#a9c474\"\ntheme[free_end]=\"#e2f5bc\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#75715E\"\ntheme[cached_mid]=\"#66D9EF\"\ntheme[cached_end]=\"#aae7f2\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#75715E\"\ntheme[available_mid]=\"#E6DB74\"\ntheme[available_end]=\"#f2ecb6\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#75715E\"\ntheme[used_mid]=\"#2eb398\"\ntheme[used_end]=\"#33b165\"\n\n# Download graph colors\ntheme[download_start]=\"#2d2042\"\ntheme[download_mid]=\"#2eb398\"\ntheme[download_end]=\"#33b165\"\n\n# Upload graph colors\ntheme[upload_start]=\"#0d493d\"\ntheme[upload_mid]=\"#2eb398\"\ntheme[upload_end]=\"#33b165\"\n"
  },
  {
    "path": "themes/monokai.theme",
    "content": "#Bashtop monokai theme\n#by aristocratos\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#FFFFFF\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#060604\"\n\n# Main text color\ntheme[main_fg]=\"#F8F8F2\"\n\n# Title color for boxes\ntheme[title]=\"#F8F8F2\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#F92672\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#7a1137\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#F8F8F2\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#595647\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#797667\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#A6E22E\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#75715E\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#75715E\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#75715E\"\n\n# Processes box outline color\ntheme[proc_box]=\"#75715E\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#595647\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#7976B7\"\ntheme[temp_mid]=\"#D8B8B2\"\ntheme[temp_end]=\"#F92672\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#A6E22E\"\ntheme[cpu_mid]=\"#F8F8F2\" #b05475\"\ntheme[cpu_end]=\"#F92672\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#75715E\"\ntheme[free_mid]=\"#a9c474\"\ntheme[free_end]=\"#e2f5bc\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#75715E\"\ntheme[cached_mid]=\"#66D9EF\"\ntheme[cached_end]=\"#aae7f2\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#75715E\"\ntheme[available_mid]=\"#E6DB74\"\ntheme[available_end]=\"#f2ecb6\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#75715E\"\ntheme[used_mid]=\"#F92672\"\ntheme[used_end]=\"#ff87b2\"\n\n# Download graph colors\ntheme[download_start]=\"#2d2042\"\ntheme[download_mid]=\"#7352a8\"\ntheme[download_end]=\"#ccaefc\"\n\n# Upload graph colors\ntheme[upload_start]=\"#570d33\"\ntheme[upload_mid]=\"#cf277d\"\ntheme[upload_end]=\"#fa91c7\"\n"
  },
  {
    "path": "themes/night-owl.theme",
    "content": "#Bashtop theme with night-owl colors\n#by zkourouma\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#ffffff\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#011627\"\n\n# Main text color\ntheme[main_fg]=\"#d6deeb\"\n\n# Title color for boxes\ntheme[title]=\"#ffffff\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#addb67\"\n\n# Background color of selected items\ntheme[selected_bg]=\"#000000\"\n\n# Foreground color of selected items\ntheme[selected_fg]=\"#ffeb95\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#575656\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#585858\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#22da6e\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#ffffff\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#ffffff\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#ffffff\"\n\n# Processes box outline color\ntheme[proc_box]=\"#ffffff\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#ffffff\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#82aaff\"\ntheme[temp_mid]=\"#c792ea\"\ntheme[temp_end]=\"#fb4394\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#22da6e\"\ntheme[cpu_mid]=\"#addb67\"\ntheme[cpu_end]=\"#ef5350\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#4e5900\"\ntheme[free_mid]=\"\"\ntheme[free_end]=\"#22da6e\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#82aaff\"\ntheme[cached_mid]=\"\"\ntheme[cached_end]=\"#82aaff\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#addb67\"\ntheme[available_mid]=\"\"\ntheme[available_end]=\"#ffeb95\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#ef5350\"\ntheme[used_mid]=\"\"\ntheme[used_end]=\"#ef5350\"\n\n# Download graph colors\ntheme[download_start]=\"#3d4070\"\ntheme[download_mid]=\"#6c71c4\"\ntheme[download_end]=\"#a3a8f7\"\n\n# Upload graph colors\ntheme[upload_start]=\"#701c45\"\ntheme[upload_mid]=\"#c792ea\"\ntheme[upload_end]=\"#c792ea\"\n"
  },
  {
    "path": "themes/nord.theme",
    "content": "#Bashtop theme with nord palette (https://www.nordtheme.com)\n#by Justin Zobel <justin.zobel@gmail.com>\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#ffffff\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#2E3440\"\n\n# Main text color\ntheme[main_fg]=\"#D8DEE9\"\n\n# Title color for boxes\ntheme[title]=\"#8FBCBB\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#5E81AC\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#4C566A\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#ECEFF4\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#4C566A\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#5E81AC\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#4C566A\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#4C566A\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#4C566A\"\n\n# Processes box outline color\ntheme[proc_box]=\"#4C566A\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#4C566A\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#81A1C1\"\ntheme[temp_mid]=\"#88C0D0\"\ntheme[temp_end]=\"#ECEFF4\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#81A1C1\"\ntheme[cpu_mid]=\"#88C0D0\"\ntheme[cpu_end]=\"#ECEFF4\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#81A1C1\"\ntheme[free_mid]=\"#88C0D0\"\ntheme[free_end]=\"#ECEFF4\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#81A1C1\"\ntheme[cached_mid]=\"#88C0D0\"\ntheme[cached_end]=\"#ECEFF4\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#81A1C1\"\ntheme[available_mid]=\"#88C0D0\"\ntheme[available_end]=\"#ECEFF4\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#81A1C1\"\ntheme[used_mid]=\"#88C0D0\"\ntheme[used_end]=\"#ECEFF4\"\n\n# Download graph colors\ntheme[download_start]=\"#81A1C1\"\ntheme[download_mid]=\"#88C0D0\"\ntheme[download_end]=\"#ECEFF4\"\n\n# Upload graph colors\ntheme[upload_start]=\"#81A1C1\"\ntheme[upload_mid]=\"#88C0D0\"\ntheme[upload_end]=\"#ECEFF4\"\n"
  },
  {
    "path": "themes/onedark.theme",
    "content": "# Theme: OneDark\n# By: Vitor Melo\n\n# Main bg\ntheme[main_bg]=\"#282c34\"\n\n# Main text color\ntheme[main_fg]=\"#abb2bf\"\n\n# Title color for boxes\ntheme[title]=\"#abb2bf\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#61afef\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#2c313c\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#abb2bf\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#5c6370\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#61afef\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#5c6370\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#5c6370\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#5c6370\"\n\n# Processes box outline color\ntheme[proc_box]=\"#5c6370\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#5c6370\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#98c379\"\ntheme[temp_mid]=\"#e5c07b\"\ntheme[temp_end]=\"#e06c75\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#98c379\"\ntheme[cpu_mid]=\"#e5c07b\"\ntheme[cpu_end]=\"#e06c75\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#98c379\"\ntheme[free_mid]=\"#e5c07b\"\ntheme[free_end]=\"#e06c75\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#98c379\"\ntheme[cached_mid]=\"#e5c07b\"\ntheme[cached_end]=\"#e06c75\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#98c379\"\ntheme[available_mid]=\"#e5c07b\"\ntheme[available_end]=\"#e06c75\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#98c379\"\ntheme[used_mid]=\"#e5c07b\"\ntheme[used_end]=\"#e06c75\"\n\n# Download graph colors\ntheme[download_start]=\"#98c379\"\ntheme[download_mid]=\"#e5c07b\"\ntheme[download_end]=\"#e06c75\"\n\n# Upload graph colors\ntheme[upload_start]=\"#98c379\"\ntheme[upload_mid]=\"#e5c07b\"\ntheme[upload_end]=\"#e06c75\"\n"
  },
  {
    "path": "themes/orange.theme",
    "content": "# Btop orange theme\n# by neocerambyx\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#00\"\n\n# Main text color\ntheme[main_fg]=\"#ffa500\"\n\n# Title color for boxes\ntheme[title]=\"#ffa500\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#ffcc66\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#ffa500\" \n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#000000\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#4d3200\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#ffa500\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#ffa500\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#ffa500\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#ffa500\"\n\n# Processes box outline color\ntheme[proc_box]=\"#ffa500\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#332100\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#996300\"\ntheme[temp_mid]=\"\"\ntheme[temp_end]=\"#ffa500\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#996300\"\ntheme[cpu_mid]=\"\"\ntheme[cpu_end]=\"#ffa500\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#996300\"\ntheme[free_mid]=\"\"\ntheme[free_end]=\"#ffa500\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#996300\"\ntheme[cached_mid]=\"\"\ntheme[cached_end]=\"#ffa500\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#996300\"\ntheme[available_mid]=\"\"\ntheme[available_end]=\"#ffa500\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#996300\"\ntheme[used_mid]=\"\"\ntheme[used_end]=\"#ffa500\"\n\n# Download graph colors\ntheme[download_start]=\"#996300\"\ntheme[download_mid]=\"\"\ntheme[download_end]=\"#ffa500\"\n\n# Upload graph colors\ntheme[upload_start]=\"#996300\"\ntheme[upload_mid]=\"\"\ntheme[upload_end]=\"#ffa500\"\n\n# Process list banner attributes\ntheme[proc_pause_bg]=\"#996300\"\ntheme[proc_follow_bg]=\"#ffa500\"\ntheme[proc_banner_bg]=\"#ffcc66\"\ntheme[proc_banner_fg]=\"#000000\"\n\n# Process following attributes\ntheme[followed_bg]=\"#ffa500\"\ntheme[followed_fg]=\"#000000\"\n"
  },
  {
    "path": "themes/paper.theme",
    "content": "# Bashtop Paper theme\n# c/o @s6muel\n# inspired by @yorickpeterse's vim-paper theme at https://gitlab.com/yorickpeterse/vim-paper\n#\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#F2EEDE\"\n\n# Main text color\ntheme[main_fg]=\"#00\"\n\n# Title color for boxes\ntheme[title]=\"#00\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#CC3E28\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#D8D5C7\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#00\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#d8d5c7\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#00\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#00\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#00\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#00\"\n\n# Processes box outline color\ntheme[proc_box]=\"#00\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#00\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#55\"\ntheme[temp_mid]=\"#00\"\ntheme[temp_end]=\"#CC3E28\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#55\"\ntheme[cpu_mid]=\"#00\"\ntheme[cpu_end]=\"#CC3E28\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#216609\"\ntheme[free_mid]=\"\"\ntheme[free_end]=\"#216609\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#1e6fcc\"\ntheme[cached_mid]=\"\"\ntheme[cached_end]=\"#1e6fcc\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#216609\"\ntheme[available_mid]=\"\"\ntheme[available_end]=\"#216609\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#CC3E28\"\ntheme[used_mid]=\"\"\ntheme[used_end]=\"#CC3E28\"\n\n# Download graph colors\ntheme[download_start]=\"#55\"\ntheme[download_mid]=\"#00\"\ntheme[download_end]=\"#CC3E28\"\n\n# Upload graph colors\ntheme[upload_start]=\"#55\"\ntheme[upload_mid]=\"#00\"\ntheme[upload_end]=\"#CC3E28\"\n"
  },
  {
    "path": "themes/phoenix-night.theme",
    "content": "# Theme: Phoenix Night\n# By: Firehawke\n# A combination of:\n# Base theme colors from Pascal Jaeger's tokyo-night\n# Graph theme colors from Pete Allebone's HotPurpleTrafficLight\n# ...basically, I wanted most of Tokyo Night with a significantly more visible graph bar coloration.\n\n# Main bg\ntheme[main_bg]=\"#1a1b26\"\n\n# Main text color\ntheme[main_fg]=\"#cfc9c2\"\n\n# Title color for boxes\ntheme[title]=\"#cfc9c2\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#7dcfff\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#414868\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#cfc9c2\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#565f89\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#7dcfff\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#565f89\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#565f89\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#565f89\"\n\n# Processes box outline color\ntheme[proc_box]=\"#565f89\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#565f89\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#00ff00\"\ntheme[temp_mid]=\"#ff9933\"\ntheme[temp_end]=\"#ff0000\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#00ff00\"\ntheme[cpu_mid]=\"#ccff66\"\ntheme[cpu_end]=\"#ff0000\"\n\n# Mem/Disk free meter\ntheme[free_end]=\"#00ff00\"\ntheme[free_mid]=\"#ccff66\"\ntheme[free_start]=\"#ff0000\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#00ff00\"\ntheme[cached_mid]=\"#ccff66\"\ntheme[cached_end]=\"#ff0000\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#ff0000\"\ntheme[available_mid]=\"#ccff66\"\ntheme[available_end]=\"#00ff00\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#00ff00\"\ntheme[used_mid]=\"#ccff66\"\ntheme[used_end]=\"#ff0000\"\n\n# Download graph colors\ntheme[download_start]=\"#00ff00\"\ntheme[download_mid]=\"#ff9933\"\ntheme[download_end]=\"#ff0000\"\n\n# Upload graph colors\ntheme[upload_start]=\"#00ff00\"\ntheme[upload_mid]=\"#ff9933\"\ntheme[upload_end]=\"#ff0000\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#9999ff\"\ntheme[process_mid]=\"#4d4dff\"\ntheme[process_end]=\"#a64dff\"\n"
  },
  {
    "path": "themes/solarized_dark.theme",
    "content": "#Bashtop solarized theme\n#by aristocratos\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#FFFFFF\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#002b36\"\n\n# Main text color\ntheme[main_fg]=\"#eee8d5\"\n\n# Title color for boxes\ntheme[title]=\"#fdf6e3\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#b58900\"\n\n# Background color of selected items\ntheme[selected_bg]=\"#073642\" \n\n# Foreground color of selected items\ntheme[selected_fg]=\"#d6a200\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#073642\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#bad600\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#586e75\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#586e75\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#586e75\"\n\n# Processes box outline color\ntheme[proc_box]=\"#586e75\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#586e75\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#268bd2\"\ntheme[temp_mid]=\"#ccb5f7\"\ntheme[temp_end]=\"#fc5378\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#adc700\"\ntheme[cpu_mid]=\"#d6a200\"\ntheme[cpu_end]=\"#e65317\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#4e5900\"\ntheme[free_mid]=\"\"\ntheme[free_end]=\"#bad600\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#114061\"\ntheme[cached_mid]=\"\"\ntheme[cached_end]=\"#268bd2\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#705500\"\ntheme[available_mid]=\"\"\ntheme[available_end]=\"#edb400\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#6e1718\"\ntheme[used_mid]=\"\"\ntheme[used_end]=\"#e02f30\"\n\n# Download graph colors\ntheme[download_start]=\"#3d4070\"\ntheme[download_mid]=\"#6c71c4\"\ntheme[download_end]=\"#a3a8f7\"\n\n# Upload graph colors\ntheme[upload_start]=\"#701c45\"\ntheme[upload_mid]=\"#d33682\"\ntheme[upload_end]=\"#f56caf\""
  },
  {
    "path": "themes/solarized_light.theme",
    "content": "#solarized_light theme\n#modified from solarized_dark theme\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#FFFFFF\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#fdf6e3\"\n\n# Main text color\ntheme[main_fg]=\"#586e75\"\n\n# Title color for boxes\ntheme[title]=\"#002b36\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#b58900\"\n\n# Background color of selected items\ntheme[selected_bg]=\"#eee8d5\" \n\n# Foreground color of selected items\ntheme[selected_fg]=\"#b58900\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#eee8d5\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#d33682\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#93a1a1\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#93a1a1\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#93a1a1\"\n\n# Processes box outline color\ntheme[proc_box]=\"#93a1a1\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#93a1a1\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#268bd2\"\ntheme[temp_mid]=\"#ccb5f7\"\ntheme[temp_end]=\"#fc5378\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#adc700\"\ntheme[cpu_mid]=\"#d6a200\"\ntheme[cpu_end]=\"#e65317\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#4e5900\"\ntheme[free_mid]=\"\"\ntheme[free_end]=\"#bad600\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#114061\"\ntheme[cached_mid]=\"\"\ntheme[cached_end]=\"#268bd2\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#705500\"\ntheme[available_mid]=\"\"\ntheme[available_end]=\"#edb400\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#6e1718\"\ntheme[used_mid]=\"\"\ntheme[used_end]=\"#e02f30\"\n\n# Download graph colors\ntheme[download_start]=\"#3d4070\"\ntheme[download_mid]=\"#6c71c4\"\ntheme[download_end]=\"#a3a8f7\"\n\n# Upload graph colors\ntheme[upload_start]=\"#701c45\"\ntheme[upload_mid]=\"#d33682\"\ntheme[upload_end]=\"#f56caf\"\n"
  },
  {
    "path": "themes/tokyo-night.theme",
    "content": "# Theme: tokyo-night\n# By: Pascal Jaeger\n\n# Main bg\ntheme[main_bg]=\"#1a1b26\"\n\n# Main text color\ntheme[main_fg]=\"#cfc9c2\"\n\n# Title color for boxes\ntheme[title]=\"#cfc9c2\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#7dcfff\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#414868\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#cfc9c2\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#565f89\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#7dcfff\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#565f89\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#565f89\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#565f89\"\n\n# Processes box outline color\ntheme[proc_box]=\"#565f89\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#565f89\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#9ece6a\"\ntheme[temp_mid]=\"#e0af68\"\ntheme[temp_end]=\"#f7768e\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#9ece6a\"\ntheme[cpu_mid]=\"#e0af68\"\ntheme[cpu_end]=\"#f7768e\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#9ece6a\"\ntheme[free_mid]=\"#e0af68\"\ntheme[free_end]=\"#f7768e\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#9ece6a\"\ntheme[cached_mid]=\"#e0af68\"\ntheme[cached_end]=\"#f7768e\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#9ece6a\"\ntheme[available_mid]=\"#e0af68\"\ntheme[available_end]=\"#f7768e\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#9ece6a\"\ntheme[used_mid]=\"#e0af68\"\ntheme[used_end]=\"#f7768e\"\n\n# Download graph colors\ntheme[download_start]=\"#9ece6a\"\ntheme[download_mid]=\"#e0af68\"\ntheme[download_end]=\"#f7768e\"\n\n# Upload graph colors\ntheme[upload_start]=\"#9ece6a\"\ntheme[upload_mid]=\"#e0af68\"\ntheme[upload_end]=\"#f7768e\"\n"
  },
  {
    "path": "themes/tokyo-storm.theme",
    "content": "# Theme: tokyo-storm\n# By: Pascal Jaeger\n\n# Main bg\ntheme[main_bg]=\"#24283b\"\n\n# Main text color\ntheme[main_fg]=\"#cfc9c2\"\n\n# Title color for boxes\ntheme[title]=\"#cfc9c2\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#7dcfff\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#414868\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#cfc9c2\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#565f89\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#7dcfff\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#565f89\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#565f89\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#565f89\"\n\n# Processes box outline color\ntheme[proc_box]=\"#565f89\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#565f89\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#9ece6a\"\ntheme[temp_mid]=\"#e0af68\"\ntheme[temp_end]=\"#f7768e\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#9ece6a\"\ntheme[cpu_mid]=\"#e0af68\"\ntheme[cpu_end]=\"#f7768e\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#9ece6a\"\ntheme[free_mid]=\"#e0af68\"\ntheme[free_end]=\"#f7768e\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#9ece6a\"\ntheme[cached_mid]=\"#e0af68\"\ntheme[cached_end]=\"#f7768e\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#9ece6a\"\ntheme[available_mid]=\"#e0af68\"\ntheme[available_end]=\"#f7768e\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#9ece6a\"\ntheme[used_mid]=\"#e0af68\"\ntheme[used_end]=\"#f7768e\"\n\n# Download graph colors\ntheme[download_start]=\"#9ece6a\"\ntheme[download_mid]=\"#e0af68\"\ntheme[download_end]=\"#f7768e\"\n\n# Upload graph colors\ntheme[upload_start]=\"#9ece6a\"\ntheme[upload_mid]=\"#e0af68\"\ntheme[upload_end]=\"#f7768e\"\n"
  },
  {
    "path": "themes/tomorrow-night.theme",
    "content": "#Nord theme but using the Tomorrow Night palette\n#by Appuchia <contact@appu.ltd>\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#ffffff\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#1d1f21\"\n\n# Main text color\ntheme[main_fg]=\"#c5c8c6\"\n\n# Title color for boxes\ntheme[title]=\"#c5c8c6\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#81beb7\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#282a2e\"\n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#c5c8c6\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#373b41\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#969896\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#81a2be\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#81a2be\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#81a2be\"\n\n# Processes box outline color\ntheme[proc_box]=\"#81a2be\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#81a2be\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#b5bd68\"\ntheme[temp_mid]=\"#f0c674\"\ntheme[temp_end]=\"#cc6666\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#b5bd68\"\ntheme[cpu_mid]=\"#f0c674\"\ntheme[cpu_end]=\"#cc6666\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#b5bd68\"\ntheme[free_mid]=\"#f0c674\"\ntheme[free_end]=\"#cc6666\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#b5bd68\"\ntheme[cached_mid]=\"#f0c674\"\ntheme[cached_end]=\"#cc6666\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#b5bd68\"\ntheme[available_mid]=\"#f0c674\"\ntheme[available_end]=\"#cc6666\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#b5bd68\"\ntheme[used_mid]=\"#f0c674\"\ntheme[used_end]=\"#cc6666\"\n\n# Download graph colors\ntheme[download_start]=\"#b5bd68\"\ntheme[download_mid]=\"#f0c674\"\ntheme[download_end]=\"#cc6666\"\n\n# Upload graph colors\ntheme[upload_start]=\"#b5bd68\"\ntheme[upload_mid]=\"#f0c674\"\ntheme[upload_end]=\"#cc6666\"\n"
  },
  {
    "path": "themes/twilight.theme",
    "content": "# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#141414\"\n\n# Main text color\ntheme[main_fg]=\"#A7A7A7\"\n\n# Title color for boxes\ntheme[title]=\"#DAD085\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#CF6A4C\"\n\n# Background color of selected items\ntheme[selected_bg]=\"#3E3E3E\"\n\n# Foreground color of selected items\ntheme[selected_fg]=\"#8B98AB\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#828282\"\n\n# Color of text appearing on top of graphs, i.e uptime and current network graph scaling\ntheme[graph_text]=\"#C5AF75\"\n\n# Background color of the percentage meters\ntheme[meter_bg]=\"#3E3E3E\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#8F9D6A\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#8F9D6A\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#9B703F\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#CDA869\"\n\n# Processes box outline color\ntheme[proc_box]=\"#CF6A4C\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#494949\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#8F9D6A\"\ntheme[temp_mid]=\"#F9EE98\"\ntheme[temp_end]=\"#CF6A4C\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#8F9D6A\"\ntheme[cpu_mid]=\"#F9EE98\"\ntheme[cpu_end]=\"#CF6A4C\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#CF6A4C\"\ntheme[free_mid]=\"#F9EE98\"\ntheme[free_end]=\"#8F9D6A\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#8F9D6A\"\ntheme[cached_mid]=\"#F9EE98\"\ntheme[cached_end]=\"#CF6A4C\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#8F9D6A\"\ntheme[available_mid]=\"#F9EE98\"\ntheme[available_end]=\"#CF6A4C\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#8F9D6A\"\ntheme[used_mid]=\"#F9EE98\"\ntheme[used_end]=\"#CF6A4C\"\n\n# Download graph colors\ntheme[download_start]=\"#8F9D6A\"\ntheme[download_mid]=\"#F9EE98\"\ntheme[download_end]=\"#CF6A4C\"\n\n# Upload graph colors\ntheme[upload_start]=\"#8F9D6A\"\ntheme[upload_mid]=\"#F9EE98\"\ntheme[upload_end]=\"#CF6A4C\"\n\n# Process box color gradient for threads, mem and cpu usage\ntheme[process_start]=\"#8F9D6A\"\ntheme[process_mid]=\"#F9EE98\"\ntheme[process_end]=\"#CF6A4C\"\n\n# Process pause background color\ntheme[proc_pause_bg]=\"#CF6A4C\"\n\n# Process follow background color\ntheme[proc_follow_bg]=\"#7587A6\"\n\n# Process banner background color\ntheme[proc_banner_bg]=\"#3E3E3E\"\n\n# Process banner foreground color\ntheme[proc_banner_fg]=\"#A7A7A7\"\n\n# Followed process background color\ntheme[followed_bg]=\"#7587A6\"\n\n# Followed process foreground color\ntheme[followed_fg]=\"#A7A7A7\"\n"
  },
  {
    "path": "themes/whiteout.theme",
    "content": "#Bashtop \"whiteout\" theme\n#by aristocratos\n\n# Colors should be in 6 or 2 character hexadecimal or single spaced rgb decimal: \"#RRGGBB\", \"#BW\" or \"0-255 0-255 0-255\"\n# example for white: \"#FFFFFF\", \"#ff\" or \"255 255 255\".\n\n# All graphs and meters can be gradients\n# For single color graphs leave \"mid\" and \"end\" variable empty.\n# Use \"start\" and \"end\" variables for two color gradient\n# Use \"start\", \"mid\" and \"end\" for three color gradient\n\n# Main background, empty for terminal default, need to be empty if you want transparent background\ntheme[main_bg]=\"#ff\"\n\n# Main text color\ntheme[main_fg]=\"#30\"\n\n# Title color for boxes\ntheme[title]=\"#10\"\n\n# Highlight color for keyboard shortcuts\ntheme[hi_fg]=\"#284d75\"\n\n# Background color of selected item in processes box\ntheme[selected_bg]=\"#15283d\" \n\n# Foreground color of selected item in processes box\ntheme[selected_fg]=\"#ff\"\n\n# Color of inactive/disabled text\ntheme[inactive_fg]=\"#dd\"\n\n# Misc colors for processes box including mini cpu graphs, details memory graph and details status text\ntheme[proc_misc]=\"#03521d\"\n\n# Cpu box outline color\ntheme[cpu_box]=\"#1a361e\"\n\n# Memory/disks box outline color\ntheme[mem_box]=\"#3d3c14\"\n\n# Net up/down box outline color\ntheme[net_box]=\"#1a1742\"\n\n# Processes box outline color\ntheme[proc_box]=\"#3b1515\"\n\n# Box divider line and small boxes line color\ntheme[div_line]=\"#80\"\n\n# Temperature graph colors\ntheme[temp_start]=\"#184567\"\ntheme[temp_mid]=\"#122c87\"\ntheme[temp_end]=\"#9e0061\"\n\n# CPU graph colors\ntheme[cpu_start]=\"#0b8e44\"\ntheme[cpu_mid]=\"#a49104\"\ntheme[cpu_end]=\"#8d0202\"\n\n# Mem/Disk free meter\ntheme[free_start]=\"#b0d090\"\ntheme[free_mid]=\"#70ba26\"\ntheme[free_end]=\"#496600\"\n\n# Mem/Disk cached meter\ntheme[cached_start]=\"#26c5ff\"\ntheme[cached_mid]=\"#74e6fc\"\ntheme[cached_end]=\"#0b1a29\"\n\n# Mem/Disk available meter\ntheme[available_start]=\"#ffb814\"\ntheme[available_mid]=\"#ffd77a\"\ntheme[available_end]=\"#292107\"\n\n# Mem/Disk used meter\ntheme[used_start]=\"#ff4769\"\ntheme[used_mid]=\"#d9626d\"\ntheme[used_end]=\"#3b1f1c\"\n\n# Download graph colors\ntheme[download_start]=\"#8d82de\"\ntheme[download_mid]=\"#413786\"\ntheme[download_end]=\"#130f29\"\n\n# Upload graph colors\ntheme[upload_start]=\"#f590f9\"\ntheme[upload_mid]=\"#722e76\"\ntheme[upload_end]=\"#2b062d\""
  }
]