Переглянути джерело

refactor: restructure chat-vault to services architecture

tukuaiai 1 місяць тому
батько
коміт
318ae2b416
100 змінених файлів з 46288 додано та 293 видалено
  1. 145 14
      libs/external/chat-vault/.gitignore
  2. 5 0
      libs/external/chat-vault/.gitmodules
  3. 245 0
      libs/external/chat-vault/AGENTS.md
  4. 12 0
      libs/external/chat-vault/CLAUDE.md
  5. 1 1
      libs/external/chat-vault/LICENSE
  6. 103 278
      libs/external/chat-vault/README.md
  7. 9 0
      libs/external/chat-vault/Sublime-Text.txt
  8. 1 0
      libs/external/chat-vault/docs/architecture.md
  9. 1 0
      libs/external/chat-vault/docs/deployment.md
  10. 0 0
      libs/external/chat-vault/libs/common/models/.gitkeep
  11. 0 0
      libs/external/chat-vault/libs/common/utils/.gitkeep
  12. 0 0
      libs/external/chat-vault/libs/database/.gitkeep
  13. 0 0
      libs/external/chat-vault/monitoring/alertmanager/.gitkeep
  14. 7 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.editorconfig
  15. 12 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/FUNDING.yml
  16. 59 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/ISSUE_TEMPLATE/bug_report.md
  17. 22 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/ISSUE_TEMPLATE/feature_request.md
  18. 48 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/cmake-freebsd.yml
  19. 66 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/cmake-linux.yml
  20. 52 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/cmake-macos.yml
  21. 53 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/cmake-netbsd.yml
  22. 48 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/cmake-openbsd.yml
  23. 67 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/continuous-build-freebsd.yml
  24. 47 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/continuous-build-gpu.yml
  25. 87 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/continuous-build-linux.yml
  26. 64 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/continuous-build-macos.yml
  27. 63 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/continuous-build-netbsd.yml
  28. 56 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/continuous-build-openbsd.yml
  29. 47 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/test-snap-can-build.yml
  30. 90 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/.gitignore
  31. 624 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/CHANGELOG.md
  32. 275 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/CMakeLists.txt
  33. 93 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/CODE_OF_CONDUCT.md
  34. 57 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/CONTRIBUTING.md
  35. 111 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/Img/icon.svg
  36. 44 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/Img/logo.svg
  37. 202 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/LICENSE
  38. 1534 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/README.md
  39. 16 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/btop.desktop
  40. 23 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/cmake/Finddevstat.cmake
  41. 23 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/cmake/Findelf.cmake
  42. 23 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/cmake/Findkvm.cmake
  43. 23 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/cmake/Findproplib.cmake
  44. 27 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/LICENSE.rst
  45. 220 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/args.h
  46. 2994 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/base.h
  47. 2241 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/chrono.h
  48. 637 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/color.h
  49. 585 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/compile.h
  50. 5 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/core.h
  51. 1953 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/format-inl.h
  52. 4383 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/format.h
  53. 428 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/os.h
  54. 167 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/ostream.h
  55. 624 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/printf.h
  56. 852 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/ranges.h
  57. 707 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/std.h
  58. 356 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/xchar.h
  59. 1491 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/include/widechar_width.hpp
  60. 70 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/manpage.md
  61. 6 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/renovate.json
  62. 10 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/run.sh
  63. 64 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/snap/snapcraft.yaml
  64. 1188 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop.cpp
  65. 4 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop.hpp
  66. 216 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_cli.cpp
  67. 50 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_cli.hpp
  68. 831 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_config.cpp
  69. 135 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_config.hpp
  70. 2299 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_draw.cpp
  71. 141 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_draw.hpp
  72. 542 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_input.cpp
  73. 78 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_input.hpp
  74. 1800 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_menu.cpp
  75. 99 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_menu.hpp
  76. 292 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_shared.cpp
  77. 461 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_shared.hpp
  78. 454 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_theme.cpp
  79. 70 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_theme.hpp
  80. 714 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_tools.cpp
  81. 488 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_tools.hpp
  82. 10 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/config.h.in
  83. 1356 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/freebsd/btop_collect.cpp
  84. 3122 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/btop_collect.cpp
  85. 19 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/CMakeLists.txt
  86. 1318 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/drm.h
  87. 1318 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/drm_mode.h
  88. 3860 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/i915_drm.h
  89. 786 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/i915_pciids.h
  90. 67 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/i915_pciids_local.h
  91. 210 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/igt_perf.c
  92. 75 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/igt_perf.h
  93. 233 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/intel_chipset.h
  94. 653 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/intel_device_info.c
  95. 697 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/intel_gpu_top.c
  96. 95 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/intel_gpu_top.h
  97. 97 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/intel_name_lookup_shim.c
  98. 2 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/source.txt
  99. 218 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/xe_pciids.h
  100. 12 0
      libs/external/chat-vault/monitoring/grafana/monitor-tui/src/main.cpp

+ 145 - 14
libs/external/chat-vault/.gitignore

@@ -1,28 +1,159 @@
 # Python
 __pycache__/
 *.py[cod]
+*$py.class
 *.so
-*.egg-info/
-dist/
+*.jsonl
+.Python
 build/
-*.spec
-
-# Output
-output/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+*.csv
+*.zip
+*.jsonl
 *.db
-*.sqlite3
-*.log
+*.pyc
+*.png
+libs/database/csv/futures/
+*.jpg
 
-# Environment
-.env
-.venv/
+# Virtual Environment
+.venv
+env/
 venv/
+ENV/
+env.bak/
+venv.bak/
+.venv_telegram/
+*.gz
 
 # IDE
 .vscode/
 .idea/
+.github/
 *.swp
-
-# OS
+*.swo
+*~
 .DS_Store
-Thumbs.db
+
+# Testing
+.pytest_cache/
+.coverage
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+
+# Logs
+*.log
+*.log.[0-9]*
+*.out
+logs/*.log
+logs/*.out
+
+# 项目特定
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# pyenv
+.python-version
+
+# Celery
+*.pyc
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.env.local
+.env.*.local
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# backtest folder
+src/backtest/
+
+# Additional exclusions
+.history/
+.venv_patterns/
+logs/
+
+# src/telegram venv
+src/telegram/venv
+services/data-service/src/backtest/
+
+# Backup files
+*.bak
+*.tmp
+backups/gz/
+
+# Data service exclusions
+services/data-service/data/csv/缺口补齐/
+services/data-service/data/csv/backups/
+services/data-service/data/csv/exports/
+services/data-service/data/csv/futures/
+
+# OS-specific
+
+# OS-specific
+
+data/csv/缺口补齐
+data/csv/backups
+data/csv/exports
+data/csv/futures
+# Custom rule for metrics data
+services/data-service/data/csv/metrics/
+
+# Rust build artifacts (order-service)
+services/order-service/target/
+services/order-service/services/backend-service/target/
+
+# Frontend service node_modules
+services/order-service/services/frontend-service/node_modules/
+
+# order-service external vendor mirrors
+services/order-service/libs/external/
+
+# External vendor mirrors (mirror-only, never commit)
+# 默认忽略 external 下所有内容,但保留少量文档
+libs/external/*
+!libs/external/AGENTS.md
+!libs/external/README.md
+!libs/external/CLAUDE.md
+# 常见镜像目录(冗余标记,便于阅读)
+libs/external/backtrader-master/
+libs/external/CodeWeaver-main/
+libs/external/crypto-trading-open-main/
+libs/external/cryptofeed-master/
+libs/external/flowsurface-main/
+libs/external/freqtrade-develop/
+libs/external/hftbacktest-master/
+libs/external/hummingbot-master/
+libs/external/lean-master/
+libs/external/lightweight-charts-master/
+libs/external/qlib-main/
+libs/external/qstrader-master/
+libs/external/vnpy-master/
+libs/external/zipline-main/
+backups/archive

+ 5 - 0
libs/external/chat-vault/.gitmodules

@@ -0,0 +1,5 @@
+# Git Submodules
+# 示例:
+# [submodule "libs/external/some-lib"]
+#     path = libs/external/some-lib
+#     url = https://github.com/xxx/some-lib.git

+ 245 - 0
libs/external/chat-vault/AGENTS.md

@@ -0,0 +1,245 @@
+# AGENTS.md
+
+AI Agent 操作手册 - Chat Vault Monorepo
+
+---
+
+## 1. Mission & Scope(目标与边界)
+
+### 允许操作
+- 修改 `services/chat-vault/src/` 下的 Python 代码
+- 添加新的解析器到 `services/chat-vault/src/parsers/`
+- 更新文档 (`README.md`, `AGENTS.md`, `docs/`)
+- 修改配置示例 `.env.example`
+
+### 禁止操作
+- **禁止修改** `output/` 目录下的任何文件(数据库、日志)
+- **禁止修改** `.env` 文件(包含用户敏感配置)
+- **禁止修改** `libs/external/` 下的外部依赖镜像
+- **禁止删除** 现有解析器,除非明确要求
+
+### 敏感区域
+| 路径 | 说明 |
+|------|------|
+| `services/chat-vault/.env` | 用户配置,不得读取或修改 |
+| `services/chat-vault/output/` | 运行时数据,不得修改 |
+| `libs/external/` | 外部镜像,只读 |
+
+---
+
+## 2. Golden Path(推荐执行路径)
+
+```bash
+# 1. 进入服务目录
+cd services/chat-vault
+
+# 2. 首次运行(自动创建 venv 并安装依赖)
+python src/main.py
+
+# 3. 验证功能
+python src/main.py --stats
+
+# 4. 修改代码后测试
+python src/main.py              # 同步测试
+python src/main.py --search "test"  # 搜索测试
+
+# 5. 更新文档(如有变更)
+# 编辑 README.md, AGENTS.md, docs/schema.md
+```
+
+---
+
+## 3. Must-Run Commands(必须执行的命令)
+
+### 环境准备
+```bash
+cd services/chat-vault
+python src/main.py  # 首次运行自动安装依赖
+```
+
+### 依赖文件
+- `services/chat-vault/requirements.txt`
+  ```
+  python-dotenv>=1.0.0
+  watchdog>=3.0.0
+  tiktoken>=0.5.0
+  ```
+
+### 功能验证
+```bash
+# 同步一次
+python src/main.py
+
+# 查看统计
+python src/main.py --stats
+
+# 监控模式
+python src/main.py --watch
+```
+
+---
+
+## 4. Code Change Rules(修改约束)
+
+### 架构原则
+- 解析器必须继承 `parsers/base.py` 的 `SessionData` 数据结构
+- 新增 CLI 支持需在 `parsers/__init__.py` 中导出
+- 配置项通过 `config.py` 的 `CONFIG` 字典访问
+
+### 模块边界
+| 模块 | 职责 | 禁止 |
+|------|------|------|
+| `main.py` | CLI 入口、命令分发 | 不含业务逻辑 |
+| `config.py` | 路径检测、配置加载 | 不含 I/O 操作 |
+| `storage.py` | SQLite 读写、Token 计数 | 不含解析逻辑 |
+| `watcher.py` | 文件监控 | 不含存储逻辑 |
+| `parsers/*.py` | 各 CLI 格式解析 | 不含存储逻辑 |
+
+### 依赖添加规则
+- 新依赖必须添加到 `requirements.txt`
+- 优先使用标准库
+- 避免引入大型框架
+
+### 兼容性要求
+- Python 3.8+ 兼容
+- 跨平台:Linux / macOS / Windows (WSL)
+- WSL 路径格式:`\\wsl.localhost\Ubuntu\...`
+
+---
+
+## 5. Style & Quality(风格与质量)
+
+### 代码风格
+- 文件头:`#!/usr/bin/env python3` + `# -*- coding: utf-8 -*-`
+- 缩进:4 空格
+- 行宽:建议 100 字符
+- 命名:snake_case(函数/变量),PascalCase(类)
+
+### 文档要求
+- 每个模块需有 docstring 说明用途
+- 公开函数需有参数/返回值说明
+- 复杂逻辑需有行内注释
+
+### 错误处理
+- 解析失败记录到日志,不中断流程
+- 使用 `logger.py` 的 `get_logger()` 记录
+
+---
+
+## 6. Project Map(项目结构速览)
+
+```
+chat-vault/
+├── services/chat-vault/       # 核心服务
+│   ├── src/
+│   │   ├── main.py           # 入口:CLI 命令分发
+│   │   ├── config.py         # 配置:路径检测、环境变量
+│   │   ├── storage.py        # 存储:SQLite + tiktoken
+│   │   ├── watcher.py        # 监控:watchdog 封装
+│   │   ├── logger.py         # 日志:统一日志配置
+│   │   └── parsers/
+│   │       ├── __init__.py   # 导出所有解析器
+│   │       ├── base.py       # SessionData 数据结构
+│   │       ├── codex.py      # Codex CLI 解析
+│   │       ├── kiro.py       # Kiro CLI 解析
+│   │       ├── gemini.py     # Gemini CLI 解析
+│   │       └── claude.py     # Claude CLI 解析
+│   ├── docs/
+│   │   ├── schema.md         # 数据库结构文档
+│   │   ├── roadmap.md        # 开发路线图
+│   │   └── AI_PROMPT.md      # AI 助手指南
+│   ├── requirements.txt      # Python 依赖
+│   ├── .env.example          # 配置示例
+│   ├── start.sh              # Linux/macOS 启动脚本
+│   └── start.bat             # Windows 启动脚本
+├── libs/                      # 共享库(预留)
+├── monitoring/                # 监控配置(预留)
+├── scripts/                   # 全局脚本
+├── README.md                  # 项目说明
+└── AGENTS.md                  # 本文件
+```
+
+### 关键入口
+- **CLI 入口**: `services/chat-vault/src/main.py`
+- **配置加载**: `services/chat-vault/src/config.py` → `CONFIG` 字典
+- **数据库**: `services/chat-vault/output/chat_history.db`
+
+---
+
+## 7. Common Pitfalls(常见问题)
+
+| 问题 | 原因 | 解决 |
+|------|------|------|
+| `ModuleNotFoundError` | 未在 venv 中运行 | 运行 `python src/main.py` 自动创建 venv |
+| 路径未检测到 | 默认路径不存在 | 在 `.env` 中配置 `CODEX_PATHS` 等 |
+| WSL 路径失败 | 格式错误 | 使用 `\\wsl.localhost\Ubuntu\...` 格式 |
+| Token 计数为 0 | tiktoken 未安装 | 检查 `requirements.txt` 是否包含 tiktoken |
+| 数据库锁定 | 多进程同时写入 | 确保只有一个实例运行 |
+
+---
+
+## 8. PR / Commit Rules(提交规则)
+
+### Commit Message 格式
+```
+<type>(<scope>): <description>
+
+type: feat|fix|docs|refactor|test|chore
+scope: chat-vault|parsers|storage|config|docs
+```
+
+示例:
+```
+feat(parsers): add support for new CLI format
+fix(storage): handle empty message array
+docs(readme): update quick start section
+```
+
+### 分支策略
+- `main`: 稳定版本
+- `dev`: 开发分支
+- `feature/*`: 功能分支
+
+---
+
+## 9. Documentation Sync Rule(文档同步规则)
+
+### 强制同步
+以下变更必须同步更新文档:
+
+| 变更类型 | 需更新文档 |
+|----------|-----------|
+| 新增命令行参数 | README.md, AGENTS.md |
+| 新增解析器 | README.md (功能特性), AGENTS.md (Project Map) |
+| 数据库结构变更 | docs/schema.md |
+| 配置项变更 | README.md (配置说明), .env.example |
+| 目录结构变更 | README.md, AGENTS.md |
+
+### 不确定时
+- 使用 `TODO: 需确认 <具体问题>` 标注
+- 不允许猜测或编造
+
+---
+
+## 10. Quick Reference(速查)
+
+```bash
+# 同步
+python src/main.py
+
+# 监控
+python src/main.py --watch
+
+# 统计
+python src/main.py --stats
+
+# 搜索
+python src/main.py --search "关键词"
+
+# 导出
+python src/main.py --export json
+python src/main.py --export csv --source codex
+
+# 清理
+python src/main.py --prune
+```

+ 12 - 0
libs/external/chat-vault/CLAUDE.md

@@ -0,0 +1,12 @@
+# CLAUDE.md
+
+Claude 持久上下文文件
+
+## 项目概述
+这是一个 monorepo 项目,包含多个微服务。
+
+## 目录结构
+- services/ - 微服务
+- libs/ - 共享库
+- infrastructure/ - 基础设施配置
+- monitoring/ - 监控系统

+ 1 - 1
libs/external/chat-vault/LICENSE

@@ -1,6 +1,6 @@
 MIT License
 
-Copyright (c) 2024
+Copyright (c) 2025
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal

+ 103 - 278
libs/external/chat-vault/README.md

@@ -1,318 +1,143 @@
-<div align="center">
-
-# 🔐 Chat Vault
-
-**One tool to save ALL your AI chat history**
-
-[![Python](https://img.shields.io/badge/Python-3.8+-blue.svg)](https://python.org)
-[![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
-[![Platform](https://img.shields.io/badge/Platform-Linux%20%7C%20macOS%20%7C%20Windows-lightgrey.svg)]()
-[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)]()
-
-[English](README.md) | [中文](README_CN.md)
-
-[✨ Features](#-features) •
-[🚀 Quick Start](#-quick-start) •
-[📋 Commands](#-commands) •
-[📁 Project Structure](#-project-structure) •
-[❓ FAQ](#-faq)
-
-[📞 Contact](#-contact) •
-[✨ Support](#-support) •
-[🤝 Contributing](#-contributing)
-
-AI-powered docs: [zread.ai/tukuaiai/chat-vault](https://zread.ai/tukuaiai/chat-vault)
-
-> 📦 This tool is part of [vibe-coding-cn](https://github.com/tukuaiai/vibe-coding-cn) - A comprehensive Vibe Coding guide
-
-</div>
-
----
-
-## ✨ Features
-
-<table>
-<tr>
-<td>🔄 <b>Multi-CLI</b></td>
-<td>Codex, Kiro, Gemini, Claude - all supported</td>
-</tr>
-<tr>
-<td>⚡ <b>Real-time</b></td>
-<td>Watch mode with system-level file monitoring</td>
-</tr>
-<tr>
-<td>🔢 <b>Token Stats</b></td>
-<td>Accurate counting using tiktoken (cl100k_base)</td>
-</tr>
-<tr>
-<td>🔍 <b>Search</b></td>
-<td>Find any conversation instantly</td>
-</tr>
-<tr>
-<td>📤 <b>Export</b></td>
-<td>JSON or CSV, your choice</td>
-</tr>
-<tr>
-<td>🚀 <b>Zero Config</b></td>
-<td>Auto-detects paths, just run it</td>
-</tr>
-</table>
-
----
-
-## 🏗️ Architecture
-
-```mermaid
-graph LR
-    subgraph Sources
-        A[~/.codex] 
-        B[~/.kiro]
-        C[~/.gemini]
-        D[~/.claude]
-    end
-    
-    subgraph Chat Vault
-        E[Watcher]
-        F[Parsers]
-        G[Storage]
-    end
-    
-    subgraph Output
-        H[(SQLite DB)]
-    end
-    
-    A --> E
-    B --> E
-    C --> E
-    D --> E
-    E --> F
-    F --> G
-    G --> H
-```
+# Chat Vault Monorepo
 
----
+AI 聊天记录集中存储与管理平台。
 
-## 🔄 How It Works
+## 项目概述
 
-```mermaid
-sequenceDiagram
-    participant User
-    participant CLI as AI CLI (Codex/Kiro/...)
-    participant Watcher
-    participant Parser
-    participant DB as SQLite
+本项目是一个 monorepo,包含 AI 聊天记录同步工具及相关基础设施。核心功能是将多个 AI CLI 工具(Codex、Kiro、Gemini、Claude)的聊天记录统一存储到 SQLite 数据库。
 
-    User->>CLI: Chat with AI
-    CLI->>CLI: Save to local file
-    Watcher->>Watcher: Detect file change
-    Watcher->>Parser: Parse new content
-    Parser->>DB: Upsert session
-    DB-->>User: Query anytime
-```
+## 功能特性
 
----
+- 多 CLI 支持:Codex、Kiro、Gemini、Claude
+- 实时监控:基于 watchdog 的文件变更检测
+- Token 统计:使用 tiktoken (cl100k_base) 精确计数
+- 搜索导出:支持关键词搜索、JSON/CSV 导出
+- 零配置:自动检测默认路径,开箱即用
 
-## 🚀 Quick Start
+## 快速开始
 
-### 30 Seconds Setup
+### 环境要求
 
-```bash
-# Clone
-git clone https://github.com/tukuaiai/vibe-coding-cn.git
-cd vibe-coding-cn/libs/external/chat-vault
+- Python 3.8+
+- Linux / macOS / Windows (WSL)
 
-# Run (auto-installs dependencies)
-./start.sh        # Linux/macOS
-start.bat         # Windows
-```
+### 启动服务
 
-**That's it!** 🎉
-
----
+```bash
+cd services/chat-vault
 
-## 📊 Example Output
+# Linux/macOS
+./start.sh
 
-```
-==================================================
-AI 聊天记录 → 集中存储
-==================================================
-数据库: ./output/chat_history.db
-
-[Codex] 新增:1241 更新:0 跳过:0 错误:0
-[Kiro] 新增:21 更新:0 跳过:0 错误:0
-[Gemini] 新增:332 更新:0 跳过:0 错误:0
-[Claude] 新增:168 更新:0 跳过:0 错误:0
-
-==================================================
-总计: 1762 会话, 40000+ 消息
-✓ 同步完成!
-
-=== Token 统计 (tiktoken) ===
-  codex: 11,659,952 tokens
-  kiro: 26,337 tokens
-  gemini: 3,195,821 tokens
-  claude: 29,725 tokens
-  总计: 14,911,835 tokens
+# Windows
+start.bat
 ```
 
----
+首次运行会自动创建虚拟环境并安装依赖。
 
-## 📋 Commands
-
-| Command | Description |
-|---------|-------------|
-| `python src/main.py` | Sync once |
-| `python src/main.py -w` | Watch mode (real-time) |
-| `python src/main.py --stats` | Show statistics |
-| `python src/main.py --search "keyword"` | Search messages |
-| `python src/main.py --export json` | Export to JSON |
-| `python src/main.py --export csv --source codex` | Export specific source |
-| `python src/main.py --prune` | Clean orphaned records |
-
----
-
-## 📁 Project Structure
+## 目录结构
 
 ```
 chat-vault/
-├── 🚀 start.sh / start.bat    # One-click start
-├── 📦 build.py                # Build standalone exe
-├── 📂 src/
-│   ├── main.py                # CLI entry
-│   ├── config.py              # Auto-detection
-│   ├── storage.py             # SQLite + tiktoken
-│   ├── watcher.py             # File monitoring
-│   └── parsers/               # CLI parsers
-├── 📂 docs/
-│   ├── AI_PROMPT.md           # AI assistant guide
-│   └── schema.md              # Database schema
-└── 📂 output/
-    ├── chat_history.db        # Your database
-    └── logs/                   # Sync logs
+├── services/
+│   └── chat-vault/          # 核心同步服务
+│       ├── src/
+│       │   ├── main.py      # CLI 入口
+│       │   ├── config.py    # 配置与路径检测
+│       │   ├── storage.py   # SQLite 存储
+│       │   ├── watcher.py   # 文件监控
+│       │   └── parsers/     # 各 CLI 解析器
+│       ├── docs/            # 服务文档
+│       ├── scripts/         # 辅助脚本
+│       ├── requirements.txt
+│       ├── start.sh
+│       └── .env.example
+├── libs/
+│   ├── common/              # 共享库(预留)
+│   ├── database/            # 数据库工具(预留)
+│   └── external/            # 外部依赖镜像
+├── monitoring/
+│   ├── grafana/             # Grafana 配置
+│   ├── prometheus/          # Prometheus 配置(预留)
+│   └── alertmanager/        # 告警配置(预留)
+├── scripts/                 # 全局脚本
+│   ├── build_all.sh
+│   ├── test_all.sh
+│   └── deploy.sh
+├── docs/                    # 全局文档
+├── AGENTS.md
+├── README.md
+└── LICENSE
 ```
 
----
-
-## 🗄️ Database Schema
-
-```mermaid
-erDiagram
-    sessions {
-        TEXT file_path PK
-        TEXT session_id
-        TEXT source
-        TEXT cwd
-        TEXT messages
-        INTEGER file_mtime
-        TEXT start_time
-        INTEGER token_count
-    }
-    
-    meta {
-        TEXT key PK
-        TEXT value
-    }
-    
-    meta_codex {
-        TEXT key PK
-        TEXT value
-    }
-```
-
----
-
-## 🤖 For AI Assistants
-
-Send [docs/AI_PROMPT.md](docs/AI_PROMPT.md) to your AI assistant for:
-- SQL query examples
-- Python code snippets
-- Task guidance
+## 常用命令
 
----
+在 `services/chat-vault/` 目录下执行:
 
-## ❓ FAQ
+| 命令 | 说明 |
+|------|------|
+| `python src/main.py` | 同步一次 |
+| `python src/main.py -w` | 持续监控模式 |
+| `python src/main.py --stats` | 显示统计信息 |
+| `python src/main.py --search "关键词"` | 搜索消息 |
+| `python src/main.py --export json` | 导出 JSON |
+| `python src/main.py --export csv --source codex` | 导出指定来源 |
+| `python src/main.py --prune` | 清理孤立记录 |
 
-<details>
-<summary><b>Do I need to configure anything?</b></summary>
+## 配置说明
 
-No. Auto-detects `~/.codex`, `~/.kiro`, `~/.gemini`, `~/.claude`
-</details>
+### 环境变量(可选)
 
-<details>
-<summary><b>Does it work with WSL?</b></summary>
+参考 `services/chat-vault/.env.example`:
 
-Yes! Paths like `\\wsl.localhost\Ubuntu\...` are supported
-</details>
-
-<details>
-<summary><b>How do I view the database?</b></summary>
-
-Use [DB Browser for SQLite](https://sqlitebrowser.org/) or any SQLite tool
-</details>
-
-<details>
-<summary><b>Is my data safe?</b></summary>
-
-Yes. We only READ from AI tools, never modify original files
-</details>
-
----
-
-## 📞 Contact
-
-- **GitHub**: [tukuaiai](https://github.com/tukuaiai)
-- **Twitter / X**: [123olp](https://x.com/123olp)
-- **Telegram**: [@desci0](https://t.me/desci0)
-- **Telegram Group**: [glue_coding](https://t.me/glue_coding)
-- **Telegram Channel**: [tradecat_ai_channel](https://t.me/tradecat_ai_channel)
-- **Email**: tukuai.ai@gmail.com
-
----
-
-## ✨ Support
-
-If this project helped you, consider supporting:
-
-- **Binance UID**: `572155580`
-- **Tron (TRC20)**: `TQtBXCSTwLFHjBqTS4rNUp7ufiGx51BRey`
-- **Solana**: `HjYhozVf9AQmfv7yv79xSNs6uaEU5oUk2USasYQfUYau`
-- **Ethereum (ERC20)**: `0xa396923a71ee7D9480b346a17dDeEb2c0C287BBC`
-- **BNB Smart Chain (BEP20)**: `0xa396923a71ee7D9480b346a17dDeEb2c0C287BBC`
-- **Bitcoin**: `bc1plslluj3zq3snpnnczplu7ywf37h89dyudqua04pz4txwh8z5z5vsre7nlm`
-- **Sui**: `0xb720c98a48c77f2d49d375932b2867e793029e6337f1562522640e4f84203d2e`
-
----
+```bash
+# 自定义路径(逗号分隔多个)
+CODEX_PATHS=~/.codex/sessions
+KIRO_PATHS=~/.local/share/kiro-cli
+GEMINI_PATHS=~/.gemini/tmp
+CLAUDE_PATHS=~/.claude
+
+# WSL 路径支持
+CODEX_PATHS=\\wsl.localhost\Ubuntu\home\user\.codex\sessions
+```
 
-## 🤝 Contributing
+默认自动检测以下路径:
+- Codex: `~/.codex/sessions`, `~/.codex`
+- Kiro: `~/.local/share/kiro-cli`
+- Gemini: `~/.gemini/tmp`, `~/.gemini`
+- Claude: `~/.claude`
 
-We welcome all contributions! Feel free to open an [Issue](https://github.com/tukuaiai/vibe-coding-cn/issues) or submit a [Pull Request](https://github.com/tukuaiai/vibe-coding-cn/pulls).
+### 输出位置
 
----
+- 数据库:`services/chat-vault/output/chat_history.db`
+- 日志:`services/chat-vault/output/logs/`
 
-## 📄 License
+## 数据库结构
 
-[MIT](LICENSE) - Do whatever you want with it.
+详见 `services/chat-vault/docs/schema.md`
 
----
+主表 `sessions`:
+- `file_path` (PK): 源文件路径
+- `session_id`: 会话 ID
+- `source`: 来源 (codex/kiro/gemini/claude)
+- `messages`: JSON 消息数组
+- `token_count`: Token 数量
 
-<div align="center">
+## FAQ
 
-**If this helped you, give it a ⭐!**
+**Q: 需要配置吗?**
+A: 不需要,自动检测默认路径。
 
-## Star History
+**Q: 支持 WSL 吗?**
+A: 支持,`\\wsl.localhost\Ubuntu\...` 格式路径会自动转换。
 
-<a href="https://www.star-history.com/#tukuaiai/vibe-coding-cn&type=Date">
- <picture>
-   <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=tukuaiai/vibe-coding-cn&type=Date&theme=dark" />
-   <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=tukuaiai/vibe-coding-cn&type=Date" />
-   <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=tukuaiai/vibe-coding-cn&type=Date" />
- </picture>
-</a>
+**Q: 数据安全吗?**
+A: 只读取 AI 工具的文件,不修改原始数据。
 
----
+## 贡献
 
-**Made with ❤️ by [tukuaiai](https://github.com/tukuaiai)**
+欢迎提交 Issue 和 Pull Request。
 
-[⬆ Back to Top](#-chat-vault)
+## 许可证
 
-</div>
+MIT License

+ 9 - 0
libs/external/chat-vault/Sublime-Text.txt

@@ -0,0 +1,9 @@
+# Sublime-Text.txt
+# 需求和注意事项,给自己看的 ^_^
+
+## 会话恢复指令
+# TODO: 添加CLI会话恢复指令
+
+## 需求记录
+
+## 注意事项

+ 1 - 0
libs/external/chat-vault/docs/architecture.md

@@ -0,0 +1 @@
+# 架构文档

+ 1 - 0
libs/external/chat-vault/docs/deployment.md

@@ -0,0 +1 @@
+# 部署文档

+ 0 - 0
libs/external/chat-vault/libs/common/models/.gitkeep


+ 0 - 0
libs/external/chat-vault/libs/common/utils/.gitkeep


+ 0 - 0
libs/external/chat-vault/libs/database/.gitkeep


+ 0 - 0
libs/external/chat-vault/monitoring/alertmanager/.gitkeep


+ 7 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.editorconfig

@@ -0,0 +1,7 @@
+[*.{cpp,h,hpp,sh,md,cfg,sample}]
+indent_style = tab
+indent_size = 4
+
+[*.{yml,yaml}]
+indent_style = space
+indent_size = 2

+ 12 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/FUNDING.yml

@@ -0,0 +1,12 @@
+# These are supported funding model platforms
+
+github: aristocratos
+patreon: # Replace with a single Patreon username
+open_collective: # Replace with a single Open Collective username
+ko_fi: aristocratos
+tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
+community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
+liberapay: # Replace with a single Liberapay username
+issuehunt: # Replace with a single IssueHunt username
+otechie: # Replace with a single Otechie username
+custom: https://paypal.me/aristocratos

+ 59 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/ISSUE_TEMPLATE/bug_report.md

@@ -0,0 +1,59 @@
+---
+name: Bug report
+about: Create a report to help us improve
+labels: bug
+
+---
+
+**Read the README.md and search for similar issues before posting a bug report!**
+
+<!-- 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. -->
+
+**Describe the bug**
+
+<!-- A clear and concise description of what the bug is. -->
+
+**To Reproduce**
+
+<!-- Steps to reproduce the behavior. ->
+
+**Expected behavior**
+
+<!-- A clear and concise description of what you expected to happen. -->
+
+**Screenshots**
+
+<!-- If applicable, add screenshots to help explain your problem. -->
+
+**Info (please complete the following information):**
+ - btop++ version: `btop --version`
+   - If using snap: `snap info btop`
+ - Binary: [self compiled or static binary from release]
+ - Architecture: [x86_64, aarch64, etc.] `uname -m`
+ - Platform: [Linux, FreeBSD, OsX]
+ - (Linux) Kernel: `uname -r`
+ - (OSX/FreeBSD) Os release version:
+ - Terminal used:
+ - Font used:
+
+**Additional context**
+
+<!-- Contents of `~/.local/state/btop.log` -->
+
+<!-- Note: The snap uses: `~/snap/btop/current/.local/state/btop.log` -->
+
+<!-- (try running btop with `--debug` flag if btop.log is empty) -->
+
+**GDB Backtrace**
+
+<!-- If btop++ is crashing at start the following steps could be helpful: -->
+
+<!-- (Extra helpful if compiled with `make OPTFLAGS="-O0 -g"`) -->
+
+<!-- 1. run (linux): `gdb btop` (macos): `lldb btop` -->
+
+<!-- 2. `r` to run, wait for crash and press enter if prompted, CTRL+L to clear screen if needed. -->
+
+<!-- 3. (gdb): `thread apply all bt` (lldb): `bt all` to get backtrace for all threads -->
+
+<!-- 4. Copy and paste the backtrace here: -->

+ 22 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/ISSUE_TEMPLATE/feature_request.md

@@ -0,0 +1,22 @@
+---
+name: Feature request
+about: Suggest an idea for this project
+labels: feature
+
+---
+
+**Is your feature request related to a problem? Please describe.**
+
+<!-- A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] -->
+
+**Describe the solution you'd like**
+
+<!-- A clear and concise description of what you want to happen. -->
+
+**Describe alternatives you've considered**
+
+<!-- A clear and concise description of any alternative solutions or features you've considered. -->
+
+**Additional context**
+
+<!-- Add any other context or screenshots about the feature request here. -->

+ 48 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/cmake-freebsd.yml

@@ -0,0 +1,48 @@
+name: FreeBSD CMake
+
+on:
+  push:
+    branches: main
+    tags-ignore: '*.*'
+    paths:
+      - '.github/workflows/cmake-freebsd.yml'
+      - 'CMakeLists.txt'
+      - 'cmake/**'
+      - 'include/**'
+      - 'src/*pp'
+      - 'src/freebsd/*pp'
+  pull_request:
+    branches: main
+    paths:
+      - '.github/workflows/cmake-freebsd.yml'
+      - 'CMakeLists.txt'
+      - 'cmake/**'
+      - 'include/**'
+      - 'src/*pp'
+      - 'src/freebsd/*pp'
+
+jobs:
+  build:
+    name: freebsd-${{ matrix.version}}-${{ matrix.arch}}
+    runs-on: ubuntu-24.04
+    concurrency:
+      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ matrix.arch }}-${{ matrix.version }}
+      cancel-in-progress: true
+    strategy:
+      matrix:
+        arch: ['aarch64', 'x86_64']
+        version: ['14.3', '15.0']
+    steps:
+      - uses: actions/checkout@v6
+
+      - name: Compile
+        uses: vmactions/freebsd-vm@v1
+        with:
+          arch: ${{ matrix.arch }}
+          release: ${{ matrix.version }}
+          usesh: true
+          prepare: pkg install -y cmake git ninja
+          run: |
+            cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug
+            cmake --build build --verbose
+            ctest --test-dir build

+ 66 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/cmake-linux.yml

@@ -0,0 +1,66 @@
+name: Linux CMake
+
+on:
+  push:
+    branches: main
+    tags-ignore: '*.*'
+    paths:
+      - '.github/workflows/cmake-linux.yml'
+      - 'CMakeLists.txt'
+      - 'cmake/**'
+      - 'include/**'
+      - 'src/*pp'
+      - 'src/linux/*pp'
+  pull_request:
+    branches: main
+    paths:
+      - '.github/workflows/cmake-linux.yml'
+      - 'CMakeLists.txt'
+      - 'cmake/**'
+      - 'include/**'
+      - 'src/*pp'
+      - 'src/linux/*pp'
+
+jobs:
+  build:
+    name: ${{ matrix.compiler }}-${{ matrix.version }}
+    runs-on: ubuntu-24.04
+    concurrency:
+      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ matrix.compiler }}-${{ matrix.version }}
+      cancel-in-progress: true
+    strategy:
+      matrix:
+        include:
+          - compiler: clang
+            version: 19
+          - compiler: clang
+            version: 20
+          - compiler: clang
+            version: 21
+          - compiler: gcc
+            version: 14
+    steps:
+      - uses: actions/checkout@v6
+
+      - name: Install clang ${{ matrix.version }}
+        if: ${{ matrix.compiler == 'clang' }}
+        run: wget -qO - https://apt.llvm.org/llvm.sh | sudo bash -s -- ${{ matrix.version }} all
+
+      - name: Configure
+        run: |
+          if [[ "${{ matrix.compiler }}" == "clang" ]]; then
+            export CC=clang-${{ matrix.version }}
+            export CXX=clang++-${{ matrix.version }}
+            export CXXFLAGS="-stdlib=libc++"
+            export LDFLAGS="-fuse-ld=lld -rtlib=compiler-rt -unwindlib=libunwind"
+          else
+            export CC=gcc-${{ matrix.version }}
+            export CXX=g++-${{ matrix.version }}
+          fi
+          cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug
+
+      - name: Compile
+        run: cmake --build build --verbose
+
+      - name: Test
+        run: ctest --test-dir build

+ 52 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/cmake-macos.yml

@@ -0,0 +1,52 @@
+name: macOS CMake
+
+on:
+  push:
+    branches: main
+    tags-ignore: '*.*'
+    paths:
+      - '.github/workflows/cmake-macos.yml'
+      - 'CMakeLists.txt'
+      - 'cmake/**'
+      - 'include/**'
+      - 'src/*pp'
+      - 'src/osx/*pp'
+  pull_request:
+    branches: main
+    paths:
+      - '.github/workflows/cmake-macos.yml'
+      - 'CMakeLists.txt'
+      - 'cmake/**'
+      - 'include/**'
+      - 'src/*pp'
+      - 'src/osx/*pp'
+
+jobs:
+  cmake_build_on_macos:
+    runs-on: macos-15
+    concurrency:
+      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+      cancel-in-progress: true
+    steps:
+      - uses: actions/checkout@v6
+
+      - name: Install build tools
+        run: |
+          export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1
+          brew update --quiet
+          brew install --force --overwrite cmake llvm lld ninja
+
+      - name: Configure
+        run: |
+          export LLVM_PREFIX="$(brew --prefix llvm)"
+          export LLD_PREFIX="$(brew --prefix lld)"
+          export CXX="$LLVM_PREFIX/bin/clang++"
+          export CPPFLAGS="-I$LLVM_PREFIX/include"
+          export LDFLAGS="-L$LLVM_PREFIX/lib -L$LLVM_PREFIX/lib/c++ -Wl,-rpath,$LLVM_PREFIX/lib/c++ -fuse-ld=$LLD_PREFIX/bin/ld64.lld"
+          cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug
+
+      - name: Compile
+        run: cmake --build build --verbose
+
+      - name: Test
+        run: ctest --test-dir build

+ 53 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/cmake-netbsd.yml

@@ -0,0 +1,53 @@
+name: NetBSD CMake
+
+on:
+  push:
+    branches: main
+    tags-ignore: '*.*'
+    paths:
+      - '.github/workflows/cmake-netbsd.yml'
+      - 'CMakeLists.txt'
+      - 'cmake/**'
+      - 'include/**'
+      - 'src/*pp'
+      - 'src/netbsd/*pp'
+  pull_request:
+    branches: main
+    paths:
+      - '.github/workflows/cmake-netbsd.yml'
+      - 'CMakeLists.txt'
+      - 'cmake/**'
+      - 'include/**'
+      - 'src/*pp'
+      - 'src/netbsd/*pp'
+
+jobs:
+  build:
+    name: netbsd-${{ matrix.version }}-${{ matrix.arch }}
+    runs-on: ubuntu-24.04
+    concurrency:
+      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ matrix.arch }}-${{ matrix.version }}
+      cancel-in-progress: true
+    strategy:
+      matrix:
+        arch: ['aarch64', 'amd64']
+        version: ['10.1']
+    steps:
+      - uses: actions/checkout@v6
+
+      - name: Compile
+        uses: vmactions/netbsd-vm@v1
+        with:
+          arch: ${{ matrix.arch }}
+          release: ${{ matrix.version }}
+          usesh: true
+          prepare: |
+            export PATH="/usr/pkg/sbin:/usr/pkg/bin:$PATH"
+            export PKG_PATH="https://ftp.netbsd.org/pub/pkgsrc/packages/NetBSD/${{ matrix.arch }}/${{ matrix.version }}/All/"
+            /usr/sbin/pkg_add pkgin
+            pkgin -y install cmake gcc14 git ninja-build
+          run: |
+            export CXX="/usr/pkg/gcc14/bin/g++"
+            cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug
+            cmake --build build --verbose
+            ctest --test-dir build

+ 48 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/cmake-openbsd.yml

@@ -0,0 +1,48 @@
+name: OpenBSD CMake
+
+on:
+  push:
+    branches: main
+    tags-ignore: '*.*'
+    paths:
+      - '.github/workflows/cmake-openbsd.yml'
+      - 'CMakeLists.txt'
+      - 'cmake/**'
+      - 'include/**'
+      - 'src/*pp'
+      - 'src/openbsd/*pp'
+  pull_request:
+    branches: main
+    paths:
+      - '.github/workflows/cmake-openbsd.yml'
+      - 'CMakeLists.txt'
+      - 'cmake/**'
+      - 'include/**'
+      - 'src/*pp'
+      - 'src/openbsd/*pp'
+
+jobs:
+  build:
+    name: openbsd-${{ matrix.version}}-${{ matrix.arch}}
+    runs-on: ubuntu-24.04
+    concurrency:
+      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ matrix.arch }}-${{ matrix.version }}
+      cancel-in-progress: true
+    strategy:
+      matrix:
+        arch: ['aarch64', 'x86_64']
+        version: ['7.8']
+    steps:
+      - uses: actions/checkout@v6
+
+      - name: Compile
+        uses: vmactions/openbsd-vm@v1
+        with:
+          arch: ${{ matrix.arch }}
+          release: ${{ matrix.version }}
+          usesh: true
+          prepare: pkg_add cmake git ninja
+          run: |
+            cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug
+            cmake --build build --verbose
+            ctest --test-dir build

+ 67 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/continuous-build-freebsd.yml

@@ -0,0 +1,67 @@
+name: Continuous Build FreeBSD
+
+on:
+  workflow_dispatch:
+  push:
+    branches:
+      - main
+    tags-ignore:
+      - '*.*'
+    paths:
+      - 'src/**'
+      - '!src/linux/**'
+      - '!src/osx/**'
+      - '!src/netbsd/**'
+      - '!src/openbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/continuous-build-freebsd.yml'
+  pull_request:
+    branches:
+      - main
+    paths:
+      - 'src/**'
+      - '!src/linux/**'
+      - '!src/osx/**'
+      - '!src/netbsd/**'
+      - '!src/openbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/continuous-build-freebsd.yml'
+
+jobs:
+  build-freebsd:
+    runs-on: ubuntu-24.04
+    timeout-minutes: 20
+    strategy:
+      matrix:
+        compiler: ["clang++", "g++"]
+    steps:
+      - uses: actions/checkout@v6
+
+      - name: Compile
+        uses: vmactions/freebsd-vm@v1
+        with:
+          release: '14.3'
+          usesh: true
+          prepare: |
+            pkg install -y gmake gcc15 coreutils git lowdown
+            git config --global --add safe.directory /home/runner/work/btop/btop
+          run: |
+            if [ "${{ matrix.compiler }}" == "g++" ]; then
+              CXX=g++15
+              COMPILER=gcc
+            else
+              CXX=clang++
+              COMPILER=llvm
+            fi
+            gmake STATIC=true STRIP=true
+            GIT_HASH=$(git rev-parse --short "$GITHUB_SHA")
+            mv bin/btop bin/btop-"$COMPILER"-"$GIT_HASH"
+            ls -alh bin
+
+      - uses: actions/upload-artifact@v5
+        with:
+          name: btop-x86_64-freebsd-14-${{ matrix.compiler }}
+          path: 'bin/*'
+          if-no-files-found: error

+ 47 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/continuous-build-gpu.yml

@@ -0,0 +1,47 @@
+name: Continuous Build Gpu
+
+on:
+  workflow_dispatch:
+  push:
+    branches:
+      - main
+    tags-ignore:
+      - '*.*'
+    paths:
+      - 'src/**'
+      - '!src/osx/**'
+      - '!src/freebsd/**'
+      - '!src/netbsd/**'
+      - '!src/openbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/continuous-build-gpu.yml'
+  pull_request:
+    branches:
+      - main
+    paths:
+      - 'src/**'
+      - '!src/osx/**'
+      - '!src/freebsd/**'
+      - '!src/netbsd/**'
+      - '!src/openbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/continuous-build-gpu.yml'
+
+jobs:
+  gpu_build_linux:
+    runs-on: ubuntu-24.04
+    container: alpine:edge
+    concurrency:
+      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
+      cancel-in-progress: true
+    steps:
+      - uses: actions/checkout@v6
+
+      - name: Install build tools
+        run: apk add --no-cache --update gcc g++ make linux-headers
+
+      - name: Compile
+        run: make CXX=g++ GPU_SUPPORT=true
+

+ 87 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/continuous-build-linux.yml

@@ -0,0 +1,87 @@
+name: Continuous Build Linux
+
+on:
+  workflow_dispatch:
+  push:
+    branches: main
+    tags-ignore: '*.*'
+    paths:
+      - 'src/**'
+      - '!src/osx/**'
+      - '!src/freebsd/**'
+      - '!src/netbsd/**'
+      - '!src/openbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/continuous-build-linux.yml'
+  pull_request:
+    branches: main
+    paths:
+      - 'src/**'
+      - '!src/osx/**'
+      - '!src/freebsd/**'
+      - '!src/netbsd/**'
+      - '!src/openbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/continuous-build-linux.yml'
+
+jobs:
+  build:
+    runs-on: ubuntu-24.04
+    concurrency:
+      group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}-${{ matrix.toolchain }}
+      cancel-in-progress: true
+    continue-on-error: true
+    strategy:
+      matrix:
+        toolchain:
+          - aarch64-unknown-linux-musl
+          - arm-unknown-linux-musleabi
+          - arm-unknown-linux-musleabihf
+          - armv7-unknown-linux-musleabi
+          - armv7-unknown-linux-musleabihf
+          - i586-unknown-linux-musl
+          - i686-unknown-linux-musl
+          - m68k-unknown-linux-musl
+          - mips-unknown-linux-musl
+          - mips-unknown-linux-muslsf
+          - mips64-unknown-linux-musl
+          - mips64el-unknown-linux-musl
+          - mipsel-unknown-linux-musl
+          - mipsel-unknown-linux-muslsf
+          - powerpc-unknown-linux-musl
+          - powerpc64-unknown-linux-musl
+          - powerpc64le-unknown-linux-musl
+          - powerpcle-unknown-linux-musl
+          - riscv32-unknown-linux-musl
+          - riscv64-unknown-linux-musl
+          - s390x-ibm-linux-musl
+          - x86_64-unknown-linux-musl
+
+    steps:
+      - uses: actions/checkout@v6
+
+      - name: Install cross toolchain
+        run: |
+          wget -q -P /tmp https://github.com/cross-tools/musl-cross/releases/download/20250929/${{ matrix.toolchain }}.tar.xz
+          wget -q -P /tmp https://github.com/cross-tools/musl-cross/releases/download/20250929/${{ matrix.toolchain }}.tar.xz.sha256
+          echo "$(cat /tmp/${{ matrix.toolchain }}.tar.xz.sha256) /tmp/${{ matrix.toolchain }}.tar.xz" | sha256sum --check --status
+          mkdir -p /opt/x-tools/
+          tar -xf /tmp/${{ matrix.toolchain }}.tar.xz -C /opt/x-tools
+
+      - name: Compile
+        run: CXX=/opt/x-tools/${{ matrix.toolchain }}/bin/${{ matrix.toolchain }}-g++ make STATIC=true STRIP=true
+
+      - name: Create binary artifacts
+        run: |
+          TOOLCHAIN=${{ matrix.toolchain }}
+          GIT_HASH=$(git rev-parse --short "${{ github.sha }}")
+          FILENAME=btop-${TOOLCHAIN/linux-musl/}-$GIT_HASH
+          mv bin/btop bin/$FILENAME
+
+      - name: Upload artifacts
+        uses: actions/upload-artifact@v5
+        with:
+          name: btop-${{ matrix.toolchain }}
+          path: '${{ github.workspace }}/bin/*'

+ 64 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/continuous-build-macos.yml

@@ -0,0 +1,64 @@
+name: Continuous Build MacOS
+
+on:
+  workflow_dispatch:
+  push:
+    branches:
+      - main
+    tags-ignore:
+      - '*.*'
+    paths:
+      - 'src/**'
+      - '!src/linux/**'
+      - '!src/freebsd/**'
+      - '!src/netbsd/**'
+      - '!src/openbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/continuous-build-macos.yml'
+  pull_request:
+    branches:
+      - main
+    paths:
+      - 'src/**'
+      - '!src/linux/**'
+      - '!src/freebsd/**'
+      - '!src/netbsd/**'
+      - '!src/openbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/continuous-build-macos.yml'
+
+jobs:
+  build-macos:
+    strategy:
+      matrix:
+        os:
+         # - {runner: 'macos-13', version: 'Ventura'}
+          - {runner: 'macos-14', version: 'Sonoma'}
+          - {runner: 'macos-15', version: 'Sequoia'}
+    runs-on: ${{ matrix.os.runner }}
+    steps:
+      - uses: maxim-lobanov/setup-xcode@v1
+        with:
+          xcode-version: latest-stable
+
+      - uses: actions/checkout@v6
+
+      - name: Install build tools
+        run: |
+          export HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1
+          brew update --quiet
+          brew install --force --overwrite gcc@15 lowdown
+
+      - name: Compile
+        run: |
+          make CXX=$(brew --prefix)/bin/g++-15
+          GIT_HASH=$(git rev-parse --short "$GITHUB_SHA")
+          mv bin/btop bin/btop-arm64-${{ matrix.os.runner }}-${{ matrix.os.version }}-$GIT_HASH
+          ls -alh bin
+
+      - uses: actions/upload-artifact@v5
+        with:
+          name: btop-arm64-${{ matrix.os.runner }}-${{ matrix.os.version }}
+          path: 'bin/*'

+ 63 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/continuous-build-netbsd.yml

@@ -0,0 +1,63 @@
+name: Continuous Build NetBSD
+
+on:
+  workflow_dispatch:
+  push:
+    branches:
+      - main
+    tags-ignore:
+      - '*.*'
+    paths:
+      - 'src/**'
+      - '!src/linux/**'
+      - '!src/osx/**'
+      - '!src/freebsd/**'
+      - '!src/openbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/continuous-build-netbsd.yml'
+  pull_request:
+    branches:
+      - main
+    paths:
+      - 'src/**'
+      - '!src/linux/**'
+      - '!src/osx/**'
+      - '!src/freebsd/**'
+      - '!src/openbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/continuous-build-netbsd.yml'
+
+jobs:
+  build-netbsd:
+    runs-on: ubuntu-24.04
+    timeout-minutes: 20
+    steps:
+      - uses: actions/checkout@v6
+
+      - name: Compile
+        uses: vmactions/netbsd-vm@v1
+
+        with:
+          release: '10.1'
+          usesh: true
+          prepare: |
+            PATH="/usr/pkg/sbin:/usr/pkg/bin:$PATH"
+            PKG_PATH="https://ftp.netbsd.org/pub/pkgsrc/packages/NetBSD/amd64/10.1/All/"
+            export PATH PKG_PATH
+            /usr/sbin/pkg_add pkgin
+            pkgin -y install gmake gcc14 coreutils git
+            git config --global --add safe.directory /home/runner/work/btop/btop
+          run: |
+            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
+            GIT_HASH=$(git rev-parse --short "$GITHUB_SHA")
+            mv bin/btop bin/btop-GCC10-"$GIT_HASH"
+            ls -alh bin
+
+      - uses: actions/upload-artifact@v5
+        with:
+          name: btop-x86_64-netbsd-9.3
+          path: 'bin/*'
+          if-no-files-found: error
+

+ 56 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/continuous-build-openbsd.yml

@@ -0,0 +1,56 @@
+name: Continuous Build OpenBSD
+
+on:
+  workflow_dispatch:
+  push:
+    branches:
+      - main
+    tags-ignore:
+      - '*.*'
+    paths:
+      - 'src/**'
+      - '!src/linux/**'
+      - '!src/osx/**'
+      - '!src/freebsd/**'
+      - '!src/netbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/continuous-build-openbsd.yml'
+  pull_request:
+    branches:
+      - main
+    paths:
+      - 'src/**'
+      - '!src/linux/**'
+      - '!src/osx/**'
+      - '!src/freebsd/**'
+      - '!src/netbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/continuous-build-openbsd.yml'
+
+jobs:
+  build-openbsd:
+    runs-on: ubuntu-24.04
+    timeout-minutes: 20
+    steps:
+      - uses: actions/checkout@v6
+
+      - name: Compile
+        uses: vmactions/openbsd-vm@v1
+        with:
+          release: '7.8'
+          usesh: true
+          prepare: |
+            pkg_add gmake coreutils git lowdown
+            git config --global --add safe.directory /home/runner/work/btop/btop
+          run: |
+            gmake STATIC=true STRIP=true
+            GIT_HASH=$(git rev-parse --short "$GITHUB_SHA")
+            mv bin/btop bin/btop-"$GIT_HASH"
+
+      - uses: actions/upload-artifact@v5
+        with:
+          name: btop-x86_64-openbsd-7.8
+          path: 'bin/*'
+          if-no-files-found: error

+ 47 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.github/workflows/test-snap-can-build.yml

@@ -0,0 +1,47 @@
+name: 🧪 Test snap can be built on x86_64
+on:
+  workflow_dispatch:
+  push:
+   branches: [ main ]
+   tags-ignore:
+      - '*.*'
+   paths:
+      - 'src/**'
+      - '!src/osx/**'
+      - '!src/freebsd/**'
+      - '!src/netbsd/**'
+      - '!src/openbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/test-snap-can-build.yml'
+      - 'snap/snapcraft.yaml'
+  pull_request:
+   branches: [ main ]
+   paths:
+      - 'src/**'
+      - '!src/osx/**'
+      - '!src/freebsd/**'
+      - '!src/netbsd/**'
+      - '!src/openbsd/**'
+      - 'include/**'
+      - 'Makefile'
+      - '.github/workflows/test-snap-can-build.yml'
+      - 'snap/snapcraft.yaml'
+
+jobs:
+  build:
+    runs-on: ubuntu-24.04
+    strategy:
+      matrix:
+        node-version: [20.x]
+
+    steps:
+      - uses: actions/checkout@v6
+
+      - uses: snapcore/action-build@v1
+        id: build
+
+      - uses: diddlesnaps/snapcraft-review-action@v1
+        with:
+          snap: ${{ steps.build.outputs.snap }}
+          isClassic: 'false'

+ 90 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/.gitignore

@@ -0,0 +1,90 @@
+# gitginore template for creating Snap packages
+# website: https://snapcraft.io/
+
+parts/
+prime/
+stage/
+*.snap
+
+# Snapcraft global state tracking data(automatically generated)
+# https://forum.snapcraft.io/t/location-to-save-global-state/768
+/snap/.snapcraft/
+
+# Source archive packed by `snapcraft cleanbuild` before pushing to the LXD container
+/*_source.tar.bz2
+
+# Prerequisites
+*.d
+
+# Compiled Object files
+*.slo
+*.lo
+*.o
+*.obj
+
+# Precompiled Headers
+*.gch
+*.pch
+
+# Compiled Dynamic libraries
+*.so
+*.dylib
+*.dll
+
+# Fortran module files
+*.mod
+*.smod
+
+# Compiled Static libraries
+*.lai
+*.la
+*.a
+*.lib
+
+# Executables
+*.exe
+*.out
+*.app
+
+# Compiled man page
+btop.1
+
+build
+bin
+btop
+/obj/
+config.h
+.*/
+
+# Optional libraries
+lib/rocm_smi_lib
+
+# Don't ignore .github directory
+!.github/
+
+# Ignore files created by Qt Creator
+*.config
+*.creator
+*.creator.user
+*.creator.user.*
+*.cflags
+*.cxxflags
+*.files
+*.includes
+
+# CMake
+CMakeLists.txt.user
+CMakeCache.txt
+CMakeFiles
+CMakeScripts
+Testing
+Makefile
+cmake_install.cmake
+install_manifest.txt
+compile_commands.json
+CTestTestfile.cmake
+_deps
+CMakeUserPresets.json
+
+# CLion
+cmake-build-*

+ 624 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/CHANGELOG.md

@@ -0,0 +1,624 @@
+## v1.4.5
+
+References | Description | Author(s)
+--- | --- | ---
+#1254 | Bump bundled fmt to 12.0.0 | @deckstose
+#1242 | Enable vim movement in help menu | @botantony
+#948 | Remove reduntant symbols in tree view | @Denizantip
+#1249 | Use /sys/dev/block/MAJOR:MINOR instead of /sys/block/NAME for disk I/O | @CountBleck
+#1227 | feat: display CPU power draw & fix GPU+load avg overwriting core info | @Tom94 and @YuriiShkrobut
+4f5abbb | Fix locale issues | @aristocratos
+#1165 | Add encode and decode meters on Nvidia GPUs | @sam-kirby
+#1197 | linux: Battery Time-to-full | @RadsammyT
+#1203 | Convert ascii escape codes in mountpoint names before reading statvfs | @deckstose
+#1198 | Fix presets erroring with gpu* usage | @entropylost
+#1191 | Fix --tty/--no-tty flag having no effect | @deckstose
+
+## v1.4.4
+
+References | Description | Author(s)
+--- | --- | ---
+#1185 | Fix auto-detection of CPU temp on Ampere boards | @bexcran
+589c133 | Fixed floating_humanizer() to work correctly when numeric delimiter isn't a dot. | @aristocratos
+#1157 | Add command line option to set an inital filter | @imwints
+#1172 | Make 100ms the minimal refresh rate. Exit gracefully if integer conversion in CLI parser fails. | @imwints
+#1031 | Lock/unlock config to avoid infinite recursion | @Jacajack
+#1156 | Fix incorrect positioning and start symbol of second title introduced in 2538d89 | @xDMPx
+ffcd064 | Fix dangling reference warnings for GCC 13 and later | aristocratos
+
+## v1.4.3
+
+References | Description | Author(s)
+--- | --- | ---
+c3b225f | Revert e266ccd which broke str_to_upper() and str_to_lower() | @aristocratos
+#1137 | Enable additional checks in libc++ with the new hardening mode | @imwints
+#1135 | Remove redundant optimization flag | @imwints
+#1139 | Ignore incomplete filter regex, issue #1133 | @imwints
+
+## v1.4.2
+
+References | Description | Author(s)
+--- | --- | ---
+f1482fe | Fix process arguments appearing outside proc box by replacing ASCII control codes with blankspace, issue #1080 | @aristocratos
+#1130 | Fix problems shown by clang-tidy's performance checks | @imwints
+#1120 | Fix wrong error message and documentation of renamed option --utf-force | @t-webber @imwints
+#1128 | Flatten cmake module path | @imwints
+#1129 | CMake: Remove option to use mold  | @imwints
+#1047 | Update Terminus font link, fix typo, spelling, and grammar | @QinCai-rui
+#929 | Please clang with sanitizers | @bad-co-de
+#1126 | Fix MacOS tree-mode + aggregate memory/thread scaling issue | @xaskii
+#993 | Fix typo: Mhz -> MHz | @NyCodeGHG
+
+## v1.4.1
+
+References | Description | Author(s)
+--- | --- | ---
+#1111 #1112 | Various code fixes | @imwints
+#930 #931 | Various code fixes | @bad-co-de
+#1061 | Fixed typo | @polluks
+#1110 | Move the config parser in it's own module  | @imwints
+#1101 | Adding a menu option to show bitrates in base 10 separate from the setting to show bytes/bits in base 10 | @georgev93
+#1079 | Allow MidnightBSD to build btop using the existing freebsd support. | @laffer1
+#1098 | Use XDG_STATE_HOME to save logs | @imwints
+#1092 | Bump CMake version to 3.25 required for LINUX variable | @imwints
+#1058 | Replace brackets with arrows in net and proc box | @taha-yassine
+#1091 | Bump bundled fmt to 11.1.4 | @imwints
+#725 | cmake:  link to CMAKE_DL_LIBS | @alalazo
+#990 | Fix phoenix-night.theme marked as executable | @sertonix
+#1034 | Add Kanagawa-lotus and Kanagawa-wave themes | @philikarus
+#973 | Bump NetBSD version to 10.1 and FreeBSD version to 14.2. | @fraggerfox
+#1072 | Add dark version of adwaita theme: adwaita-dark | @k0tran
+#1036 | Resetting last selection on page navigation in optionsMenu to avoid unordered_map error | @seth-wood
+#1029 | Share the CPU name trimming code between platforms | @yarrick
+#1033 | Update Ryzen name trimming | @yarrick
+#1030 | Drop macos 12 build, add v14 and v15 | @yarrick
+#1028 | Fix cmake-macos workflow | @yarrick
+#1027 | Bump version of deprecated upload-artifact step | @yarrick
+#1025 | Update obsolete egrep call | @tywkeene
+b52069c | Fix menu crash when GPU_SUPPORT=false, issue #989 | @aristocratos
+#961 | Add 'Everforest Ligth Medium' theme | @mstuttgart
+#960 | Support intel GPUs before Gen-6 (patch from upstream) | @w8jcik
+#958 | intel_name_lookup_shim.c (get_intel_device_name): Fix SEGFAULT | @artyom-poptsov
+2e7208d | Fix rsmi_measure_pcie_speeds not saving, issue #934 | @aristocratos
+f3446ed | Show GPU Watt fractions when below 100W | @aristocratos
+
+| + more from @imwints @aristocratos
+
+Big thanks to @imwints for helping out with project maintenance, PR reviews and merging!
+
+## v1.4.0
+
+References | Description | Author(s)
+--- | --- | ---
+#703 | NetBSD Support | @fraggerfox
+#903 | Intel GPU support | @bjia56
+161e8f4 | Added warnings when toggling boxes and terminal size is to small | @aristocratos
+4210f5f | Fix missing core percentages, issue #792 | @aristocratos
+35857f8 | Various fixes for drawing GPU related information | @aristocratos
+#879 | fix divide 0 error when caculating disk usage percentage (#791) | @flylai
+#884 | fix io_graph_speeds parsing | @feihtthief
+#863 | V1 of Phoenix Night theme | @Firehawke
+3f384c0 | Fixed missing CPU core temps when too small to show core temp graphs, issues #792 #867 | @aristocratos
+97d2fb5 | Fixed missing IO graphs in IO mode, issue #867 | @aristocratos
+#840 | fix zero temp (#467) | @joske
+#850 | Fix comments (parsing) in theme files | @acidghost
+#806 | Add regex filtering | @imwints
+#836 | Fix typo in file existences check for voltage_now | @vsey
+#835 | Show time in days when remaining battery exceeds an estimation of 24h | @imwints
+#819 | (AMD Gpu) fix pwr_usage not being defined correctly during rsmi collection | @kalkafox
+#831 | macOS: fix crash if there exists a uid not associated with any user | @thecoder-001
+#796 | Fix rsmi device name buffer size | @davc0n
+#807 | Add gruvbox_light theme | @kk9uk
+#724 | Create man page for btop in Markdown | @ottok
+#734 | Include metadata in binary version output `btop --version` | @imwints
+#771 | collect: Fix reading of battery power draw on Linux | @Derppening
+
+## v1.3.2
+
+Description | Author(s) | References
+--- | --- | ---
+fix: Can't detect librocm 6.0.x | @imwints, @aristocratos | #761
+
+## v1.3.1
+
+Description | Author(s) | References
+--- | --- | ---
+GPU: Added support for dynamic loading of ROCm v6 libraries | @aristocratos, @fxzjshm | 5511131, #737
+Increase max network interface name to 15 | @tessus | #714
+Fix OpenBSD UTF-8 locale detection | @lcheylus, @imwints | #753, #717
+Add hot-reloading of config file with CTRL+R or SIGUSR2 signal | @MartinPit | #722
+Add battery power draw for linux and freebsd | @vsey | #689
+Fix crash caused by string exception when cpu clock is exactly between 999.5 and 999.9 Mhz | @rkmcode | #735
+Write newline at end of config file | @planet36 | #743
+Add theme based on Everforest Dark Medium palette | @M-Sviridov | #746
+fix: don't mangle memory for zombie processes | @joske | #747
+Share common code from collect | @imwints | #756
+Fixed incorrect used and available memory for OSX | | 4461a43
+
+## v1.3.0
+
+* Added Gpu Support Linux | @romner-set | PR #529
+
+* Added platform support for OpenBSD | @joske | PR #607
+
+* Enable macos clang | @muneebmahmed | PR #666
+
+* Fix Apple Silicon CPUs misprinted | @masiboss | PR #679
+
+* Cmake support for MacOS | @imwints | PR #675
+
+* Elementarish theme: color update according to Elementary palette | @stradicat | PR #660
+
+* Add alternative key codes for Delete, Insert, Home, End | @ivanp7 | PR #659
+
+* Fix scrollbar not clearing sometimes. | @DecklynKern | PR #643
+
+* Add keybind for toggling memory display mode in PROC box | @rahulaggarwal965 | PR #623
+
+* Minor string initialization improvement | @imwints | PR #636
+
+* Made disks statvfs logic asynchronous. | @crestfallnatwork | PR #633
+
+* Fix signal list on non-linux/weird linux platforms | @lvxnull | PR #630
+
+* Add option to accumulate a child's resources in parent in tree-view | @imwints | PR #618
+
+* Add CMake support for Linux | @imwints | PR #589
+
+* Horizon theme | @SidVeld | PR #610
+
+* Fix short conversion of 1000-1023 *iB | @scorpion-26 | #609
+
+* Fix integer overflows in btop_collect.cpp | @dorrellmw | #546
+
+* Support compiling with LLVM | @imwints | #510
+
+* Fix getting zfs pool name with '.' char in freebsd | @jfouquart | #602
+
+* [macos/freebsd] support gcc13 | @joske | #600
+
+* FreeBSD swap info | @rrveex | #560
+
+* Create adwaita.theme | @flipflop133 | #485
+
+* Try get terminal size of "/dev/tty" if stdout fails | @imwints | PR #627
+
+* Refresh rate program argument | @imwints | PR #640
+
+* Improved error handling when determining the config directory | @imwints | #652
+
+* Use native POSIX polling syscalls to read input | @lvxnull | #624
+
+* Conditional compile on Big Sur and up | @joske | PR #690
+
++ Various fixes by @imwints, @simplepad, @joske, @gwena, @cpalv, @iambeingtracked, @mattico, @NexAdn
+
+## v1.2.13
+
+* Makefile: VERBOSE=true flag for Makefile to display all compiler commands and fixed so already set CXXFLAGS and LDFLAGS are displayed.
+
+* Makefile: Added autodetection for gcc12 to make compiling on macos Ventura easier.
+
+* 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
+
+* Fixed: Ignore disks that fails in statvfs64() to avoid slowdowns and possible crashes.
+
+* Fixed: Moved up get_cpuHz() in the execution order to get better cpu clock reading.
+
+* Added: proc tree view: if there's more than 40 width left, try to print full cmd, by @Superty
+
+* Fixed: Show the first IP of the interface in NET box instead of the last, by @correabuscar
+
+* Changed: Replace getnameinfo with inet_ntop [on Linux], by @correabuscar
+
+* Fixed: Not picking up last username from /etc/passwd
+
+* Fixed: Process nice value underflowing, issue #461
+
+* Changed: Replace getnameinfo with inet_ntop [on FreeBSD], by @correabuscar
+
+* Changed: Replace getnameinfo with inet_ntop [on macos], by @correabuscar
+
+## v1.2.12
+
+* Added: Dynamic updating of max number of CPU cores.
+
+## v1.2.11
+
+* Fixed: Number of cores wrongly detected for Ryzen in rare cases.
+
+## v1.2.10
+
+* Fixed: Process tree filtering not case insensitive
+
+* Added: Paper theme, by @s6muel
+
+* Fixed: Extra checks to avoid crash on trying to replace empty strings in tree mode
+
+* Fixed: Crashing when cores are offline
+
+* Fixed: Cpu::collect() core count counter...
+
+* Changed: Using sysconf(_SC_NPROCESSORS_CONF) for number of cores instead of sysconf(_SC_NPROCESSORS_ONLN)
+
+* Maintenance: Code cleanup, by @stefanos82
+
+## v1.2.9
+
+* Fixed: Memory values not clearing properly when not in graph mode in mem box
+
+* Changed: kyli0x theme color update, by @kyli0x
+
+* Added: Elementarish theme, by @dennismayr
+
+* Added: key "?" to see help, by @mohi001
+
+* Added: solarized_light theme, by @Fingerzam
+
+* Changed: Made ZFS stats collection compatible with zfs_pools_only option, by @simplepad
+
+* Changed: Rewrite of process sorting and tree generation including fixes for tree sorting and mouse support
+
+* Added: Option to hide the small cpu graphs for processes
+
+* Changed: Small graphs now show colors for each character
+
+* Fixed: Getting selfpath on macos (fix for finding theme folder)
+
+## v1.2.8
+
+* Added: Support for ZFS pool io stats monitoring, by @simplepad
+
+* Added: Filtering of kernel processes, by @0xJoeMama
+
+* Added: New theme everforest-dark-hard, by @iambeingtracked
+
+* Added: New theme tomorrow-night, by @appuchias
+
+* Changed: Disable battery monitoring if it fails instead of exiting
+
+## v1.2.7
+
+* Fixed: Disk IO stats for individual partitions instead of whole disk (Linux)
+
+* Added: Case insensitive process filtering, by @abrasumente233
+
+* Added: Include ZFS ARC in cached/available memory on Linux, by @mattico
+
+* Added: Desktop entry and icons, by @yonatan8070
+
+* Fixed: Net sync scale bug
+
+* Added: tokyo-night & tokyo-storm themes, by @Schievel1
+
+## v1.2.6
+
+* Fixed: Wrong memory unit when shorten and size is less than 10, by @mohi001
+
+* Fixed: Use cpu cores average temp if missing cpu package temp for FreeBSD
+
+* Changed: Enter symbol to a more common variant
+
+## v1.2.5
+
+* Fixed: Fallback to less accurate UTF8 char count if conversion to wstring fails
+
+* Fixed: Small ui fixes for mem and disks
+
+* Added: New theme HotPurpleTrafficLight, by @pallebone
+
+* Fixed: title_left symbol between auto and zero in the net box is not displayed, by @mrdotx
+
+* Fixed: Mouse mappings for net box
+
+## v1.2.4
+
+* Optimization: Proc::draw()
+
+* Fixed: Ignore duplicate disks with same mountpoint
+
+* Changed: Restrict command line for processes to 1000 characters to fix utf8 conversion errors
+
+* Added: add "g" and "G" to vim keys, by @mohi001
+
+## v1.2.3
+
+* Changed: floating_humanizer() now show fractions when shortened and value is < 10
+
+* Fixed: Process tree not redrawing properly
+
+* Fixed: string to wstring conversion crash when string is too big
+
+## v1.2.2
+
+* Changed: Reverted uncolor() back to using regex to fix delay in opening menu when compiled with musl
+
+* Added: Toggle for showing free disk space for privileged or normal users
+
+* Added: Clarification on signal screen that number can be manually entered
+
+## v1.2.1
+
+* Added: Arrow only after use of "f" when filtering processes, by @NavigationHazard
+
+* Fixed: Fx::uncolor not removing all escapes
+
+* Fixed: Text alignment for popup boxes
+
+* Fixed: Terminal resize warning getting stuck
+
+* Removed: Unnecessary counter for atomic_lock
+
+* Added: Percentage progress to Makefile
+
+* Fixed: Alignment of columns in proc box when wide UTF8 characters are used
+
+* Fixed: Battery meter draw fix
+
+## v1.2.0
+
+* Added: Support for FreeBSD, by @joske and @aristocratos
+
+* Fixed (again): Account for system rolling over net speeds in Net::collect()
+
+* Added: Theme gruvbox_material_dark, by @marcoradocchia
+
+* Added: Option for base 10 bytes/bits
+
+## v1.1.5
+
+* Fixed: Account for system rolling over net speeds in Net::collect()
+
+## v1.1.4
+
+* Fixed: Create dependency files in build directory when compiling, by @stwnt
+
+* Fixed: fix CPU temp fallback on macOS, by @joske
+
+* Changed: From rng::sort() to rng::stable_sort() for more stability
+
+* Fixed: in_avail() can always be zero, by @pg83
+
+## v1.1.3
+
+* Added: New theme ayu, by @AlphaNecron
+
+* Added: New theme gruvbox_dark_v2, by @pietryszak
+
+* Fixed: Macos cpu coretemp for Intel, by @joske
+
+* Added: New theme OneDark, by @vtmx
+
+* Fixed: Fixed network graph scale int rollover
+
+* Fixed: Suspected possibility of very rare stall in Input::clear()
+
+## v1.1.2
+
+* Fixed: SISEGV on macos Mojave, by @mgradowski
+
+* Fixed: Small optimizations and fixes to Mem::collect() and Input::get()
+
+* Fixed: Wrong unit for net_upload and net_download in config menu
+
+* Fixed: UTF-8 detection on macos
+
+* Fixed: coretemp iteration due to missing tempX_input, by @KFilipek
+
+* Fixed: coretemp ordering
+
+## v1.1.1
+
+* Added: Partial static build (libgcc, libstdc++) for macos
+
+* Changed: Continuous build macos switched to OSX 11.6 (Big Sur) and partial static build
+
+* Changed: Release binaries for macos switched to OSX 12 (Monterey) and partial static build
+
+## v1.1.0
+
+* Added: Support for OSX, by @joske and @aristocratos
+
+## v1.0.24
+
+* Changed: Collection ordering
+
+* Fixed: Restore all escape seq mouse modes on exit
+
+* Fixed: SIGINT not cleaning up on exit
+
+## v1.0.23
+
+* Fixed: Config parser missing first value when not including version header
+
+* Fixed: Vim keys menu lists selection
+
+* Fixed: Stall when clearing input queue on exit and queue is >1
+
+* Fixed: Inconsistent behaviour of "q" key in the menus
+
+## v1.0.22
+
+* Fixed: Bad values for disks and network on 32-bit
+
+## v1.0.21
+
+* Fixed: Removed extra spaces in cpu name
+
+* Added: / as alternative bind for filter
+
+* Fixed: Security issue when running with SUID bit set
+
+## v1.0.20
+
+* Added: Improved cpu sensor detection for Ryzen Mobile, by @adnanpri
+
+* Changed: Updated makefile
+
+* Changed: Regex for Fx::uncolor() changed to string search and replace
+
+* Changed: Removed all use of regex with dedicated string functions
+
+## v1.0.19
+
+* Fixed: Makefile now tests compiler flag compatibility
+
+## v1.0.18
+
+* Fixed: Makefile g++ -dumpmachine failure to get platform on some distros
+
+## v1.0.17
+
+* Changed: Reverted mutexes back to custom atomic bool based locks
+
+* Added: Static binaries switched to building with musl + more platforms, by @jan-guenter
+
+* Fixed: Improved battery detection, by @jan-guenter
+
+* Added: Displayed battery selectable in options menu
+
+* Fixed: Battery error if non existent battery named is entered
+
+## v1.0.16
+
+* Fixed: atomic_wait() and atomic_lock{} use cpu pause instructions instead of thread sleep
+
+* Fixed: Swapped from atomic bool spinlocks to mutexes to fix rare deadlock
+
+* Added: Continuous Build workflow for OSX branch, by @ShrirajHegde
+
+* Changed: Reverted thread mutex lock to atomic bool with wait and timeout
+
+* Changed: Removed unnecessary async threads in Runner thread
+
+* Added: Try to restart secondary thread in case of stall and additional error checks for ifstream in Proc::collect()
+
+* Fixed: change [k]ill to [K]ill when enabling vim keys, by @jlopezcur
+
+## v1.0.15
+
+* Fixed: Extra "root" partition when running in snap
+
+* Changed: Limit atomic_wait() to 1000ms to fix rare stall
+
+* Fixed: Removed unneeded lock in Runner::run()
+
+* Added: Toggle in options for enabling directional vim keys "h,j,k,l"
+
+## v1.0.14
+
+* Changed: Total system memory is checked at every update instead of once at start
+
+* Added: Continuous Build workflow, by @ShrirajHegde
+
+* Fixed: Uid -> User fallback to getpwuid() if failure for non static builds
+
+* Fixed: snap root disk and changed to compiler flags instead of env variables for detection
+
+* Added: Development branch for OSX, by @joske
+
+## v1.0.13
+
+* Changed: Graph empty symbol is now regular whitespace
+
+## v1.0.12
+
+* Fixed: Exception handling for faulty net download/upload speed
+
+* Fixed: Cpu percent formatting if over 10'000
+
+## v1.0.11
+
+* Changed: atomic_wait to use while loop instead of wait() because of rare stall when a signal handler is triggered while waiting
+
+* Fixed: Get real / mountpoint when running inside snap
+
+* Fixed: UTF8 set LANG and LC_ALL to empty before UTF8 search and fixed empty error msg on exit before signal handler init
+
+* Changed: Init will continue with a warning if UTF-8 locale are detected and it fails to set the locale
+
+## v1.0.10
+
+* Added: Wait for terminal size properties to be available at start
+
+* Changed: Stop second thread before updating terminal size variables
+
+* Changed: Moved check for valid terminal dimensions to before platform init
+
+* Added: Check for empty percentage deques
+
+* Changed: Cpu temp values check for existing values
+
+* Fixed: Cpu percent cutting off above 1000 percent and added scaling with "k" prefix above 10'000
+
+* Fixed: Crash when rapidly resizing terminal at start
+
+## v1.0.9
+
+* Added: ifstream check and try-catch for stod() in Tools::system_uptime()
+
+* Fixed: Freeze on cin.ignore()
+
+## v1.0.8
+
+* Fixed: Additional NULL checks in UTF-8 detection
+
+* Changed: Makefile: Only look for g++-11 if CXX=g++
+
+* Fixed: Missing NULL check for ttyname
+
+* Changed: Only log tty name if known
+
+## v1.0.7
+
+* Fixed: Crash when opening menu at too small size
+
+* Fixed: Cores not constrained to cpu box and core numbers above 100 cut off
+
+* Fixed: Scrollbar position incorrect in small lists and selection not working when filtering
+
+## v1.0.6
+
+* Fixed: Check that getenv("LANG") is not NULL in UTF-8 check
+
+* Fixed: Processes not completely hidden when collapsed in tree mode
+
+* Fixed: Changed wrong filename error.log to btop.log
+
+## v1.0.5
+
+* Fixed: Load AVG sizing when hiding temperatures
+
+* Fixed: Sizing constraints bug on start and boxes can be toggled from size error screen
+
+* Fixed: UTF-8 check crashing if LANG was set to non existent locale
+
+## v1.0.4
+
+* Fixed: Use /proc/pid/statm if RSS memory from /proc/pid/stat is faulty
+
+## v1.0.3
+
+* Fixed: stoi 0 literal pointer to nullptr and added more clamping for gradient array access
+
+## v1.0.2
+
+* Fixed: ARCH detection in Makefile
+
+* Fixed: Color gradient array out of bounds, added clamp 0-100 for cpu percent values
+
+* Fixed: Menu size and preset size issues and added warnings for small terminal size
+
+* Fixed: Options menu page selection alignment
+
+## v1.0.1
+
+* Fixed: UTF-8 check to include UTF8
+
+* Fixed: Added thread started check before joining in clean_quit()
+
+* Fix documentation of --utf-force in README and --help. by @purinchu
+
+## v1.0.0
+
+* First release for Linux

+ 275 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/CMakeLists.txt

@@ -0,0 +1,275 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# CMake configuration for btop
+#
+
+cmake_minimum_required(VERSION 3.25)
+
+# Disable in-source builds since they would override the Makefile
+if("${CMAKE_CURRENT_SOURCE_DIR}" STREQUAL "${CMAKE_CURRENT_BINARY_DIR}")
+  message(FATAL_ERROR "In-source builds are not allowed")
+endif()
+
+project("btop"
+  DESCRIPTION "A monitor of resources"
+  HOMEPAGE_URL "https://github.com/aristocratos/btop"
+  LANGUAGES CXX
+)
+
+include(CheckIPOSupported)
+include(CMakeDependentOption)
+
+# Make our Find<Package>.cmake files available
+list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/")
+
+set(CMAKE_CXX_STANDARD 23)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+set(CMAKE_CXX_EXTENSIONS OFF)
+set(CMAKE_COLOR_DIAGNOSTICS ON)
+set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
+
+option(BTOP_STATIC "Link btop statically" OFF)
+option(BTOP_GPU "Enable GPU support" ON)
+cmake_dependent_option(BTOP_RSMI_STATIC "Link statically to ROCm SMI" OFF "BTOP_GPU" OFF)
+
+# Enable LTO in release builds by default
+if(CMAKE_BUILD_TYPE MATCHES "Rel(ease|WithDebInfo)")
+  option(BTOP_LTO "Enable LTO" ON)
+else()
+  option(BTOP_LTO "Enable LTO" OFF)
+endif()
+
+if(BTOP_STATIC AND NOT APPLE)
+  # Set this before calling find_package
+  set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
+endif()
+
+add_executable(btop src/main.cpp)
+add_library(libbtop OBJECT
+  src/btop.cpp
+  src/btop_cli.cpp
+  src/btop_config.cpp
+  src/btop_draw.cpp
+  src/btop_input.cpp
+  src/btop_menu.cpp
+  src/btop_shared.cpp
+  src/btop_theme.cpp
+  src/btop_tools.cpp
+)
+
+target_link_libraries(btop libbtop)
+
+if(BTOP_LTO)
+  check_ipo_supported()
+  set_target_properties(btop PROPERTIES INTERPROCEDURAL_OPTIMIZATION ON)
+  set_target_properties(libbtop PROPERTIES INTERPROCEDURAL_OPTIMIZATION ON)
+endif()
+
+if(APPLE)
+  target_sources(libbtop PRIVATE src/osx/btop_collect.cpp src/osx/sensors.cpp src/osx/smc.cpp)
+elseif(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD" OR CMAKE_SYSTEM_NAME STREQUAL "MidnightBSD")
+  target_sources(libbtop PRIVATE src/freebsd/btop_collect.cpp)
+elseif(CMAKE_SYSTEM_NAME STREQUAL "OpenBSD")
+  target_sources(libbtop PRIVATE src/openbsd/btop_collect.cpp src/openbsd/sysctlbyname.cpp)
+elseif(CMAKE_SYSTEM_NAME STREQUAL "NetBSD")
+  target_sources(libbtop PRIVATE src/netbsd/btop_collect.cpp)
+elseif(LINUX)
+  target_sources(libbtop PRIVATE src/linux/btop_collect.cpp)
+  if(BTOP_GPU)
+    add_subdirectory(src/linux/intel_gpu_top)
+  endif()
+else()
+  message(FATAL_ERROR "${CMAKE_SYSTEM_NAME} is not supported")
+endif()
+
+# Generate build info
+execute_process(
+  COMMAND "git" "rev-parse" "--short" "HEAD"
+  WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
+  OUTPUT_VARIABLE GIT_COMMIT
+  OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
+set(CONFIGURE_COMMAND
+    "cmake -DBTOP_STATIC=${BTOP_STATIC} -DBTOP_GPU=${BTOP_GPU}"
+)
+get_filename_component(CXX_COMPILER_BASENAME "${CMAKE_CXX_COMPILER}" NAME)
+set(COMPILER "${CXX_COMPILER_BASENAME}")
+set(COMPILER_VERSION "${CMAKE_CXX_COMPILER_VERSION}")
+configure_file(${CMAKE_CURRENT_SOURCE_DIR}/src/config.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.h @ONLY IMMEDIATE)
+set(CMAKE_INCLUDE_CURRENT_DIR ON)
+
+include(CheckCXXSourceCompiles)
+include(CheckCXXSymbolExists)
+
+check_cxx_source_compiles(
+  "
+  #include <version>
+  #if __cpp_lib_optional < 202110L
+  #error \"Missing __cpp_lib_optional < 202110L\"
+  #endif
+  int main() { return 0; }
+  "
+  HAS_CXX_OPTIONAL_MONADS
+)
+if(NOT HAS_CXX_OPTIONAL_MONADS)
+  message(FATAL_ERROR "The compiler doesn't support std::optional::and_then")
+endif()
+check_cxx_symbol_exists("__cpp_lib_expected" "version" HAS_CXX_EXPECTED)
+if(NOT HAS_CXX_EXPECTED)
+  message(FATAL_ERROR "The compiler doesn't support std::expected")
+endif()
+check_cxx_symbol_exists("__cpp_lib_ranges" "version" HAS_CXX_RANGES)
+if(NOT HAS_CXX_RANGES)
+  message(FATAL_ERROR "The compiler doesn't support std::ranges")
+endif()
+check_cxx_symbol_exists("__cpp_lib_ranges_to_container" "version" HAS_CXX_RANGES_TO_CONTAINER)
+if(NOT HAS_CXX_RANGES_TO_CONTAINER)
+  message(FATAL_ERROR "The compiler doesn't support std::ranges::to")
+endif()
+check_cxx_symbol_exists("__cpp_lib_string_contains" "version" HAS_CXX_STRING_CONTAINS)
+if(NOT HAS_CXX_STRING_CONTAINS)
+  message(FATAL_ERROR "The compiler doesn't support std::string::contains")
+endif()
+
+target_compile_options(libbtop PUBLIC -Wall -Wextra -Wpedantic)
+
+include(CheckCXXCompilerFlag)
+
+if(NOT APPLE)
+  target_compile_options(libbtop PUBLIC -fstack-clash-protection)
+endif()
+check_cxx_compiler_flag(-fstack-protector HAS_FSTACK_PROTECTOR)
+if(HAS_FSTACK_PROTECTOR)
+  target_compile_options(libbtop PUBLIC -fstack-protector)
+endif()
+check_cxx_compiler_flag(-fcf-protection HAS_FCF_PROTECTION)
+if(HAS_FCF_PROTECTION)
+  target_compile_options(libbtop PUBLIC -fcf-protection)
+endif()
+
+target_compile_definitions(libbtop PUBLIC
+  FMT_HEADER_ONLY
+  _FILE_OFFSET_BITS=64
+  $<$<CONFIG:Debug>:_GLIBCXX_ASSERTIONS _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG>
+)
+
+target_include_directories(libbtop SYSTEM PUBLIC include)
+
+# Enable pthreads
+set(THREADS_PREFER_PTHREAD_FLAG ON)
+find_package(Threads REQUIRED)
+target_link_libraries(libbtop Threads::Threads)
+
+# SQLite3 for AltData
+find_package(SQLite3 REQUIRED)
+target_link_libraries(libbtop SQLite::SQLite3)
+
+# Enable GPU support
+if(LINUX AND BTOP_GPU)
+  target_compile_definitions(libbtop PUBLIC GPU_SUPPORT)
+
+  if(BTOP_RSMI_STATIC)
+    # ROCm doesn't properly add it's folders to the module path if `CMAKE_MODULE_PATH` is already
+    # set
+    # We could also manually append ROCm's path here
+    set(_CMAKE_MODULE_PATH CMAKE_MODULE_PATH)
+    unset(CMAKE_MODULE_PATH)
+
+    # NOTE: This might be problematic in the future if other sub projects depend on this or if
+    # btop starts producing libraries
+    # Build a static ROCm library
+    set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
+
+    add_subdirectory(lib/rocm_smi_lib EXCLUDE_FROM_ALL)
+
+    add_library(ROCm INTERFACE)
+    # Export ROCm's properties to a target
+    target_compile_definitions(ROCm INTERFACE RSMI_STATIC)
+    target_include_directories(ROCm INTERFACE lib/rocm_smi_lib/include)
+    target_link_libraries(ROCm INTERFACE rocm_smi64)
+
+    set(CMAKE_MODULE_PATH _CMAKE_MODULE_PATH)
+
+    target_link_libraries(libbtop ROCm)
+  endif()
+  if(NOT BTOP_STATIC)
+    target_link_libraries(libbtop ${CMAKE_DL_LIBS})
+  endif()
+endif()
+
+if(BTOP_STATIC)
+  target_compile_definitions(libbtop PUBLIC STATIC_BUILD)
+  target_link_options(libbtop PUBLIC -static LINKER:--fatal-warnings)
+endif()
+
+# Other platform dependent flags
+if(APPLE)
+  target_link_libraries(libbtop
+    $<LINK_LIBRARY:FRAMEWORK,CoreFoundation> $<LINK_LIBRARY:FRAMEWORK,IOKit>
+  )
+elseif(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD" OR CMAKE_SYSTEM_NAME STREQUAL "MidnightBSD")
+  # Avoid version mismatch for libstdc++ when a specific version of GCC is installed and not the
+  # default one since all use the default ones RPATH
+  if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
+    string(REGEX MATCH "^[0-9]+" GCC_VERSION_MAJOR "${CMAKE_CXX_COMPILER_VERSION}")
+    set_target_properties(btop PROPERTIES
+      INSTALL_RPATH "/usr/local/lib/gcc${GCC_VERSION_MAJOR}"
+      BUILD_WITH_INSTALL_RPATH TRUE
+    )
+
+    # The gcc compiler wrapper doesn't add '--eh-frame-hdr' on FreeBSD with static builds
+    # https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=278551
+    if(BTOP_STATIC)
+      target_link_options(libbtop PUBLIC LINKER:--eh-frame-hdr)
+    endif()
+  endif()
+
+  find_package(devstat REQUIRED)
+  find_package(kvm REQUIRED)
+  target_link_libraries(libbtop devstat::devstat kvm::kvm)
+  if(BTOP_STATIC)
+    find_package(elf REQUIRED)
+    target_link_libraries(libbtop elf::elf)
+  endif()
+elseif(CMAKE_SYSTEM_NAME STREQUAL "OpenBSD")
+  if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
+    target_compile_options(libbtop PUBLIC -static-libstdc++)
+  endif()
+  find_package(kvm REQUIRED)
+  target_link_libraries(libbtop kvm::kvm)
+elseif(CMAKE_SYSTEM_NAME STREQUAL "NetBSD")
+  if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
+    target_compile_options(libbtop PUBLIC -static-libstdc++)
+  endif()
+  find_package(kvm REQUIRED)
+  find_package(proplib REQUIRED)
+  target_link_libraries(libbtop kvm::kvm proplib::proplib)
+endif()
+
+# Check if lowdown is installed
+find_program(LOWDOWN_EXECUTABLE lowdown)
+
+if(LOWDOWN_EXECUTABLE)
+  # Custom target to compile Markdown to man page using lowdown
+  add_custom_command(
+    OUTPUT btop.1
+    COMMAND lowdown -s -T man -o btop.1 ${CMAKE_CURRENT_SOURCE_DIR}/manpage.md
+    DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/manpage.md
+    VERBATIM
+  )
+  add_custom_target(generate_manpage ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/btop.1)
+  # Install the man page
+  install(FILES "${CMAKE_CURRENT_BINARY_DIR}/btop.1" DESTINATION "share/man/man1")
+else()
+  message(STATUS "Command 'lowdown' not found: skipping generating man page btop.1")
+endif()
+
+install(TARGETS btop RUNTIME)
+install(FILES "btop.desktop" DESTINATION "share/applications")
+install(FILES "Img/icon.png" DESTINATION "share/icons/hicolor/48x48/apps" RENAME "btop.png")
+install(FILES "Img/icon.svg" DESTINATION "share/icons/hicolor/scalable/apps" RENAME "btop.svg")
+install(DIRECTORY "themes" DESTINATION "share/btop")
+
+include(CTest)
+if(BUILD_TESTING)
+  add_subdirectory(tests)
+endif()

+ 93 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/CODE_OF_CONDUCT.md

@@ -0,0 +1,93 @@
+
+# Contributor Covenant 3.0
+
+## Our Pledge
+
+We pledge to make our community welcoming, safe, and equitable for all.
+
+We 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.
+
+
+## Encouraged Behaviors
+
+While 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.
+
+With these considerations in mind, we agree to behave mindfully toward each other and act in ways that center our shared values, including:
+
+1. Respecting the **purpose of our community**, our activities, and our ways of gathering.
+2. Engaging **kindly and honestly** with others.
+3. Respecting **different viewpoints** and experiences.
+4. **Taking responsibility** for our actions and contributions.
+5. Gracefully giving and accepting **constructive feedback**.
+6. Committing to **repairing harm** when it occurs.
+7. Behaving in other ways that promote and sustain the **well-being of our community**.
+
+
+## Restricted Behaviors
+
+We agree to restrict the following behaviors in our community. Instances, threats, and promotion of these behaviors are violations of this Code of Conduct.
+
+1. **Harassment.** Violating explicitly expressed boundaries or engaging in unnecessary personal attention after any clear request to stop.
+2. **Character attacks.** Making insulting, demeaning, or pejorative comments directed at a community member or group of people.
+3. **Stereotyping or discrimination.** Characterizing anyone’s personality or behavior on the basis of immutable identities or traits.
+4. **Sexualization.** Behaving in a way that would generally be considered inappropriately intimate in the context or purpose of the community.
+5. **Violating confidentiality**. Sharing or acting on someone's personal or private information without their permission.
+6. **Endangerment.** Causing, encouraging, or threatening violence or other harm toward any person or group.
+7. Behaving in other ways that **threaten the well-being** of our community.
+
+### Other Restrictions
+
+1. **Misleading identity.** Impersonating someone else for any reason, or pretending to be someone else to evade enforcement actions.
+2. **Failing to credit sources.** Not properly crediting the sources of content you contribute.
+3. **Promotional materials**. Sharing marketing or other commercial content in a way that is outside the norms of the community.
+4. **Irresponsible communication.** Failing to responsibly present content which includes, links or describes any other restricted behaviors.
+
+
+## Reporting an Issue
+
+Tensions 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.
+
+When an incident does occur, it is important to report it promptly. To report a possible violation, **[NOTE: describe your means of reporting here.]**
+
+Community 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.
+
+
+## Addressing and Repairing Harm
+
+**[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.]**
+
+If 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.
+
+1) Warning
+   1) Event: A violation involving a single incident or series of incidents.
+   2) Consequence: A private, written warning from the Community Moderators.
+   3) Repair: Examples of repair include a private written apology, acknowledgement of responsibility, and seeking clarification on expectations.
+2) Temporarily Limited Activities
+   1) Event: A repeated incidence of a violation that previously resulted in a warning, or the first incidence of a more serious violation.
+   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.
+   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.
+3) Temporary Suspension
+   1) Event: A pattern of repeated violation which the Community Moderators have tried to address with warnings, or a single serious violation.
+   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.
+   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.
+4) Permanent Ban
+   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.
+   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.
+   3) Repair: There is no possible repair in cases of this severity.
+
+This 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.
+
+
+## Scope
+
+This 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.
+
+
+## Attribution
+
+This 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/).
+
+Contributor 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/)
+
+For 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).
+

+ 57 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/CONTRIBUTING.md

@@ -0,0 +1,57 @@
+# Contributing guidelines
+
+## When submitting pull requests
+
+* Explain your thinking in why a change or addition is needed.
+  * Is it a requested change or feature?
+  * If not, open a feature request to get feedback before making a pull request.
+
+* Split up multiple unrelated changes in multiple pull requests.
+
+* If it's a fix for a unreported bug, make a bug report and link the pull request.
+
+* Purely cosmetic changes won't be accepted without a very good explanation of its value.
+
+* Submissions where the majority of the code is AI generated must be marked with [AI generated].
+
+* "Vibe coded" PR's where it seems like the author doesn't understand the generated code will be dismissed.
+
+## Formatting
+
+### Follow the current syntax design
+
+* Indent type: Tabs
+
+* Tab size: 4
+
+* Alternative operators `and`, `or` and `not`.
+
+* Opening curly braces `{` at the end of the same line as the statement/condition.
+
+## General guidelines
+
+* Don't force a programming style. Use object oriented, functional, data oriented, etc., where it's suitable.
+
+* Use [RAII](https://en.cppreference.com/w/cpp/language/raii).
+
+* 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.
+
+* Use the included `fmt` library for string formatting, see issue [#535](https://github.com/aristocratos/btop/issues/535) for more info and examples.
+
+* Do not add includes if the same functionality can be achieved using the already included libraries.
+
+* Use descriptive names for variables.
+
+* Use comments if not very obvious what your code is doing.
+
+* Add comments as labels for what's currently happening in bigger sections of code for better readability.
+
+* Avoid writing to disk.
+
+* If using the logger functions, be sensible, only call it if something of importance has changed.
+
+* Benchmark your code and look for alternatives if they cause a noticeable negative impact.
+
+For questions open a new discussion thread or send a mail to jakob@qvantnet.com
+
+For proposing changes to this document create a [new issue](https://github.com/aristocratos/btop/issues/new/choose).

+ 111 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/Img/icon.svg

@@ -0,0 +1,111 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+   width="90"
+   height="90"
+   version="1.1"
+   id="svg70"
+   xmlns:xlink="http://www.w3.org/1999/xlink"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:svg="http://www.w3.org/2000/svg">
+  <defs
+     id="defs26">
+    <pattern
+       xlink:href="#gray-stripes"
+       id="pattern1888" />
+    <pattern
+       xlink:href="#red-stripes"
+       id="pattern1870" />
+    <pattern
+       id="red-stripes"
+       width="341"
+       height="90"
+       patternUnits="userSpaceOnUse">
+      <rect
+         width="341"
+         height="16"
+         fill="#f00"
+         id="rect2" />
+      <rect
+         y="16"
+         width="341"
+         height="16"
+         fill="#d70000"
+         id="rect4" />
+      <rect
+         y="32"
+         width="341"
+         height="16"
+         fill="#af0000"
+         id="rect6" />
+      <rect
+         y="48"
+         width="341"
+         height="16"
+         fill="#870000"
+         id="rect8" />
+      <rect
+         y="64"
+         width="341"
+         height="16"
+         fill="#5f0000"
+         id="rect10" />
+    </pattern>
+    <pattern
+       id="gray-stripes"
+       width="341"
+       height="90"
+       patternUnits="userSpaceOnUse">
+      <rect
+         width="341"
+         height="16"
+         fill="#585858"
+         id="rect13" />
+      <rect
+         y="16"
+         width="341"
+         height="16"
+         fill="#4e4e4e"
+         id="rect15" />
+      <rect
+         y="32"
+         width="341"
+         height="16"
+         fill="#444"
+         id="rect17" />
+      <rect
+         y="48"
+         width="341"
+         height="16"
+         fill="#3a3a3a"
+         id="rect19" />
+      <rect
+         y="64"
+         width="341"
+         height="16"
+         fill="#303030"
+         id="rect21" />
+      <rect
+         y="80"
+         width="341"
+         height="10"
+         fill="#262626"
+         id="rect23" />
+    </pattern>
+  </defs>
+  <g
+     id="g2074"
+     transform="translate(18)">
+    <path
+       d="M 2,7 V 90 H 47 V 74 h 7 V 55 H 47 V 42 h 7 V 23 H 47 V 7 Z M 19,26 H 37 V 39 H 19 Z m 0,32 H 37 V 71 H 19 Z"
+       id="path28"
+       style="fill:#080808" />
+    <path
+       d="M 2,7 V 90 H 47 V 74 h 7 V 55 H 47 V 42 h 7 V 23 H 47 V 7 Z m 1,1 h 43 v 16 h 7 v 17 h -7 v 15 h 7 V 73 H 46 V 89 H 3 Z M 18,25 H 38 V 40 H 18 Z m 1,1 V 39 H 37 V 26 Z M 18,57 H 38 V 72 H 18 Z m 1,1 V 71 H 37 V 58 Z M 4,9 V 88 H 45 V 72 h 7 V 57 H 45 V 40 h 7 V 25 H 45 V 9 Z m 1,1 h 39 v 16 h 7 v 13 h -7 v 19 h 7 V 71 H 44 V 87 H 5 Z M 16,23 H 40 V 42 H 16 Z m 1,1 V 41 H 39 V 24 Z M 16,55 H 40 V 74 H 16 Z m 1,1 V 73 H 39 V 56 Z"
+       id="path42"
+       style="fill:url(#pattern1888)" />
+    <path
+       d="M 0,0 V 80 H 42 V 64 h 7 V 48 H 42 V 32 h 7 V 16 H 42 V 0 Z M 14,16 H 35 V 32 H 14 Z m 0,32 H 35 V 64 H 14 Z"
+       id="path56"
+       style="fill:url(#pattern1870)" />
+  </g>
+</svg>

+ 44 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/Img/logo.svg

@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="341" height="90" version="1.1" xmlns="http://www.w3.org/2000/svg">
+	<defs>
+		<pattern id="red-stripes" width="341" height="90" patternUnits="userSpaceOnUse">
+			<rect width="341" height="16" fill="#f00"/>
+			<rect y="16" width="341" height="16" fill="#d70000"/>
+			<rect y="32" width="341" height="16" fill="#af0000"/>
+			<rect y="48" width="341" height="16" fill="#870000"/>
+			<rect y="64" width="341" height="16" fill="#5f0000"/>
+		</pattern>
+		<pattern id="gray-stripes" width="341" height="90" patternUnits="userSpaceOnUse">
+			<rect width="341" height="16" fill="#585858"/>
+			<rect y="16" width="341" height="16" fill="#4e4e4e"/>
+			<rect y="32" width="341" height="16" fill="#444"/>
+			<rect y="48" width="341" height="16" fill="#3a3a3a"/>
+			<rect y="64" width="341" height="16" fill="#303030"/>
+			<rect y="80" width="341" height="10" fill="#262626"/>
+		</pattern>
+	</defs>
+	<g fill="#080808">
+		<path d="m2,7v83h45v-16h7v-19h-7v-13h7v-19h-7v-16h-45zm17,19h18v13h-18v-13zm0,32h18v13h-18v-13z"/>
+		<path d="m58,7v19h21v64h17v-64h21v-19h-59z"/>
+		<path d="m128,7v16h-7v51h7v16h45v-16h7v-51h-7v-16h-45zm10,19h25v45h-25v-45z"/>
+		<path d="m184,7v83h17v-32h28v-16h7v-19h-7v-16h-45zm17,19h18v13h-18v-13z"/>
+		<path d="m261,23v16h-14v19h14v16h17v-16h14v-19h-14v-16h-17z"/>
+		<path d="m310,23v16h-14v19h14v16h17v-16h14v-19h-14v-16h-17z"/>
+	</g>
+	<g fill="url(#gray-stripes)">
+		<path d="m2,7v83h45v-16h7v-19h-7v-13h7v-19h-7v-16h-45zm1,1h43v16h7v17h-7v15h7v17h-7v16h-43v-81zm15,17h20v15h-20v-15zm1,1v13h18v-13h-18zm-1,31h20v15h-20v-15zm1,1v13h18v-13h-18zm-15-49v79h41v-16h7v-15h-7v-17h7v-15h-7v-16h-41zm1,1h39v16h7v13h-7v19h7v13h-7v16h-39v-77zm11,13h24v19h-24v-19zm1,1v17h22v-17h-22zm-1,31h24v19h-24v-19zm1,1v17h22v-17h-22z"/>
+		<path d="m58,7v19h21v64h17v-64h21v-19h-59zm1,1h57v17h-21v64h-15v-64h-21v-17zm1,1v15h21v64h13v-64h21v-15h-55zm1,1h53v13h-21v64h-11v-64h-21v-13z"/>
+		<path d="m128,7v16h-7v51h7v16h45v-16h7v-51h-7v-16h-45zm1,1h43v16h7v49h-7v16h-43v-16h-7v-49h7v-16zm9,18v45h25v-45h-25zm-1-1h27v47h-27v-47zm-7-16v16h-7v47h7v16h41v-16h7v-47h-7v-16h-41zm1,1h39v16h7v45h-7v16h-39v-16h-7v-45h7v-16zm5,14v49h29v-49h-29zm-1-1h31v51h-31v-51z"/>
+		<path d="m184,7v83h17v-32h28v-16h7v-19h-7v-16h-45zm1,1h43v16h7v17h-7v16h-28v32h-15v-81zm16,18v13h18v-13h-18zm-1-1h20v15h-20v-15zm-14-16v79h13v-32h28v-16h7v-15h-7v-16h-41zm1,1h39v16h7v13h-7v16h-28v32h-11v-77zm12,14v17h22v-17h-22zm-1-1h24v19h-24v-19z"/>
+		<path d="m261,23v16h-14v19h14v16h17v-16h14v-19h-14v-16h-17zm1,1h15v16h14v17h-14v16h-15v-16h-14v-17h14v-16zm1,1v16h-14v15h14v16h13v-16h14v-15h-14v-16h-13zm1,1h11v16h14v13h-14v16h-11v-16h-14v-13h14v-16z"/>
+		<path d="m310,23v16h-14v19h14v16h17v-16h14v-19h-14v-16h-17zm1,1h15v16h14v17h-14v16h-15v-16h-14v-17h14v-16zm1,1v16h-14v15h14v16h13v-16h14v-15h-14v-16h-13zm1,1h11v16h14v13h-14v16h-11v-16h-14v-13h14v-16z"/>
+	</g>
+	<g fill="url(#red-stripes)">
+		<path d="m0,0v80h42v-16h7v-16h-7v-16h7v-16h-7v-16h-42zm14,16h21v16h-21v-16zm0,32h21v16h-21v-16z"/>
+		<path d="m56,0v16h21v64h14v-64h21v-16h-56z"/>
+		<path d="m126,0v16h-7v48h7v16h42v-16h7v-48h-7v-16h-42zm7,16h28v48h-28v-48z"/>
+		<path d="m182,0v80h14v-32h28v-16h7v-16h-7v-16h-42zm14,16h21v16h-21v-16z"/>
+		<path d="m259,16v16h-14v16h14v16h14v-16h14v-16h-14v-16h-14z"/>
+		<path d="m308,16v16h-14v16h14v16h14v-16h14v-16h-14v-16h-14z"/>
+	</g>
+</svg>

+ 202 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/LICENSE

@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.

+ 1534 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/README.md

@@ -0,0 +1,1534 @@
+# ![btop++](Img/logo.png)
+
+<a href="https://repology.org/project/btop/versions">
+    <img src="https://repology.org/badge/vertical-allrepos/btop.svg" alt="Packaging status" align="right">
+</a>
+
+![Linux](https://img.shields.io/badge/-Linux-grey?logo=linux)
+![macOS](https://img.shields.io/badge/-OSX-black?logo=apple)
+![FreeBSD](https://img.shields.io/badge/-FreeBSD-red?logo=freebsd)
+![NetBSD](https://img.shields.io/badge/-NetBSD-black?logo=netbsd)
+![OpenBSD](https://img.shields.io/badge/-OpenBSD-black?logo=openbsd)
+![Usage](https://img.shields.io/badge/Usage-System%20resource%20monitor-yellow)
+![c++23](https://img.shields.io/badge/cpp-c%2B%2B23-green)
+![latest_release](https://img.shields.io/github/v/tag/aristocratos/btop?label=release)
+[![Donate](https://img.shields.io/badge/-Donate-yellow?logo=paypal)](https://paypal.me/aristocratos)
+[![Sponsor](https://img.shields.io/badge/-Sponsor-red?logo=github)](https://github.com/sponsors/aristocratos)
+[![Coffee](https://img.shields.io/badge/-Buy%20me%20a%20Coffee-grey?logo=Ko-fi)](https://ko-fi.com/aristocratos)
+[![btop](https://snapcraft.io/btop/badge.svg)](https://snapcraft.io/btop)
+[![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)
+[![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)
+[![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)
+[![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)
+[![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)
+
+## Index
+
+* [News](#news)
+* [Documents](#documents)
+* [Description](#description)
+* [Features](#features)
+* [Themes](#themes)
+* [Support and funding](#support-and-funding)
+* [Prerequisites](#prerequisites) (Read this if you are having issues!)
+* [Screenshots](#screenshots)
+* [Keybindings](#help-menu)
+* [Installation Linux/macOS](#installation)
+* [Compilation Linux](#compilation-linux)
+* [Compilation macOS](#compilation-macos-osx)
+* [Compilation FreeBSD](#compilation-freebsd)
+* [Compilation NetBSD](#compilation-netbsd)
+* [Compilation OpenBSD](#compilation-openbsd)
+* [Testing](#testing)
+* [GPU compatibility](#gpu-compatibility)
+* [Installing the snap](#installing-the-snap)
+* [Configurability](#configurability)
+* [License](#license)
+
+## News
+
+##### 4 December 2025
+
+Since there is a increasing amount of AI generated/assisted PR's, the following guidlines have been added to CONTRIBUTING.md:
+
+* Submissions where the majority of the code is AI generated must be marked with [AI generated].
+
+* "Vibe coded" PR's where it seems like the author doesn't understand the generated code will be dismissed.
+
+##### 22 September 2024
+
+Btop release v1.4.0
+
+Intel 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.
+
+NetBSD support added. Thanks to [@fraggerfox](https://github.com/fraggerfox) for contributions.
+
+See [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.
+
+##### 7 January 2024
+
+Btop release v1.3.0
+
+Big 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.
+And 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.
+
+See news entry below for more information regarding GPU support.
+
+##### 25 November 2023
+
+GPU monitoring added for Linux!
+
+Compile from git main to try it out.
+
+Use keys `5`, `6`, `7` and `0` to show/hide the gpu monitoring boxes. `5` = Gpu 1, `6` = Gpu 2, etc.
+
+Gpu stats/graphs can also be displayed in the "Cpu box" (not as verbose), see the cpu options menu for info and configuration.
+
+Note that the binaries provided on the release page (when released) and the continuous builds will not have gpu support enabled.
+
+Because the GPU support relies on loading of dynamic gpu libraries, gpu support will not work when also static linking.
+
+See [Compilation Linux](#compilation-linux) for more info on how to compile with gpu monitoring support.
+
+Many thanks to [@romner-set](https://github.com/romner-set) who wrote the vast majority of the implementation for GPU support.
+
+Big update with version bump to 1.3 coming soon.
+
+##### 28 August 2022
+
+[![btop4win](https://github.com/aristocratos/btop4win/raw/master/Img/logo.png)](https://github.com/aristocratos/btop4win)
+
+First release of btop4win available at https://github.com/aristocratos/btop4win
+
+<details>
+<summary>More...</summary>
+
+##### 16 January 2022
+
+Release v1.2.0 with FreeBSD support. No release binaries for FreeBSD provided as of yet.
+
+Again a big thanks to [@joske](https://github.com/joske) for his porting efforts!
+
+Since compatibility with Linux, macOS and FreeBSD are done, the focus going forward will be on new features like GPU monitoring.
+
+##### 13 November 2021
+
+Release 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.
+macOS binaries + installer are included for both x86 and ARM64 (Apple Silicon) in the releases.
+
+Big thank you to [@joske](https://github.com/joske) who wrote the vast majority of the implementation!
+
+##### 30 October 2021
+
+Work 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.
+The 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.
+
+If you want to help out, test for bugs/fix bugs or just try out the branches:
+
+**macOS / OSX**
+```bash
+# Install and use Homebrew or MacPorts package managers for easy dependency installation
+brew install coreutils make gcc@11 lowdown
+git clone https://github.com/aristocratos/btop.git
+cd btop
+git checkout OSX
+gmake
+```
+
+**FreeBSD**
+```bash
+sudo pkg install gmake gcc11 coreutils git lowdown
+git clone https://github.com/aristocratos/btop.git
+cd btop
+git checkout freebsd
+gmake
+```
+
+Note that GNU make (`gmake`) is recommended but not required for macOS/OSX but it is required on FreeBSD.
+
+
+##### 6 October 2021
+
+macOS development have been started by [@joske](https://github.com/joske), big thanks :)
+See branch [OSX](https://github.com/aristocratos/btop/tree/OSX) for current progress.
+
+##### 18 September 2021
+
+The Linux version of btop++ is complete. Released as version 1.0.0
+
+I will be providing statically compiled binaries for a range of architectures in every release for those having problems compiling.
+
+For compilation GCC 11 is required.
+
+Please 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.
+
+The development plan right now:
+
+* 1.1.0 macOS [OSX] support
+* 1.2.0 FreeBSD support
+* 1.3.0 Support for GPU monitoring
+* 1.X.0 Other platforms and features...
+
+Windows support is not in the plans as of now, but if anyone else wants to take it on, I will try to help.
+
+##### 5 May 2021
+
+This 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.
+And will need some help in the form of code contributions to get complete support for BSD and macOS/OSX.
+
+</details>
+
+## Documents
+
+**[CHANGELOG.md](CHANGELOG.md)**
+
+**[CONTRIBUTING.md](CONTRIBUTING.md)**
+
+**[CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)**
+
+## Description
+
+Resource monitor that shows usage and stats for processor, memory, disks, network and processes.
+
+C++ version and continuation of [bashtop](https://github.com/aristocratos/bashtop) and [bpytop](https://github.com/aristocratos/bpytop).
+
+## Features
+
+* Easy to use, with a game inspired menu system.
+* Full mouse support: all buttons with a highlighted key are clickable and mouse scrolling works in process list and menu boxes.
+* Fast and responsive UI with UP, DOWN key process selection.
+* Function for showing detailed stats for selected process.
+* Ability to filter processes.
+* Easy switching between sorting options.
+* Tree view of processes.
+* Send any signal to selected process.
+* Pause the process list.
+* UI menu for changing all config file options.
+* Auto scaling graph for network usage.
+* Shows IO activity and speeds for disks.
+* Battery meter
+* Selectable symbols for the graphs.
+* Custom presets
+* And more...
+
+## Themes
+
+Btop++ uses the same theme files as bpytop and bashtop (some color values missing in bashtop themes).
+
+See [themes](https://github.com/aristocratos/btop/tree/main/themes) folder for available themes.
+
+Btop searches the following directories for system themes:
+
+* `../share/btop/themes` (this path is relative to the btop executable)
+* `/usr/local/share/btop/themes`
+* `/usr/share/btop/themes`
+
+The first directory that exists and isn't empty is used as the system themes directory.
+
+The user themes directory depends on which environment variables are set:
+
+* If `$XDG_CONFIG_HOME` is set, the user themes directory is `$XDG_CONFIG_HOME/btop/themes`
+* Otherwise, if `$HOME` is set, the user themes directory is `$HOME/.config/btop/themes`
+* Otherwise, the user themes directory is `~/.config/btop/themes`
+
+The `make install` command places the default themes in `[$PREFIX or /usr/local]/share/btop/themes`.
+User created themes should be placed in the user themes directory.
+
+Use the `--themes-dir` command-line option to specify a custom themes directory.
+When specified, this directory takes priority over the default search paths.
+
+Let me know if you want to contribute with new themes.
+
+## Support and funding
+
+You can sponsor this project through GitHub. See [my sponsors page](https://github.com/sponsors/aristocratos) for options.
+
+Or donate through [PayPal](https://paypal.me/aristocratos) or [ko-fi](https://ko-fi.com/aristocratos).
+
+Any support is greatly appreciated!
+
+## Prerequisites
+
+For the best experience run within a terminal with support for:
+
+* 24-bit truecolor ([See list of terminals with truecolor support](https://github.com/termstandard/colors))
+* 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.
+* 16 color TTY mode will be activated if a real tty device is detected. Can be forced with "-t/--tty" arguments.
+* Wide characters (Are sometimes problematic in web-based terminals)
+
+Also necessary is a UTF8 locale and a font that includes:
+
+* Unicode Block “Braille Patterns” U+2800 - U+28FF (Not needed in TTY mode or with graphs set to type: block or tty.)
+* Unicode Block “Geometric Shapes” U+25A0 - U+25FF
+* Unicode Block "Box Drawing" and "Block Elements" U+2500 - U+259F
+
+### **Optional Dependencies (Needed for GPU monitoring) (Only Linux)**
+
+GPU monitoring also requires a btop binary built with GPU support (`GPU_SUPPORT=true` flag).
+
+See [GPU compatibility](#gpu-compatibility) section for more about compiling with GPU support.
+
+ * **NVIDIA**
+
+   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.
+
+   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.
+
+ * **AMD**
+
+   If you have an AMD GPU `rocm_smi_lib` is required, which may or may not be packaged for your distribution.
+
+ * **INTEL**
+
+   Requires a working C compiler if compiling from source.
+
+   Also requires the user to have permission to read from SYSFS.
+
+   Can be set with `make setcap` (preferred) or `make setuid` or by running btop with `sudo` or equivalent.
+
+### **Notice (Text rendering issues)**
+
+* 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.
+
+* 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.
+
+* 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.
+
+* If text is misaligned and you use Konsole or Yakuake, turning off "Bi-Directional text rendering" is a possible fix.
+
+* 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.
+
+* Look to the creators of the terminal emulator you use to fix these issues if the previously mentioned fixes don't work for you.
+
+## Screenshots
+
+#### Main UI showing details for a selected process
+
+![Screenshot 1](Img/normal.png)
+
+#### Main UI in TTY mode
+
+![Screenshot 2](Img/tty.png)
+
+#### Main UI with custom options
+
+![Screenshot 3](Img/alt.png)
+
+#### Main-menu
+
+![Screenshot 3](Img/main-menu.png)
+
+#### Options-menu
+
+![Screenshot 4](Img/options-menu.png)
+
+#### Help-menu
+
+![Screenshot 5](Img/help-menu.png)
+
+## Installation
+
+**Binaries for Linux are statically compiled with musl and work on kernel releases 2.6.39 and newer**
+
+1. **Download btop-(VERSION)-(ARCH)-(PLATFORM).tbz from [latest release](https://github.com/aristocratos/btop/releases/latest) and unpack to a new folder**
+
+   **Notice! Use x86_64 for 64-bit x86 systems, i486 and i686 are 32-bit!**
+
+2. **Install (from created folder)**
+
+   * **Run:**
+
+   ```bash
+   # use "make install PREFIX=/target/dir" to set target, default: /usr/local
+   # only use "sudo" when installing to a NON user owned directory
+   sudo make install
+   ```
+
+3. **(Optional/Required for Intel GPU and CPU wattage) Set extended capabilities or suid bit to btop**
+
+   Enables signal sending to any process without starting with `sudo` and can prevent /proc read permissions problems on some systems.
+
+   Is required for Intel GPU support and CPU wattage monitoring.
+
+   * **Run:**
+
+   ```bash
+   # run after make install and use same PREFIX if any was used at install
+   sudo make setcap
+   ```
+   * **or**
+
+   ```bash
+   # run after make install and use same PREFIX if any was used at install
+   # set SU_USER and SU_GROUP to select user and group, default is root:root
+   sudo make setuid
+   ```
+
+* **Uninstall**
+
+  * **Run:**
+
+   ```bash
+   sudo make uninstall
+   ```
+
+* **Show help**
+
+   ```bash
+   make help
+   ```
+
+**Binary release (from native os repo)**
+
+* **openSUSE**
+  * **Tumbleweed:**
+    ```bash
+    sudo zypper in btop
+    ```
+  * For all other versions, see [openSUSE Software: btop](https://software.opensuse.org/package/btop)
+* **Fedora**
+    ```bash
+    sudo dnf install btop
+	```
+* **RHEL/Rocky/AlmaLinux 8+**
+    ```bash
+    sudo dnf install epel-release
+	sudo dnf install btop
+	```
+* **FreeBSD**
+	```sh
+	pkg install btop
+	```
+* **NetBSD**
+	```sh
+	pkg_add btop
+	```
+
+
+**Binary release on Homebrew (macOS (x86_64 & ARM64) / Linux (x86_64))**
+
+* **[Homebrew](https://formulae.brew.sh/formula/btop)**
+  ```bash
+  brew install btop
+  ```
+
+## Compilation Linux
+
+   Requires at least GCC 14 or Clang 19.
+
+   The Makefile also needs GNU `coreutils` and `sed` (should already be installed on any modern distribution).
+
+   ### GPU compatibility
+
+   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.
+
+   Gpu support for Nvidia or AMD will not work when static linking glibc (or musl, etc.)!
+
+   For x86_64 Linux the flag `GPU_SUPPORT` is automatically set to `true`, to manually disable gpu support set the flag to false, like:
+
+   `make GPU_SUPPORT=false` (or `cmake -DBTOP_GPU=false` with CMake)
+
+ * **NVIDIA**
+
+    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.
+
+    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.
+
+ * **AMD**
+
+    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.
+
+    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:
+
+   ```bash
+   git clone https://github.com/rocm/rocm_smi_lib.git --depth 1 -b rocm-5.6.x lib/rocm_smi_lib
+   ```
+
+<details>
+<summary>
+
+### With Make
+</summary>
+
+1. **Install dependencies (example for Ubuntu 24.04 Noble)**
+
+   ```bash
+   sudo apt install coreutils sed git build-essential lowdown
+   ```
+
+2. **Clone repository**
+
+   ```bash
+   git clone https://github.com/aristocratos/btop.git
+   cd btop
+   ```
+
+3. **Compile**
+
+   ```bash
+   make
+   ```
+
+   Options for make:
+
+   | Flag                            | Description                                                             |
+   |---------------------------------|-------------------------------------------------------------------------|
+   | `VERBOSE=true`                  | To display full compiler/linker commands                                |
+   | `STATIC=true`                   | For static compilation                                                  |
+   | `QUIET=true`                    | For less verbose output                                                 |
+   | `STRIP=true`                    | To force stripping of debug symbols (adds `-s` linker flag)             |
+   | `DEBUG=true`                    | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging        |
+   | `ARCH=<architecture>`           | To manually set the target architecture                                 |
+   | `GPU_SUPPORT=<true\|false>`     | Enable/disable GPU support (Enabled by default on X86_64 Linux)         |
+   | `RSMI_STATIC=true`              | To statically link the ROCm SMI library used for querying AMDGPU        |
+   | `ADDFLAGS=<flags>`              | For appending flags to both compiler and linker                         |
+   | `CXX=<compiler>`                | Manually set which compiler to use                                       |
+
+   Example: `make ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system.
+
+   Notice! If using LDAP Authentication, usernames will show as UID number for LDAP users if compiling statically with glibc.
+
+4. **Install**
+
+   ```bash
+   sudo make install
+   ```
+
+   Append `PREFIX=/target/dir` to set target, default: `/usr/local`
+
+   Notice! Only use "sudo" when installing to a NON user owned directory.
+
+5. **(Optional/Required for Intel GPU support and CPU wattage) Set extended capabilities or suid bit to btop**
+
+   No need for `sudo` to enable signal sending to any process and to prevent /proc read permissions problems on some systems.
+
+   Also required for Intel GPU monitoring and CPU wattage monitoring.
+
+   Run after make install and use same PREFIX if any was used at install.
+
+   ```bash
+   sudo make setcap
+   ```
+
+   or
+
+   Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `root`
+
+   ```bash
+   sudo make setuid
+   ```
+
+* **Uninstall**
+
+   ```bash
+   sudo make uninstall
+   ```
+
+* **Remove any object files from source dir**
+
+   ```bash
+   make clean
+   ```
+
+* **Remove all object files, binaries and created directories in source dir**
+
+   ```bash
+   make distclean
+   ```
+
+* **Show help**
+
+   ```bash
+   make help
+   ```
+
+</details>
+<details>
+<summary>
+
+### With CMake (Community maintained)
+</summary>
+
+1. **Install build dependencies**
+
+   Requires Clang / GCC, CMake, Ninja, Lowdown and Git
+
+   For example, with Debian Bookworm:
+
+   ```bash
+   sudo apt install cmake git g++ ninja-build lowdown
+   ```
+
+2. **Clone the repository**
+
+   ```bash
+   git clone https://github.com/aristocratos/btop.git && cd btop
+   ``````
+
+3. **Compile**
+
+   ```bash
+   # Configure
+   cmake -B build -G Ninja
+   # Build
+   cmake --build build
+   ```
+
+   This will automatically build a release version of btop.
+
+   Some useful options to pass to the configure step:
+
+   | Configure flag                  | Description                                                             |
+   |---------------------------------|-------------------------------------------------------------------------|
+   | `-DBTOP_STATIC=<ON\|OFF>`       | Enables static linking (OFF by default)                                 |
+   | `-DBTOP_LTO=<ON\|OFF>`          | Enables link time optimization (ON by default)                          |
+
+
+   | `-DBTOP_GPU=<ON\|OFF>`          | Enable GPU support (ON by default)                                      |
+   | `-DBTOP_RSMI_STATIC=<ON\|OFF>`  | Build and link the ROCm SMI library statically (OFF by default)         |
+   | `-DCMAKE_INSTALL_PREFIX=<path>` | The installation prefix ('/usr/local' by default)                       |
+
+   To force any other compiler, run `CXX=<compiler> cmake -B build -G Ninja`
+
+4. **Install**
+
+   ```bash
+   cmake --install build
+   ```
+
+   May require root privileges
+
+5. **Uninstall**
+
+   CMake doesn't generate an uninstall target by default. To remove installed files, run
+   ```
+   cat build/install_manifest.txt | xargs rm -irv
+   ```
+
+6. **Cleanup build directory**
+
+   ```bash
+   cmake --build build -t clean
+   ```
+
+</details>
+
+## Compilation macOS OSX
+
+   Requires at least GCC 14 or Clang 19.
+
+   The Makefile also needs GNU coreutils and `sed`.
+
+   Install and use Homebrew or MacPorts package managers for easy dependency installation
+
+<details>
+<summary>
+
+### With Make
+</summary>
+
+1. **Install dependencies (example for Homebrew)**
+
+   ```bash
+   brew install coreutils make gcc@15 lowdown
+   ```
+
+2. **Clone repository**
+
+   ```bash
+   git clone https://github.com/aristocratos/btop.git
+   cd btop
+   ```
+3. **Compile**
+
+   ```bash
+   gmake
+   ```
+
+   Options for make:
+
+   | Flag                            | Description                                                             |
+   |---------------------------------|-------------------------------------------------------------------------|
+   | `VERBOSE=true`                  | To display full compiler/linker commands                                |
+   | `STATIC=true`                   | For static compilation (only libgcc and libstdc++)                      |
+   | `QUIET=true`                    | For less verbose output                                                 |
+   | `STRIP=true`                    | To force stripping of debug symbols (adds `-s` linker flag)             |
+   | `DEBUG=true`                    | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging        |
+   | `ARCH=<architecture>`           | To manually set the target architecture                                 |
+   | `ADDFLAGS=<flags>`              | For appending flags to both compiler and linker                         |
+   | `CXX=<compiler>`                | Manually set which compiler to use                                       |
+
+   Example: `gmake ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system.
+
+4. **Install**
+
+   ```bash
+   sudo gmake install
+   ```
+
+   Append `PREFIX=/target/dir` to set target, default: `/usr/local`
+
+   Notice! Only use "sudo" when installing to a NON user owned directory.
+
+5. **(Recommended) Set suid bit to make btop always run as root (or other user)**
+
+   ```bash
+   sudo gmake setuid
+   ```
+
+   No need for `sudo` to see information for non user owned processes and to enable signal sending to any process.
+
+   Run after make install and use same PREFIX if any was used at install.
+
+   Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `wheel`
+
+* **Uninstall**
+
+   ```bash
+   sudo gmake uninstall
+   ```
+
+* **Remove any object files from source dir**
+
+   ```bash
+   gmake clean
+   ```
+
+* **Remove all object files, binaries and created directories in source dir**
+
+   ```bash
+   gmake distclean
+   ```
+
+* **Show help**
+
+   ```bash
+   gmake help
+   ```
+
+</details>
+<details>
+<summary>
+
+### With CMake (Community maintained)
+</summary>
+
+1. **Install build dependencies**
+
+   Requires Clang, CMake, Ninja, Lowdown and Git
+
+   ```bash
+   brew update --quiet
+   brew install cmake git llvm ninja lowdown
+   ```
+
+2. **Clone the repository**
+
+   ```bash
+   git clone https://github.com/aristocratos/btop.git && cd btop
+   ```
+
+3. **Compile**
+
+   ```bash
+   # Configure
+   export LLVM_PREFIX="$(brew --prefix llvm)"
+   export CXX="$LLVM_PREFIX/bin/clang++"
+   export CPPFLAGS="-I$LLVM_PREFIX/include"
+   export LDFLAGS="-L$LLVM_PREFIX/lib -L$LLVM_PREFIX/lib/c++ -Wl,-rpath,$LLVM_PREFIX/lib/c++ -fuse-ld=$LLVM_PREFIX/bin/ld64.lld"
+   cmake -B build -G Ninja
+   # Build
+   cmake --build build
+   ```
+
+   This will automatically build a release version of btop.
+
+   Some useful options to pass to the configure step:
+
+   | Configure flag                  | Description                                                             |
+   |---------------------------------|-------------------------------------------------------------------------|
+   | `-DBTOP_LTO=<ON\|OFF>`          | Enables link time optimization (ON by default)                          |
+
+
+   | `-DCMAKE_INSTALL_PREFIX=<path>` | The installation prefix ('/usr/local' by default)                       |
+
+   To force any specific compiler, run `CXX=<compiler> cmake -B build -G Ninja`
+
+4. **Install**
+
+   ```bash
+   cmake --install build
+   ```
+
+   May require root privileges
+
+5. **Uninstall**
+
+   CMake doesn't generate an uninstall target by default. To remove installed files, run
+   ```
+   cat build/install_manifest.txt | xargs rm -irv
+   ```
+
+6. **Cleanup build directory**
+
+   ```bash
+   cmake --build build -t clean
+   ```
+
+</details>
+
+## Compilation FreeBSD
+
+   Requires at least Clang 19 (default) or GCC 14.
+
+   Note that GNU make (`gmake`) is required to compile on FreeBSD.
+
+<details>
+<summary>
+
+### With gmake
+</summary>
+
+1. **Install dependencies**
+
+   ```bash
+   sudo pkg install gmake coreutils git lowdown
+   ```
+
+2. **Clone repository**
+
+   ```bash
+   git clone https://github.com/aristocratos/btop.git
+   cd btop
+   ```
+
+3. **Compile**
+
+   ```bash
+   gmake
+   ```
+
+   Options for make:
+
+   | Flag                            | Description                                                             |
+   |---------------------------------|-------------------------------------------------------------------------|
+   | `VERBOSE=true`                  | To display full compiler/linker commands                                |
+   | `STATIC=true`                   | For static compilation (only libgcc and libstdc++)                      |
+   | `QUIET=true`                    | For less verbose output                                                 |
+   | `STRIP=true`                    | To force stripping of debug symbols (adds `-s` linker flag)             |
+   | `DEBUG=true`                    | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging        |
+   | `ARCH=<architecture>`           | To manually set the target architecture                                 |
+   | `ADDFLAGS=<flags>`              | For appending flags to both compiler and linker                         |
+   | `CXX=<compiler>`                | Manually set which compiler to use                                       |
+
+   Example: `gmake ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system.
+
+4. **Install**
+
+   ```bash
+   sudo gmake install
+   ```
+
+   Append `PREFIX=/target/dir` to set target, default: `/usr/local`
+
+   Notice! Only use "sudo" when installing to a NON user owned directory.
+
+5. **(Recommended) Set suid bit to make btop always run as root (or other user)**
+
+   ```bash
+   sudo gmake setuid
+   ```
+
+   No need for `sudo` to see information for non user owned processes and to enable signal sending to any process.
+
+   Run after make install and use same PREFIX if any was used at install.
+
+   Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `wheel`
+
+* **Uninstall**
+
+   ```bash
+   sudo gmake uninstall
+   ```
+
+* **Remove any object files from source dir**
+
+   ```bash
+   gmake clean
+   ```
+
+* **Remove all object files, binaries and created directories in source dir**
+
+   ```bash
+   gmake distclean
+   ```
+
+* **Show help**
+
+   ```bash
+   gmake help
+   ```
+
+</details>
+<details>
+<summary>
+
+### With CMake (Community maintained)
+</summary>
+
+1. **Install build dependencies**
+
+   Requires Clang / GCC, CMake, Ninja, Lowdown and Git
+
+   ```bash
+   pkg install cmake ninja lowdown
+   ```
+
+2. **Clone the repository**
+
+   ```bash
+   git clone https://github.com/aristocratos/btop.git && cd btop
+   ```
+
+3. **Compile**
+
+   ```bash
+   # Configure
+   cmake -B build -G Ninja
+   # Build
+   cmake --build build
+   ```
+
+   This will automatically build a release version of btop.
+
+   Some useful options to pass to the configure step:
+
+   | Configure flag                  | Description                                                             |
+   |---------------------------------|-------------------------------------------------------------------------|
+   | `-DBTOP_STATIC=<ON\|OFF>`       | Enables static linking (OFF by default)                                 |
+   | `-DBTOP_LTO=<ON\|OFF>`          | Enables link time optimization (ON by default)                          |
+
+
+   | `-DCMAKE_INSTALL_PREFIX=<path>` | The installation prefix ('/usr/local' by default)                       |
+
+   _**Note:** Static linking does not work with GCC._
+
+   To force any other compiler, run `CXX=<compiler> cmake -B build -G Ninja`
+
+4. **Install**
+
+   ```bash
+   cmake --install build
+   ```
+
+   May require root privileges
+
+5. **Uninstall**
+
+   CMake doesn't generate an uninstall target by default. To remove installed files, run
+   ```
+   cat build/install_manifest.txt | xargs rm -irv
+   ```
+
+6. **Cleanup build directory**
+
+   ```bash
+   cmake --build build -t clean
+   ```
+
+</details>
+
+## Compilation NetBSD
+
+   Requires at least GCC 14.
+
+   Note that GNU make (`gmake`) is required to compile on NetBSD.
+
+<details>
+<summary>
+
+### With gmake
+</summary>
+
+1. **Install dependencies**
+
+   ```bash
+   /usr/sbin/pkg_add pkgin
+   pkgin install -y coregutils gcc14 git gmake
+   ```
+
+2. **Clone repository**
+
+   ```bash
+   git clone https://github.com/aristocratos/btop.git
+   cd btop
+   ```
+
+3. **Compile**
+
+   ```bash
+   CXX=/usr/pkg/gcc14/bin/g++ gmake CXXFLAGS="-DNDEBUG"
+   ```
+
+   Options for make:
+
+   | Flag                            | Description                                                             |
+   |---------------------------------|-------------------------------------------------------------------------|
+   | `VERBOSE=true`                  | To display full compiler/linker commands                                |
+   | `STATIC=true`                   | For static compilation (only libgcc and libstdc++)                      |
+   | `QUIET=true`                    | For less verbose output                                                 |
+   | `STRIP=true`                    | To force stripping of debug symbols (adds `-s` linker flag)             |
+   | `DEBUG=true`                    | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging        |
+   | `ARCH=<architecture>`           | To manually set the target architecture                                 |
+   | `ADDFLAGS=<flags>`              | For appending flags to both compiler and linker                         |
+   | `CXX=<compiler>`                | Manually set which compiler to use                                      |
+
+   Example: `gmake ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system.
+
+4. **Install**
+
+   ```bash
+   sudo gmake install
+   ```
+
+   Append `PREFIX=/target/dir` to set target, default: `/usr/local`
+
+   Notice! Only use "sudo" when installing to a NON user owned directory.
+
+5. **(Recommended) Set suid bit to make btop always run as root (or other user)**
+
+   ```bash
+   sudo gmake setuid
+   ```
+
+   No need for `sudo` to see information for non user owned processes and to enable signal sending to any process.
+
+   Run after make install and use same PREFIX if any was used at install.
+
+   Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `wheel`
+
+* **Uninstall**
+
+   ```bash
+   sudo gmake uninstall
+   ```
+
+* **Remove any object files from source dir**
+
+   ```bash
+   gmake clean
+   ```
+
+* **Remove all object files, binaries and created directories in source dir**
+
+   ```bash
+   gmake distclean
+   ```
+
+* **Show help**
+
+   ```bash
+   gmake help
+   ```
+
+</details>
+<details>
+<summary>
+
+### With CMake (Community maintained)
+</summary>
+
+1. **Install build dependencies**
+
+   Requires GCC, CMake, Ninja and Git
+
+   ```bash
+   /usr/sbin/pkg_add pkgin
+   pkgin install cmake ninja-build gcc14 git
+   ```
+
+2. **Clone the repository**
+
+   ```bash
+   git clone https://github.com/aristocratos/btop.git && cd btop
+   ```
+
+3. **Compile**
+
+   ```bash
+   # Configure
+   CXX="/usr/pkg/gcc14/bin/g++" cmake -B build -G Ninja
+   # Build
+   cmake --build build
+   ```
+
+   This will automatically build a release version of btop.
+
+   Some useful options to pass to the configure step:
+
+   | Configure flag                  | Description                                                             |
+   |---------------------------------|-------------------------------------------------------------------------|
+   | `-DBTOP_LTO=<ON\|OFF>`          | Enables link time optimization (ON by default)                          |
+
+
+   | `-DCMAKE_INSTALL_PREFIX=<path>` | The installation prefix ('/usr/local' by default)                       |
+
+   To force any other compiler, run `CXX=<compiler> cmake -B build -G Ninja`
+
+4. **Install**
+
+   ```bash
+   cmake --install build
+   ```
+
+   May require root privileges
+
+5. **Uninstall**
+
+   CMake doesn't generate an uninstall target by default. To remove installed files, run
+   ```
+   cat build/install_manifest.txt | xargs rm -irv
+   ```
+
+6. **Cleanup build directory**
+
+   ```bash
+   cmake --build build -t clean
+   ```
+
+</details>
+
+## Compilation OpenBSD
+
+   Note that GNU make (`gmake`) is required to compile on OpenBSD.
+
+<details>
+<summary>
+
+### With gmake
+</summary>
+
+1. **Install dependencies**
+
+   ```bash
+   pkg_add coreutils git gmake lowdown
+   ```
+
+2. **Clone repository**
+
+   ```bash
+   git clone https://github.com/aristocratos/btop.git
+   cd btop
+   ```
+
+3. **Compile**
+
+   ```bash
+   gmake
+   ```
+
+   Options for make:
+
+   | Flag                            | Description                                                             |
+   |---------------------------------|-------------------------------------------------------------------------|
+   | `VERBOSE=true`                  | To display full compiler/linker commands                                |
+   | `STATIC=true`                   | For static compilation (only libgcc and libstdc++)                      |
+   | `QUIET=true`                    | For less verbose output                                                 |
+   | `STRIP=true`                    | To force stripping of debug symbols (adds `-s` linker flag)             |
+   | `DEBUG=true`                    | Sets OPTFLAGS to `-O0 -g` and enables more verbose debug logging        |
+   | `ARCH=<architecture>`           | To manually set the target architecture                                 |
+   | `ADDFLAGS=<flags>`              | For appending flags to both compiler and linker                         |
+   | `CXX=<compiler>`                | Manually set which compiler to use                                       |
+
+   Example: `gmake ADDFLAGS=-march=native` might give a performance boost if compiling only for your own system.
+
+4. **Install**
+
+   ```bash
+   sudo gmake install
+   ```
+
+   Append `PREFIX=/target/dir` to set target, default: `/usr/local`
+
+   Notice! Only use "sudo" when installing to a NON user owned directory.
+
+5. **(Recommended) Set suid bit to make btop always run as root (or other user)**
+
+   ```bash
+   sudo gmake setuid
+   ```
+
+   No need for `sudo` to see information for non user owned processes and to enable signal sending to any process.
+
+   Run after make install and use same PREFIX if any was used at install.
+
+   Set `SU_USER` and `SU_GROUP` to select user and group, default is `root` and `wheel`
+
+* **Uninstall**
+
+   ```bash
+   sudo gmake uninstall
+   ```
+
+* **Remove any object files from source dir**
+
+   ```bash
+   gmake clean
+   ```
+
+* **Remove all object files, binaries and created directories in source dir**
+
+   ```bash
+   gmake distclean
+   ```
+
+* **Show help**
+
+   ```bash
+   gmake help
+   ```
+
+</details>
+<details>
+<summary>
+
+### With CMake (Community maintained)
+</summary>
+
+1. **Install build dependencies**
+
+   Requires GCC, CMake, Ninja, Lowdown and Git
+
+   _**Note:** LLVM's libc++ shipped with OpenBSD 7.4 is too old and cannot compile btop._
+
+   ```bash
+   pkg_add cmake git ninja lowdown
+   ```
+
+2. **Clone the repository**
+
+   ```bash
+   git clone https://github.com/aristocratos/btop.git && cd btop
+   ```
+
+3. **Compile**
+
+   ```bash
+   # Configure
+   cmake -B build -G Ninja
+   # Build
+   cmake --build build
+   ```
+
+   This will automatically build a release version of btop.
+
+   Some useful options to pass to the configure step:
+
+   | Configure flag                  | Description                                                             |
+   |---------------------------------|-------------------------------------------------------------------------|
+   | `-DBTOP_LTO=<ON\|OFF>`          | Enables link time optimization (ON by default)                          |
+   | `-DCMAKE_INSTALL_PREFIX=<path>` | The installation prefix ('/usr/local' by default)                       |
+
+   To force any other compiler, run `CXX=<compiler> cmake -B build -G Ninja`
+
+4. **Install**
+
+   ```bash
+   cmake --install build
+   ```
+
+   May require root privileges
+
+5. **Uninstall**
+
+   CMake doesn't generate an uninstall target by default. To remove installed files, run
+   ```
+   cat build/install_manifest.txt | xargs rm -irv
+   ```
+
+6. **Cleanup build directory**
+
+   ```bash
+   cmake --build build -t clean
+   ```
+
+</details>
+
+## Testing
+
+Testing requires [CMake](cmake.org). Tests are build by default and can be run with `ctest --test-dir <build>`.
+
+If you want to disable building tests, pass `-DBUILD_TESTING=OFF` to the configure step.
+
+## Installing the snap
+[![btop](https://snapcraft.io/btop/badge.svg)](https://snapcraft.io/btop)
+
+### 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.
+
+ * **Install the snap**
+
+    ```bash
+    sudo snap install btop
+    or
+    sudo snap install btop-desktop
+    ```
+ * **Install the latest snap from the edge channel**
+   ```
+   sudo snap install btop --edge
+   or
+   sudo snap install btop-desktop --edge
+   ```
+
+ * **Connect the interface**
+
+    ```bash
+	sudo snap connect btop:removable-media
+	or
+	sudo snap connect btop-desktop:removable-media
+	```
+
+
+## Configurability
+
+All options changeable from within UI.
+Config and log files stored in `$XDG_CONFIG_HOME/btop` or `$HOME/.config/btop` folder
+
+#### btop.conf: (auto generated if not found)
+
+```bash
+#? Config file for btop v. 1.2.2
+
+#* Name of a btop++/bpytop/bashtop formatted ".theme" file, "Default" and "TTY" for builtin themes.
+#* Themes should be placed in "../share/btop/themes" relative to binary or "$HOME/.config/btop/themes"
+color_theme = "Default"
+
+#* If the theme set background should be shown, set to False if you want terminal background transparency.
+theme_background = True
+
+#* Sets if 24-bit truecolor should be used, will convert 24-bit colors to 256 color (6x6x6 color cube) if false.
+truecolor = True
+
+#* Set to true to force tty mode regardless if a real tty has been detected or not.
+#* Will force 16-color mode and TTY theme, set all graph symbols to "tty" and swap out other non tty friendly symbols.
+force_tty = False
+
+#* Define presets for the layout of the boxes. Preset 0 is always all boxes shown with default settings. Max 9 presets.
+#* Format: "box_name:P:G,box_name:P:G" P=(0 or 1) for alternate positions, G=graph symbol to use for box.
+#* Use whitespace " " as separator between different presets.
+#* Example: "cpu:0:default,mem:0:tty,proc:1:default cpu:0:braille,proc:0:tty"
+presets = "cpu:1:default,proc:0:default cpu:0:default,mem:0:default,net:0:default cpu:0:block,net:0:tty"
+
+#* Set to True to enable "h,j,k,l,g,G" keys for directional control in lists.
+#* Conflicting keys for h:"help" and k:"kill" is accessible while holding shift.
+vim_keys = False
+
+#* Rounded corners on boxes, is ignored if TTY mode is ON.
+rounded_corners = True
+
+#* Default symbols to use for graph creation, "braille", "block" or "tty".
+#* "braille" offers the highest resolution but might not be included in all fonts.
+#* "block" has half the resolution of braille but uses more common characters.
+#* "tty" uses only 3 different symbols but will work with most fonts and should work in a real TTY.
+#* Note that "tty" only has half the horizontal resolution of the other two, so will show a shorter historical view.
+graph_symbol = "braille"
+
+# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty".
+graph_symbol_cpu = "default"
+
+# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty".
+graph_symbol_mem = "default"
+
+# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty".
+graph_symbol_net = "default"
+
+# Graph symbol to use for graphs in cpu box, "default", "braille", "block" or "tty".
+graph_symbol_proc = "default"
+
+#* Manually set which boxes to show. Available values are "cpu mem net proc" and "gpu0" through "gpu5", separate values with whitespace.
+shown_boxes = "proc cpu mem net"
+
+#* Update time in milliseconds, recommended 2000 ms or above for better sample times for graphs.
+update_ms = 1500
+
+#* Processes sorting, "pid" "program" "arguments" "threads" "user" "memory" "cpu lazy" "cpu direct",
+#* "cpu lazy" sorts top process over time (easier to follow), "cpu direct" updates top process directly.
+proc_sorting = "cpu lazy"
+
+#* Reverse sorting order, True or False.
+proc_reversed = False
+
+#* Show processes as a tree.
+proc_tree = False
+
+#* Use the cpu graph colors in the process list.
+proc_colors = True
+
+#* Use a darkening gradient in the process list.
+proc_gradient = True
+
+#* If process cpu usage should be of the core it's running on or usage of the total available cpu power.
+proc_per_core = True
+
+#* Show process memory as bytes instead of percent.
+proc_mem_bytes = True
+
+#* Choose to preserve last cpu and memory usage of dead processes for when paused.
+keep_dead_proc_usage = False
+
+#* Use /proc/[pid]/smaps for memory information in the process info box (very slow but more accurate)
+proc_info_smaps = False
+
+#* Show proc box on left side of screen instead of right.
+proc_left = False
+
+#* Sets the CPU stat shown in upper half of the CPU graph, "total" is always available.
+#* Select from a list of detected attributes from the options menu.
+cpu_graph_upper = "total"
+
+#* Sets the CPU stat shown in lower half of the CPU graph, "total" is always available.
+#* Select from a list of detected attributes from the options menu.
+cpu_graph_lower = "total"
+
+#* Toggles if the lower CPU graph should be inverted.
+cpu_invert_lower = True
+
+#* Set to True to completely disable the lower CPU graph.
+cpu_single_graph = False
+
+#* Show cpu box at bottom of screen instead of top.
+cpu_bottom = False
+
+#* Shows the system uptime in the CPU box.
+show_uptime = True
+
+#* Shows the CPU package current power consumption in watts. Requires running `make setcap` or `make setuid` or running with sudo.
+show_cpu_watts = True
+
+#* Show cpu temperature.
+check_temp = True
+
+#* Which sensor to use for cpu temperature, use options menu to select from list of available sensors.
+cpu_sensor = "Auto"
+
+#* Show temperatures for cpu cores also if check_temp is True and sensors has been found.
+show_coretemp = True
+
+#* Set a custom mapping between core and coretemp, can be needed on certain cpus to get correct temperature for correct core.
+#* Use lm-sensors or similar to see which cores are reporting temperatures on your machine.
+#* Format "x:y" x=core with wrong temp, y=core with correct temp, use space as separator between multiple entries.
+#* Example: "4:0 5:1 6:3"
+cpu_core_map = ""
+
+#* Which temperature scale to use, available values: "celsius", "fahrenheit", "kelvin" and "rankine".
+temp_scale = "celsius"
+
+#* Use base 10 for bits/bytes sizes, KB = 1000 instead of KiB = 1024.
+base_10_sizes = False
+
+#* Show CPU frequency.
+show_cpu_freq = True
+
+#* How to calculate CPU frequency, available values: "first", "range", "lowest", "highest" and "average".
+freq_mode = "first"
+
+#* Draw a clock at top of screen, formatting according to strftime, empty string to disable.
+#* Special formatting: /host = hostname | /user = username | /uptime = system uptime
+clock_format = "%H:%M"
+
+#* Update main ui in background when menus are showing, set this to false if the menus is flickering too much for comfort.
+background_update = True
+
+#* Custom cpu model name, empty string to disable.
+custom_cpu_name = ""
+
+#* Optional filter for shown disks, should be full path of a mountpoint, separate multiple values with whitespace " ".
+#* Begin line with "exclude=" to change to exclude filter, otherwise defaults to "most include" filter. Example: disks_filter="exclude=/boot /home/user".
+disks_filter = "exclude=/boot"
+
+#* Show graphs instead of meters for memory values.
+mem_graphs = True
+
+#* Show mem box below net box instead of above.
+mem_below_net = False
+
+#* Count ZFS ARC in cached and available memory.
+zfs_arc_cached = True
+
+#* If swap memory should be shown in memory box.
+show_swap = True
+
+#* Show swap as a disk, ignores show_swap value above, inserts itself after first disk.
+swap_disk = True
+
+#* If mem box should be split to also show disks info.
+show_disks = True
+
+#* Filter out non physical disks. Set this to False to include network disks, RAM disks and similar.
+only_physical = True
+
+#* Read disks list from /etc/fstab. This also disables only_physical.
+use_fstab = False
+
+#* Set to true to show available disk space for privileged users.
+disk_free_priv = False
+
+#* Toggles if io activity % (disk busy time) should be shown in regular disk usage view.
+show_io_stat = True
+
+#* Toggles io mode for disks, showing big graphs for disk read/write speeds.
+io_mode = False
+
+#* Set to True to show combined read/write io graphs in io mode.
+io_graph_combined = False
+
+#* Set the top speed for the io graphs in MiB/s (100 by default), use format "mountpoint:speed" separate disks with whitespace " ".
+#* Example: "/mnt/media:100 /:20 /boot:1".
+io_graph_speeds = ""
+
+#* Set fixed values for network graphs in Mebibits. Is only used if net_auto is also set to False.
+net_download = 100
+
+net_upload = 100
+
+#* Use network graphs auto rescaling mode, ignores any values set above and rescales down to 10 Kibibytes at the lowest.
+net_auto = True
+
+#* Sync the auto scaling for download and upload to whichever currently has the highest scale.
+net_sync = False
+
+#* Starts with the Network Interface specified here.
+net_iface = "br0"
+
+#* Show battery stats in top right if battery is present.
+show_battery = True
+
+#* Which battery to use if multiple are present. "Auto" for auto detection.
+selected_battery = "Auto"
+
+#* Set loglevel for "~/.config/btop/btop.log" levels are: "ERROR" "WARNING" "INFO" "DEBUG".
+#* The level set includes all lower levels, i.e. "DEBUG" will show all logging info.
+log_level = "DEBUG"
+```
+
+#### Command line options
+
+```text
+Usage: btop [OPTIONS]
+
+Options:
+  -c, --config <file>     Path to a config file
+  -d, --debug             Start in debug mode with additional logs and metrics
+  -f, --filter <filter>   Set an initial process filter
+      --force-utf         Override automatic UTF locale detection
+  -l, --low-color         Disable true color, 256 colors only
+  -p, --preset <id>       Start with a preset (0-9)
+  -t, --tty               Force tty mode with ANSI graph symbols and 16 colors only
+      --no-tty            Force disable tty mode
+  -u, --update <ms>       Set an initial update rate in milliseconds
+  -h, --help              Show this help message and exit
+  -V, --version           Show a version message and exit (more with --version)
+```
+
+## LICENSE
+
+[Apache License 2.0](LICENSE)

+ 16 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/btop.desktop

@@ -0,0 +1,16 @@
+[Desktop Entry]
+Type=Application
+Version=1.0
+Name=btop++
+GenericName=System Monitor
+GenericName[it]=Monitor di sistema
+GenericName[zh_TW]=系統監視器
+Comment=Resource monitor that shows usage and stats for processor, memory, disks, network and processes
+Comment[it]=Monitoraggio delle risorse: mostra utilizzo e statistiche per CPU, dischi, rete e processi
+Comment[zh_TW]=顯示處理器、主記憶體、磁碟、網路與進程的使用與統計數據的資源監視器應用程式
+Icon=btop
+Exec=btop
+Terminal=true
+Categories=System;Monitor;ConsoleOnly;
+Keywords=system;process;task
+Keywords[zh_TW]=系統;進程;處理程序;任務

+ 23 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/cmake/Finddevstat.cmake

@@ -0,0 +1,23 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Find devstat, the Device Statistics Library
+#
+
+if(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD" OR CMAKE_SYSTEM_NAME STREQUAL "MidnightBSD")
+  find_path(devstat_INCLUDE_DIR NAMES devstat.h)
+  find_library(devstat_LIBRARY NAMES devstat)
+
+  include(FindPackageHandleStandardArgs)
+  find_package_handle_standard_args(devstat REQUIRED_VARS devstat_LIBRARY devstat_INCLUDE_DIR)
+
+  if(devstat_FOUND AND NOT TARGET devstat::devstat)
+    add_library(devstat::devstat UNKNOWN IMPORTED)
+    set_target_properties(devstat::devstat PROPERTIES
+      IMPORTED_LOCATION "${devstat_LIBRARY}"
+      INTERFACE_INCLUDE_DIRECTORIES "${devstat_INCLUDE_DIR}"
+    )
+  endif()
+
+  mark_as_advanced(devstat_INCLUDE_DIR devstat_LIBRARY)
+endif()
+

+ 23 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/cmake/Findelf.cmake

@@ -0,0 +1,23 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Find libelf, the ELF Access Library
+#
+
+if(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD" OR CMAKE_SYSTEM_NAME STREQUAL "MidnightBSD")
+  find_path(elf_INCLUDE_DIR NAMES libelf.h)
+  find_library(elf_LIBRARY NAMES elf)
+
+  include(FindPackageHandleStandardArgs)
+  find_package_handle_standard_args(elf REQUIRED_VARS elf_LIBRARY elf_INCLUDE_DIR)
+
+  if(elf_FOUND AND NOT TARGET elf::elf)
+    add_library(elf::elf UNKNOWN IMPORTED)
+    set_target_properties(elf::elf PROPERTIES
+      IMPORTED_LOCATION "${elf_LIBRARY}"
+      INTERFACE_INCLUDE_DIRECTORIES "${elf_INCLUDE_DIR}"
+    )
+  endif()
+
+  mark_as_advanced(elf_INCLUDE_DIR elf_LIBRARY)
+endif()
+

+ 23 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/cmake/Findkvm.cmake

@@ -0,0 +1,23 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Find libkvm, the Kernel Data Access Library
+#
+
+if(BSD)
+  find_path(kvm_INCLUDE_DIR NAMES kvm.h)
+  find_library(kvm_LIBRARY NAMES kvm)
+
+  include(FindPackageHandleStandardArgs)
+  find_package_handle_standard_args(kvm REQUIRED_VARS kvm_LIBRARY kvm_INCLUDE_DIR)
+
+  if(kvm_FOUND AND NOT TARGET kvm::kvm)
+    add_library(kvm::kvm UNKNOWN IMPORTED)
+    set_target_properties(kvm::kvm PROPERTIES
+      IMPORTED_LOCATION "${kvm_LIBRARY}"
+      INTERFACE_INCLUDE_DIRECTORIES "${kvm_INCLUDE_DIR}"
+    )
+  endif()
+
+  mark_as_advanced(kvm_INCLUDE_DIR kvm_LIBRARY)
+endif()
+

+ 23 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/cmake/Findproplib.cmake

@@ -0,0 +1,23 @@
+# SPDX-License-Identifier: Apache-2.0
+#
+# Find proplib – property container object library
+#
+
+if(BSD)
+  find_path(proplib_INCLUDE_DIR NAMES prop/proplib.h)
+  find_library(proplib_LIBRARY NAMES libprop prop)
+
+  include(FindPackageHandleStandardArgs)
+  find_package_handle_standard_args(proplib REQUIRED_VARS proplib_LIBRARY proplib_INCLUDE_DIR)
+
+  if(proplib_FOUND AND NOT TARGET proplib::proplib)
+    add_library(proplib::proplib UNKNOWN IMPORTED)
+    set_target_properties(proplib::proplib PROPERTIES
+      IMPORTED_LOCATION "${proplib_LIBRARY}"
+      INTERFACE_INCLUDE_DIRECTORIES "${proplib_INCLUDE_DIR}"
+    )
+  endif()
+
+  mark_as_advanced(proplib_INCLUDE_DIR proplib_LIBRARY)
+endif()
+

+ 27 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/LICENSE.rst

@@ -0,0 +1,27 @@
+Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+--- Optional exception to the license ---
+
+As an exception, if, as a result of your compiling your source code, portions
+of this Software are embedded into a machine-executable object form of such
+source code, you may redistribute such embedded portions in such object form
+without including the above copyright and permission notices.

+ 220 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/args.h

@@ -0,0 +1,220 @@
+// Formatting library for C++ - dynamic argument lists
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_ARGS_H_
+#define FMT_ARGS_H_
+
+#ifndef FMT_MODULE
+#  include <functional>  // std::reference_wrapper
+#  include <memory>      // std::unique_ptr
+#  include <vector>
+#endif
+
+#include "format.h"  // std_string_view
+
+FMT_BEGIN_NAMESPACE
+namespace detail {
+
+template <typename T> struct is_reference_wrapper : std::false_type {};
+template <typename T>
+struct is_reference_wrapper<std::reference_wrapper<T>> : std::true_type {};
+
+template <typename T> auto unwrap(const T& v) -> const T& { return v; }
+template <typename T>
+auto unwrap(const std::reference_wrapper<T>& v) -> const T& {
+  return static_cast<const T&>(v);
+}
+
+// node is defined outside dynamic_arg_list to workaround a C2504 bug in MSVC
+// 2022 (v17.10.0).
+//
+// Workaround for clang's -Wweak-vtables. Unlike for regular classes, for
+// templates it doesn't complain about inability to deduce single translation
+// unit for placing vtable. So node is made a fake template.
+template <typename = void> struct node {
+  virtual ~node() = default;
+  std::unique_ptr<node<>> next;
+};
+
+class dynamic_arg_list {
+  template <typename T> struct typed_node : node<> {
+    T value;
+
+    template <typename Arg>
+    FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {}
+
+    template <typename Char>
+    FMT_CONSTEXPR typed_node(const basic_string_view<Char>& arg)
+        : value(arg.data(), arg.size()) {}
+  };
+
+  std::unique_ptr<node<>> head_;
+
+ public:
+  template <typename T, typename Arg> auto push(const Arg& arg) -> const T& {
+    auto new_node = std::unique_ptr<typed_node<T>>(new typed_node<T>(arg));
+    auto& value = new_node->value;
+    new_node->next = std::move(head_);
+    head_ = std::move(new_node);
+    return value;
+  }
+};
+}  // namespace detail
+
+/**
+ * A dynamic list of formatting arguments with storage.
+ *
+ * It can be implicitly converted into `fmt::basic_format_args` for passing
+ * into type-erased formatting functions such as `fmt::vformat`.
+ */
+FMT_EXPORT template <typename Context> class dynamic_format_arg_store {
+ private:
+  using char_type = typename Context::char_type;
+
+  template <typename T> struct need_copy {
+    static constexpr detail::type mapped_type =
+        detail::mapped_type_constant<T, char_type>::value;
+
+    enum {
+      value = !(detail::is_reference_wrapper<T>::value ||
+                std::is_same<T, basic_string_view<char_type>>::value ||
+                std::is_same<T, detail::std_string_view<char_type>>::value ||
+                (mapped_type != detail::type::cstring_type &&
+                 mapped_type != detail::type::string_type &&
+                 mapped_type != detail::type::custom_type))
+    };
+  };
+
+  template <typename T>
+  using stored_t = conditional_t<
+      std::is_convertible<T, std::basic_string<char_type>>::value &&
+          !detail::is_reference_wrapper<T>::value,
+      std::basic_string<char_type>, T>;
+
+  // Storage of basic_format_arg must be contiguous.
+  std::vector<basic_format_arg<Context>> data_;
+  std::vector<detail::named_arg_info<char_type>> named_info_;
+
+  // Storage of arguments not fitting into basic_format_arg must grow
+  // without relocation because items in data_ refer to it.
+  detail::dynamic_arg_list dynamic_args_;
+
+  friend class basic_format_args<Context>;
+
+  auto data() const -> const basic_format_arg<Context>* {
+    return named_info_.empty() ? data_.data() : data_.data() + 1;
+  }
+
+  template <typename T> void emplace_arg(const T& arg) {
+    data_.emplace_back(arg);
+  }
+
+  template <typename T>
+  void emplace_arg(const detail::named_arg<char_type, T>& arg) {
+    if (named_info_.empty())
+      data_.insert(data_.begin(), basic_format_arg<Context>(nullptr, 0));
+    data_.emplace_back(detail::unwrap(arg.value));
+    auto pop_one = [](std::vector<basic_format_arg<Context>>* data) {
+      data->pop_back();
+    };
+    std::unique_ptr<std::vector<basic_format_arg<Context>>, decltype(pop_one)>
+        guard{&data_, pop_one};
+    named_info_.push_back({arg.name, static_cast<int>(data_.size() - 2u)});
+    data_[0] = {named_info_.data(), named_info_.size()};
+    guard.release();
+  }
+
+ public:
+  constexpr dynamic_format_arg_store() = default;
+
+  operator basic_format_args<Context>() const {
+    return basic_format_args<Context>(data(), static_cast<int>(data_.size()),
+                                      !named_info_.empty());
+  }
+
+  /**
+   * Adds an argument into the dynamic store for later passing to a formatting
+   * function.
+   *
+   * Note that custom types and string types (but not string views) are copied
+   * into the store dynamically allocating memory if necessary.
+   *
+   * **Example**:
+   *
+   *     fmt::dynamic_format_arg_store<fmt::format_context> store;
+   *     store.push_back(42);
+   *     store.push_back("abc");
+   *     store.push_back(1.5f);
+   *     std::string result = fmt::vformat("{} and {} and {}", store);
+   */
+  template <typename T> void push_back(const T& arg) {
+    if (detail::const_check(need_copy<T>::value))
+      emplace_arg(dynamic_args_.push<stored_t<T>>(arg));
+    else
+      emplace_arg(detail::unwrap(arg));
+  }
+
+  /**
+   * Adds a reference to the argument into the dynamic store for later passing
+   * to a formatting function.
+   *
+   * **Example**:
+   *
+   *     fmt::dynamic_format_arg_store<fmt::format_context> store;
+   *     char band[] = "Rolling Stones";
+   *     store.push_back(std::cref(band));
+   *     band[9] = 'c'; // Changing str affects the output.
+   *     std::string result = fmt::vformat("{}", store);
+   *     // result == "Rolling Scones"
+   */
+  template <typename T> void push_back(std::reference_wrapper<T> arg) {
+    static_assert(
+        need_copy<T>::value,
+        "objects of built-in types and string views are always copied");
+    emplace_arg(arg.get());
+  }
+
+  /**
+   * Adds named argument into the dynamic store for later passing to a
+   * formatting function. `std::reference_wrapper` is supported to avoid
+   * copying of the argument. The name is always copied into the store.
+   */
+  template <typename T>
+  void push_back(const detail::named_arg<char_type, T>& arg) {
+    const char_type* arg_name =
+        dynamic_args_.push<std::basic_string<char_type>>(arg.name).c_str();
+    if (detail::const_check(need_copy<T>::value)) {
+      emplace_arg(
+          fmt::arg(arg_name, dynamic_args_.push<stored_t<T>>(arg.value)));
+    } else {
+      emplace_arg(fmt::arg(arg_name, arg.value));
+    }
+  }
+
+  /// Erase all elements from the store.
+  void clear() {
+    data_.clear();
+    named_info_.clear();
+    dynamic_args_ = {};
+  }
+
+  /// Reserves space to store at least `new_cap` arguments including
+  /// `new_cap_named` named arguments.
+  void reserve(size_t new_cap, size_t new_cap_named) {
+    FMT_ASSERT(new_cap >= new_cap_named,
+               "set of arguments includes set of named arguments");
+    data_.reserve(new_cap);
+    named_info_.reserve(new_cap_named);
+  }
+
+  /// Returns the number of elements in the store.
+  auto size() const noexcept -> size_t { return data_.size(); }
+};
+
+FMT_END_NAMESPACE
+
+#endif  // FMT_ARGS_H_

+ 2994 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/base.h

@@ -0,0 +1,2994 @@
+// Formatting library for C++ - the base API for char/UTF-8
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_BASE_H_
+#define FMT_BASE_H_
+
+#if defined(FMT_IMPORT_STD) && !defined(FMT_MODULE)
+#  define FMT_MODULE
+#endif
+
+#ifndef FMT_MODULE
+#  include <limits.h>  // CHAR_BIT
+#  include <stdio.h>   // FILE
+#  include <string.h>  // memcmp
+
+#  include <type_traits>  // std::enable_if
+#endif
+
+// The fmt library version in the form major * 10000 + minor * 100 + patch.
+#define FMT_VERSION 120000
+
+// Detect compiler versions.
+#if defined(__clang__) && !defined(__ibmxl__)
+#  define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
+#else
+#  define FMT_CLANG_VERSION 0
+#endif
+#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
+#  define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+#else
+#  define FMT_GCC_VERSION 0
+#endif
+#if defined(__ICL)
+#  define FMT_ICC_VERSION __ICL
+#elif defined(__INTEL_COMPILER)
+#  define FMT_ICC_VERSION __INTEL_COMPILER
+#else
+#  define FMT_ICC_VERSION 0
+#endif
+#if defined(_MSC_VER)
+#  define FMT_MSC_VERSION _MSC_VER
+#else
+#  define FMT_MSC_VERSION 0
+#endif
+
+// Detect standard library versions.
+#ifdef _GLIBCXX_RELEASE
+#  define FMT_GLIBCXX_RELEASE _GLIBCXX_RELEASE
+#else
+#  define FMT_GLIBCXX_RELEASE 0
+#endif
+#ifdef _LIBCPP_VERSION
+#  define FMT_LIBCPP_VERSION _LIBCPP_VERSION
+#else
+#  define FMT_LIBCPP_VERSION 0
+#endif
+
+#ifdef _MSVC_LANG
+#  define FMT_CPLUSPLUS _MSVC_LANG
+#else
+#  define FMT_CPLUSPLUS __cplusplus
+#endif
+
+// Detect __has_*.
+#ifdef __has_feature
+#  define FMT_HAS_FEATURE(x) __has_feature(x)
+#else
+#  define FMT_HAS_FEATURE(x) 0
+#endif
+#ifdef __has_include
+#  define FMT_HAS_INCLUDE(x) __has_include(x)
+#else
+#  define FMT_HAS_INCLUDE(x) 0
+#endif
+#ifdef __has_builtin
+#  define FMT_HAS_BUILTIN(x) __has_builtin(x)
+#else
+#  define FMT_HAS_BUILTIN(x) 0
+#endif
+#ifdef __has_cpp_attribute
+#  define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
+#else
+#  define FMT_HAS_CPP_ATTRIBUTE(x) 0
+#endif
+
+#define FMT_HAS_CPP14_ATTRIBUTE(attribute) \
+  (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute))
+
+#define FMT_HAS_CPP17_ATTRIBUTE(attribute) \
+  (FMT_CPLUSPLUS >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute))
+
+// Detect C++14 relaxed constexpr.
+#ifdef FMT_USE_CONSTEXPR
+// Use the provided definition.
+#elif FMT_GCC_VERSION >= 702 && FMT_CPLUSPLUS >= 201402L
+// GCC only allows constexpr member functions in non-literal types since 7.2:
+// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66297.
+#  define FMT_USE_CONSTEXPR 1
+#elif FMT_ICC_VERSION
+#  define FMT_USE_CONSTEXPR 0  // https://github.com/fmtlib/fmt/issues/1628
+#elif FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912
+#  define FMT_USE_CONSTEXPR 1
+#else
+#  define FMT_USE_CONSTEXPR 0
+#endif
+#if FMT_USE_CONSTEXPR
+#  define FMT_CONSTEXPR constexpr
+#else
+#  define FMT_CONSTEXPR
+#endif
+
+// Detect consteval, C++20 constexpr extensions and std::is_constant_evaluated.
+#if !defined(__cpp_lib_is_constant_evaluated)
+#  define FMT_USE_CONSTEVAL 0
+#elif FMT_CPLUSPLUS < 201709L
+#  define FMT_USE_CONSTEVAL 0
+#elif FMT_GLIBCXX_RELEASE && FMT_GLIBCXX_RELEASE < 10
+#  define FMT_USE_CONSTEVAL 0
+#elif FMT_LIBCPP_VERSION && FMT_LIBCPP_VERSION < 10000
+#  define FMT_USE_CONSTEVAL 0
+#elif defined(__apple_build_version__) && __apple_build_version__ < 14000029L
+#  define FMT_USE_CONSTEVAL 0  // consteval is broken in Apple clang < 14.
+#elif FMT_MSC_VERSION && FMT_MSC_VERSION < 1929
+#  define FMT_USE_CONSTEVAL 0  // consteval is broken in MSVC VS2019 < 16.10.
+#elif defined(__cpp_consteval)
+#  define FMT_USE_CONSTEVAL 1
+#elif FMT_GCC_VERSION >= 1002 || FMT_CLANG_VERSION >= 1101
+#  define FMT_USE_CONSTEVAL 1
+#else
+#  define FMT_USE_CONSTEVAL 0
+#endif
+#if FMT_USE_CONSTEVAL
+#  define FMT_CONSTEVAL consteval
+#  define FMT_CONSTEXPR20 constexpr
+#else
+#  define FMT_CONSTEVAL
+#  define FMT_CONSTEXPR20
+#endif
+
+// Check if exceptions are disabled.
+#ifdef FMT_USE_EXCEPTIONS
+// Use the provided definition.
+#elif defined(__GNUC__) && !defined(__EXCEPTIONS)
+#  define FMT_USE_EXCEPTIONS 0
+#elif defined(__clang__) && !defined(__cpp_exceptions)
+#  define FMT_USE_EXCEPTIONS 0
+#elif FMT_MSC_VERSION && !_HAS_EXCEPTIONS
+#  define FMT_USE_EXCEPTIONS 0
+#else
+#  define FMT_USE_EXCEPTIONS 1
+#endif
+#if FMT_USE_EXCEPTIONS
+#  define FMT_TRY try
+#  define FMT_CATCH(x) catch (x)
+#else
+#  define FMT_TRY if (true)
+#  define FMT_CATCH(x) if (false)
+#endif
+
+#ifdef FMT_NO_UNIQUE_ADDRESS
+// Use the provided definition.
+#elif FMT_CPLUSPLUS < 202002L
+// Not supported.
+#elif FMT_HAS_CPP_ATTRIBUTE(no_unique_address)
+#  define FMT_NO_UNIQUE_ADDRESS [[no_unique_address]]
+// VS2019 v16.10 and later except clang-cl (https://reviews.llvm.org/D110485).
+#elif FMT_MSC_VERSION >= 1929 && !FMT_CLANG_VERSION
+#  define FMT_NO_UNIQUE_ADDRESS [[msvc::no_unique_address]]
+#endif
+#ifndef FMT_NO_UNIQUE_ADDRESS
+#  define FMT_NO_UNIQUE_ADDRESS
+#endif
+
+#if FMT_HAS_CPP17_ATTRIBUTE(fallthrough)
+#  define FMT_FALLTHROUGH [[fallthrough]]
+#elif defined(__clang__)
+#  define FMT_FALLTHROUGH [[clang::fallthrough]]
+#elif FMT_GCC_VERSION >= 700 && \
+    (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520)
+#  define FMT_FALLTHROUGH [[gnu::fallthrough]]
+#else
+#  define FMT_FALLTHROUGH
+#endif
+
+// Disable [[noreturn]] on MSVC/NVCC because of bogus unreachable code warnings.
+#if FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && !defined(__NVCC__)
+#  define FMT_NORETURN [[noreturn]]
+#else
+#  define FMT_NORETURN
+#endif
+
+#ifdef FMT_NODISCARD
+// Use the provided definition.
+#elif FMT_HAS_CPP17_ATTRIBUTE(nodiscard)
+#  define FMT_NODISCARD [[nodiscard]]
+#else
+#  define FMT_NODISCARD
+#endif
+
+#if FMT_GCC_VERSION || FMT_CLANG_VERSION
+#  define FMT_VISIBILITY(value) __attribute__((visibility(value)))
+#else
+#  define FMT_VISIBILITY(value)
+#endif
+
+// Detect pragmas.
+#define FMT_PRAGMA_IMPL(x) _Pragma(#x)
+#if FMT_GCC_VERSION >= 504 && !defined(__NVCOMPILER)
+// Workaround a _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884
+// and an nvhpc warning: https://github.com/fmtlib/fmt/pull/2582.
+#  define FMT_PRAGMA_GCC(x) FMT_PRAGMA_IMPL(GCC x)
+#else
+#  define FMT_PRAGMA_GCC(x)
+#endif
+#if FMT_CLANG_VERSION
+#  define FMT_PRAGMA_CLANG(x) FMT_PRAGMA_IMPL(clang x)
+#else
+#  define FMT_PRAGMA_CLANG(x)
+#endif
+#if FMT_MSC_VERSION
+#  define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__))
+#else
+#  define FMT_MSC_WARNING(...)
+#endif
+
+// Enable minimal optimizations for more compact code in debug mode.
+FMT_PRAGMA_GCC(push_options)
+#if !defined(__OPTIMIZE__) && !defined(__CUDACC__) && !defined(FMT_MODULE)
+FMT_PRAGMA_GCC(optimize("Og"))
+#  define FMT_GCC_OPTIMIZED
+#endif
+FMT_PRAGMA_CLANG(diagnostic push)
+
+#ifdef FMT_ALWAYS_INLINE
+// Use the provided definition.
+#elif FMT_GCC_VERSION || FMT_CLANG_VERSION
+#  define FMT_ALWAYS_INLINE inline __attribute__((always_inline))
+#else
+#  define FMT_ALWAYS_INLINE inline
+#endif
+// A version of FMT_ALWAYS_INLINE to prevent code bloat in debug mode.
+#if defined(NDEBUG) || defined(FMT_GCC_OPTIMIZED)
+#  define FMT_INLINE FMT_ALWAYS_INLINE
+#else
+#  define FMT_INLINE inline
+#endif
+
+#ifndef FMT_BEGIN_NAMESPACE
+#  define FMT_BEGIN_NAMESPACE \
+    namespace fmt {           \
+    inline namespace v12 {
+#  define FMT_END_NAMESPACE \
+    }                       \
+    }
+#endif
+
+#ifndef FMT_EXPORT
+#  define FMT_EXPORT
+#  define FMT_BEGIN_EXPORT
+#  define FMT_END_EXPORT
+#endif
+
+#ifdef _WIN32
+#  define FMT_WIN32 1
+#else
+#  define FMT_WIN32 0
+#endif
+
+#if !defined(FMT_HEADER_ONLY) && FMT_WIN32
+#  if defined(FMT_LIB_EXPORT)
+#    define FMT_API __declspec(dllexport)
+#  elif defined(FMT_SHARED)
+#    define FMT_API __declspec(dllimport)
+#  endif
+#elif defined(FMT_LIB_EXPORT) || defined(FMT_SHARED)
+#  define FMT_API FMT_VISIBILITY("default")
+#endif
+#ifndef FMT_API
+#  define FMT_API
+#endif
+
+#ifndef FMT_OPTIMIZE_SIZE
+#  define FMT_OPTIMIZE_SIZE 0
+#endif
+
+// FMT_BUILTIN_TYPE=0 may result in smaller library size at the cost of higher
+// per-call binary size by passing built-in types through the extension API.
+#ifndef FMT_BUILTIN_TYPES
+#  define FMT_BUILTIN_TYPES 1
+#endif
+
+#define FMT_APPLY_VARIADIC(expr) \
+  using unused = int[];          \
+  (void)unused { 0, (expr, 0)... }
+
+FMT_BEGIN_NAMESPACE
+
+// Implementations of enable_if_t and other metafunctions for older systems.
+template <bool B, typename T = void>
+using enable_if_t = typename std::enable_if<B, T>::type;
+template <bool B, typename T, typename F>
+using conditional_t = typename std::conditional<B, T, F>::type;
+template <bool B> using bool_constant = std::integral_constant<bool, B>;
+template <typename T>
+using remove_reference_t = typename std::remove_reference<T>::type;
+template <typename T>
+using remove_const_t = typename std::remove_const<T>::type;
+template <typename T>
+using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;
+template <typename T>
+using make_unsigned_t = typename std::make_unsigned<T>::type;
+template <typename T>
+using underlying_t = typename std::underlying_type<T>::type;
+template <typename T> using decay_t = typename std::decay<T>::type;
+using nullptr_t = decltype(nullptr);
+
+#if (FMT_GCC_VERSION && FMT_GCC_VERSION < 500) || FMT_MSC_VERSION
+// A workaround for gcc 4.9 & MSVC v141 to make void_t work in a SFINAE context.
+template <typename...> struct void_t_impl {
+  using type = void;
+};
+template <typename... T> using void_t = typename void_t_impl<T...>::type;
+#else
+template <typename...> using void_t = void;
+#endif
+
+struct monostate {
+  constexpr monostate() {}
+};
+
+// An enable_if helper to be used in template parameters which results in much
+// shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed
+// to workaround a bug in MSVC 2019 (see #1140 and #1186).
+#ifdef FMT_DOC
+#  define FMT_ENABLE_IF(...)
+#else
+#  define FMT_ENABLE_IF(...) fmt::enable_if_t<(__VA_ARGS__), int> = 0
+#endif
+
+template <typename T> constexpr auto min_of(T a, T b) -> T {
+  return a < b ? a : b;
+}
+template <typename T> constexpr auto max_of(T a, T b) -> T {
+  return a > b ? a : b;
+}
+
+FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
+                                      const char* message);
+
+namespace detail {
+// Suppresses "unused variable" warnings with the method described in
+// https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/.
+// (void)var does not work on many Intel compilers.
+template <typename... T> FMT_CONSTEXPR void ignore_unused(const T&...) {}
+
+constexpr auto is_constant_evaluated(bool default_value = false) noexcept
+    -> bool {
+// Workaround for incompatibility between clang 14 and libstdc++ consteval-based
+// std::is_constant_evaluated: https://github.com/fmtlib/fmt/issues/3247.
+#if FMT_CPLUSPLUS >= 202002L && FMT_GLIBCXX_RELEASE >= 12 && \
+    (FMT_CLANG_VERSION >= 1400 && FMT_CLANG_VERSION < 1500)
+  ignore_unused(default_value);
+  return __builtin_is_constant_evaluated();
+#elif defined(__cpp_lib_is_constant_evaluated)
+  ignore_unused(default_value);
+  return std::is_constant_evaluated();
+#else
+  return default_value;
+#endif
+}
+
+// Suppresses "conditional expression is constant" warnings.
+template <typename T> FMT_ALWAYS_INLINE constexpr auto const_check(T val) -> T {
+  return val;
+}
+
+FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
+                                      const char* message);
+
+#if defined(FMT_ASSERT)
+// Use the provided definition.
+#elif defined(NDEBUG)
+// FMT_ASSERT is not empty to avoid -Wempty-body.
+#  define FMT_ASSERT(condition, message) \
+    fmt::detail::ignore_unused((condition), (message))
+#else
+#  define FMT_ASSERT(condition, message)                                    \
+    ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \
+         ? (void)0                                                          \
+         : ::fmt::assert_fail(__FILE__, __LINE__, (message)))
+#endif
+
+#ifdef FMT_USE_INT128
+// Use the provided definition.
+#elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \
+    !(FMT_CLANG_VERSION && FMT_MSC_VERSION)
+#  define FMT_USE_INT128 1
+using int128_opt = __int128_t;  // An optional native 128-bit integer.
+using uint128_opt = __uint128_t;
+inline auto map(int128_opt x) -> int128_opt { return x; }
+inline auto map(uint128_opt x) -> uint128_opt { return x; }
+#else
+#  define FMT_USE_INT128 0
+#endif
+#if !FMT_USE_INT128
+enum class int128_opt {};
+enum class uint128_opt {};
+// Reduce template instantiations.
+inline auto map(int128_opt) -> monostate { return {}; }
+inline auto map(uint128_opt) -> monostate { return {}; }
+#endif
+
+#ifndef FMT_USE_BITINT
+#  define FMT_USE_BITINT (FMT_CLANG_VERSION >= 1500)
+#endif
+
+#if FMT_USE_BITINT
+FMT_PRAGMA_CLANG(diagnostic ignored "-Wbit-int-extension")
+template <int N> using bitint = _BitInt(N);
+template <int N> using ubitint = unsigned _BitInt(N);
+#else
+template <int N> struct bitint {};
+template <int N> struct ubitint {};
+#endif  // FMT_USE_BITINT
+
+// Casts a nonnegative integer to unsigned.
+template <typename Int>
+FMT_CONSTEXPR auto to_unsigned(Int value) -> make_unsigned_t<Int> {
+  FMT_ASSERT(std::is_unsigned<Int>::value || value >= 0, "negative value");
+  return static_cast<make_unsigned_t<Int>>(value);
+}
+
+template <typename Char>
+using unsigned_char = conditional_t<sizeof(Char) == 1, unsigned char, unsigned>;
+
+// A heuristic to detect std::string and std::[experimental::]string_view.
+// It is mainly used to avoid dependency on <[experimental/]string_view>.
+template <typename T, typename Enable = void>
+struct is_std_string_like : std::false_type {};
+template <typename T>
+struct is_std_string_like<T, void_t<decltype(std::declval<T>().find_first_of(
+                                 typename T::value_type(), 0))>>
+    : std::is_convertible<decltype(std::declval<T>().data()),
+                          const typename T::value_type*> {};
+
+// Check if the literal encoding is UTF-8.
+enum { is_utf8_enabled = "\u00A7"[1] == '\xA7' };
+enum { use_utf8 = !FMT_WIN32 || is_utf8_enabled };
+
+#ifndef FMT_UNICODE
+#  define FMT_UNICODE 1
+#endif
+
+static_assert(!FMT_UNICODE || use_utf8,
+              "Unicode support requires compiling with /utf-8");
+
+template <typename T> constexpr auto narrow(T*) -> char* { return nullptr; }
+constexpr FMT_ALWAYS_INLINE auto narrow(const char* s) -> const char* {
+  return s;
+}
+
+template <typename Char>
+FMT_CONSTEXPR auto compare(const Char* s1, const Char* s2, size_t n) -> int {
+  if (!is_constant_evaluated() && sizeof(Char) == 1) return memcmp(s1, s2, n);
+  for (; n != 0; ++s1, ++s2, --n) {
+    if (*s1 < *s2) return -1;
+    if (*s1 > *s2) return 1;
+  }
+  return 0;
+}
+
+namespace adl {
+using namespace std;
+
+template <typename Container>
+auto invoke_back_inserter()
+    -> decltype(back_inserter(std::declval<Container&>()));
+}  // namespace adl
+
+template <typename It, typename Enable = std::true_type>
+struct is_back_insert_iterator : std::false_type {};
+
+template <typename It>
+struct is_back_insert_iterator<
+    It, bool_constant<std::is_same<
+            decltype(adl::invoke_back_inserter<typename It::container_type>()),
+            It>::value>> : std::true_type {};
+
+// Extracts a reference to the container from *insert_iterator.
+template <typename OutputIt>
+inline FMT_CONSTEXPR20 auto get_container(OutputIt it) ->
+    typename OutputIt::container_type& {
+  struct accessor : OutputIt {
+    FMT_CONSTEXPR20 accessor(OutputIt base) : OutputIt(base) {}
+    using OutputIt::container;
+  };
+  return *accessor(it).container;
+}
+}  // namespace detail
+
+// Parsing-related public API and forward declarations.
+FMT_BEGIN_EXPORT
+
+/**
+ * An implementation of `std::basic_string_view` for pre-C++17. It provides a
+ * subset of the API. `fmt::basic_string_view` is used for format strings even
+ * if `std::basic_string_view` is available to prevent issues when a library is
+ * compiled with a different `-std` option than the client code (which is not
+ * recommended).
+ */
+template <typename Char> class basic_string_view {
+ private:
+  const Char* data_;
+  size_t size_;
+
+ public:
+  using value_type = Char;
+  using iterator = const Char*;
+
+  constexpr basic_string_view() noexcept : data_(nullptr), size_(0) {}
+
+  /// Constructs a string view object from a C string and a size.
+  constexpr basic_string_view(const Char* s, size_t count) noexcept
+      : data_(s), size_(count) {}
+
+  constexpr basic_string_view(nullptr_t) = delete;
+
+  /// Constructs a string view object from a C string.
+#if FMT_GCC_VERSION
+  FMT_ALWAYS_INLINE
+#endif
+  FMT_CONSTEXPR20 basic_string_view(const Char* s) : data_(s) {
+#if FMT_HAS_BUILTIN(__builtin_strlen) || FMT_GCC_VERSION || FMT_CLANG_VERSION
+    if (std::is_same<Char, char>::value && !detail::is_constant_evaluated()) {
+      size_ = __builtin_strlen(detail::narrow(s));  // strlen is not constexpr.
+      return;
+    }
+#endif
+    size_t len = 0;
+    while (*s++) ++len;
+    size_ = len;
+  }
+
+  /// Constructs a string view from a `std::basic_string` or a
+  /// `std::basic_string_view` object.
+  template <typename S,
+            FMT_ENABLE_IF(detail::is_std_string_like<S>::value&& std::is_same<
+                          typename S::value_type, Char>::value)>
+  FMT_CONSTEXPR basic_string_view(const S& s) noexcept
+      : data_(s.data()), size_(s.size()) {}
+
+  /// Returns a pointer to the string data.
+  constexpr auto data() const noexcept -> const Char* { return data_; }
+
+  /// Returns the string size.
+  constexpr auto size() const noexcept -> size_t { return size_; }
+
+  constexpr auto begin() const noexcept -> iterator { return data_; }
+  constexpr auto end() const noexcept -> iterator { return data_ + size_; }
+
+  constexpr auto operator[](size_t pos) const noexcept -> const Char& {
+    return data_[pos];
+  }
+
+  FMT_CONSTEXPR void remove_prefix(size_t n) noexcept {
+    data_ += n;
+    size_ -= n;
+  }
+
+  FMT_CONSTEXPR auto starts_with(basic_string_view<Char> sv) const noexcept
+      -> bool {
+    return size_ >= sv.size_ && detail::compare(data_, sv.data_, sv.size_) == 0;
+  }
+  FMT_CONSTEXPR auto starts_with(Char c) const noexcept -> bool {
+    return size_ >= 1 && *data_ == c;
+  }
+  FMT_CONSTEXPR auto starts_with(const Char* s) const -> bool {
+    return starts_with(basic_string_view<Char>(s));
+  }
+
+  FMT_CONSTEXPR auto compare(basic_string_view other) const -> int {
+    int result =
+        detail::compare(data_, other.data_, min_of(size_, other.size_));
+    if (result != 0) return result;
+    return size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
+  }
+
+  FMT_CONSTEXPR friend auto operator==(basic_string_view lhs,
+                                       basic_string_view rhs) -> bool {
+    return lhs.compare(rhs) == 0;
+  }
+  friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool {
+    return lhs.compare(rhs) != 0;
+  }
+  friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool {
+    return lhs.compare(rhs) < 0;
+  }
+  friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool {
+    return lhs.compare(rhs) <= 0;
+  }
+  friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool {
+    return lhs.compare(rhs) > 0;
+  }
+  friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool {
+    return lhs.compare(rhs) >= 0;
+  }
+};
+
+using string_view = basic_string_view<char>;
+
+template <typename T> class basic_appender;
+using appender = basic_appender<char>;
+
+// Checks whether T is a container with contiguous storage.
+template <typename T> struct is_contiguous : std::false_type {};
+
+class context;
+template <typename OutputIt, typename Char> class generic_context;
+template <typename Char> class parse_context;
+
+// Longer aliases for C++20 compatibility.
+template <typename Char> using basic_format_parse_context = parse_context<Char>;
+using format_parse_context = parse_context<char>;
+template <typename OutputIt, typename Char>
+using basic_format_context =
+    conditional_t<std::is_same<OutputIt, appender>::value, context,
+                  generic_context<OutputIt, Char>>;
+using format_context = context;
+
+template <typename Char>
+using buffered_context =
+    conditional_t<std::is_same<Char, char>::value, context,
+                  generic_context<basic_appender<Char>, Char>>;
+
+template <typename Context> class basic_format_arg;
+template <typename Context> class basic_format_args;
+
+// A separate type would result in shorter symbols but break ABI compatibility
+// between clang and gcc on ARM (#1919).
+using format_args = basic_format_args<context>;
+
+// A formatter for objects of type T.
+template <typename T, typename Char = char, typename Enable = void>
+struct formatter {
+  // A deleted default constructor indicates a disabled formatter.
+  formatter() = delete;
+};
+
+/// Reports a format error at compile time or, via a `format_error` exception,
+/// at runtime.
+// This function is intentionally not constexpr to give a compile-time error.
+FMT_NORETURN FMT_API void report_error(const char* message);
+
+enum class presentation_type : unsigned char {
+  // Common specifiers:
+  none = 0,
+  debug = 1,   // '?'
+  string = 2,  // 's' (string, bool)
+
+  // Integral, bool and character specifiers:
+  dec = 3,  // 'd'
+  hex,      // 'x' or 'X'
+  oct,      // 'o'
+  bin,      // 'b' or 'B'
+  chr,      // 'c'
+
+  // String and pointer specifiers:
+  pointer = 3,  // 'p'
+
+  // Floating-point specifiers:
+  exp = 1,  // 'e' or 'E' (1 since there is no FP debug presentation)
+  fixed,    // 'f' or 'F'
+  general,  // 'g' or 'G'
+  hexfloat  // 'a' or 'A'
+};
+
+enum class align { none, left, right, center, numeric };
+enum class sign { none, minus, plus, space };
+enum class arg_id_kind { none, index, name };
+
+// Basic format specifiers for built-in and string types.
+class basic_specs {
+ private:
+  // Data is arranged as follows:
+  //
+  //  0                   1                   2                   3
+  //  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
+  // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+  // |type |align| w | p | s |u|#|L|  f  |          unused           |
+  // +-----+-----+---+---+---+-+-+-+-----+---------------------------+
+  //
+  //   w - dynamic width info
+  //   p - dynamic precision info
+  //   s - sign
+  //   u - uppercase (e.g. 'X' for 'x')
+  //   # - alternate form ('#')
+  //   L - localized
+  //   f - fill size
+  //
+  // Bitfields are not used because of compiler bugs such as gcc bug 61414.
+  enum : unsigned {
+    type_mask = 0x00007,
+    align_mask = 0x00038,
+    width_mask = 0x000C0,
+    precision_mask = 0x00300,
+    sign_mask = 0x00C00,
+    uppercase_mask = 0x01000,
+    alternate_mask = 0x02000,
+    localized_mask = 0x04000,
+    fill_size_mask = 0x38000,
+
+    align_shift = 3,
+    width_shift = 6,
+    precision_shift = 8,
+    sign_shift = 10,
+    fill_size_shift = 15,
+
+    max_fill_size = 4
+  };
+
+  unsigned data_ = 1 << fill_size_shift;
+  static_assert(sizeof(basic_specs::data_) * CHAR_BIT >= 18, "");
+
+  // Character (code unit) type is erased to prevent template bloat.
+  char fill_data_[max_fill_size] = {' '};
+
+  FMT_CONSTEXPR void set_fill_size(size_t size) {
+    data_ = (data_ & ~fill_size_mask) |
+            (static_cast<unsigned>(size) << fill_size_shift);
+  }
+
+ public:
+  constexpr auto type() const -> presentation_type {
+    return static_cast<presentation_type>(data_ & type_mask);
+  }
+  FMT_CONSTEXPR void set_type(presentation_type t) {
+    data_ = (data_ & ~type_mask) | static_cast<unsigned>(t);
+  }
+
+  constexpr auto align() const -> align {
+    return static_cast<fmt::align>((data_ & align_mask) >> align_shift);
+  }
+  FMT_CONSTEXPR void set_align(fmt::align a) {
+    data_ = (data_ & ~align_mask) | (static_cast<unsigned>(a) << align_shift);
+  }
+
+  constexpr auto dynamic_width() const -> arg_id_kind {
+    return static_cast<arg_id_kind>((data_ & width_mask) >> width_shift);
+  }
+  FMT_CONSTEXPR void set_dynamic_width(arg_id_kind w) {
+    data_ = (data_ & ~width_mask) | (static_cast<unsigned>(w) << width_shift);
+  }
+
+  FMT_CONSTEXPR auto dynamic_precision() const -> arg_id_kind {
+    return static_cast<arg_id_kind>((data_ & precision_mask) >>
+                                    precision_shift);
+  }
+  FMT_CONSTEXPR void set_dynamic_precision(arg_id_kind p) {
+    data_ = (data_ & ~precision_mask) |
+            (static_cast<unsigned>(p) << precision_shift);
+  }
+
+  constexpr auto dynamic() const -> bool {
+    return (data_ & (width_mask | precision_mask)) != 0;
+  }
+
+  constexpr auto sign() const -> sign {
+    return static_cast<fmt::sign>((data_ & sign_mask) >> sign_shift);
+  }
+  FMT_CONSTEXPR void set_sign(fmt::sign s) {
+    data_ = (data_ & ~sign_mask) | (static_cast<unsigned>(s) << sign_shift);
+  }
+
+  constexpr auto upper() const -> bool { return (data_ & uppercase_mask) != 0; }
+  FMT_CONSTEXPR void set_upper() { data_ |= uppercase_mask; }
+
+  constexpr auto alt() const -> bool { return (data_ & alternate_mask) != 0; }
+  FMT_CONSTEXPR void set_alt() { data_ |= alternate_mask; }
+  FMT_CONSTEXPR void clear_alt() { data_ &= ~alternate_mask; }
+
+  constexpr auto localized() const -> bool {
+    return (data_ & localized_mask) != 0;
+  }
+  FMT_CONSTEXPR void set_localized() { data_ |= localized_mask; }
+
+  constexpr auto fill_size() const -> size_t {
+    return (data_ & fill_size_mask) >> fill_size_shift;
+  }
+
+  template <typename Char, FMT_ENABLE_IF(std::is_same<Char, char>::value)>
+  constexpr auto fill() const -> const Char* {
+    return fill_data_;
+  }
+  template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
+  constexpr auto fill() const -> const Char* {
+    return nullptr;
+  }
+
+  template <typename Char> constexpr auto fill_unit() const -> Char {
+    using uchar = unsigned char;
+    return static_cast<Char>(static_cast<uchar>(fill_data_[0]) |
+                             (static_cast<uchar>(fill_data_[1]) << 8) |
+                             (static_cast<uchar>(fill_data_[2]) << 16));
+  }
+
+  FMT_CONSTEXPR void set_fill(char c) {
+    fill_data_[0] = c;
+    set_fill_size(1);
+  }
+
+  template <typename Char>
+  FMT_CONSTEXPR void set_fill(basic_string_view<Char> s) {
+    auto size = s.size();
+    set_fill_size(size);
+    if (size == 1) {
+      unsigned uchar = static_cast<detail::unsigned_char<Char>>(s[0]);
+      fill_data_[0] = static_cast<char>(uchar);
+      fill_data_[1] = static_cast<char>(uchar >> 8);
+      fill_data_[2] = static_cast<char>(uchar >> 16);
+      return;
+    }
+    FMT_ASSERT(size <= max_fill_size, "invalid fill");
+    for (size_t i = 0; i < size; ++i)
+      fill_data_[i & 3] = static_cast<char>(s[i]);
+  }
+
+  FMT_CONSTEXPR void copy_fill_from(const basic_specs& specs) {
+    set_fill_size(specs.fill_size());
+    for (size_t i = 0; i < max_fill_size; ++i)
+      fill_data_[i] = specs.fill_data_[i];
+  }
+};
+
+// Format specifiers for built-in and string types.
+struct format_specs : basic_specs {
+  int width;
+  int precision;
+
+  constexpr format_specs() : width(0), precision(-1) {}
+};
+
+/**
+ * Parsing context consisting of a format string range being parsed and an
+ * argument counter for automatic indexing.
+ */
+template <typename Char = char> class parse_context {
+ private:
+  basic_string_view<Char> fmt_;
+  int next_arg_id_;
+
+  enum { use_constexpr_cast = !FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200 };
+
+  FMT_CONSTEXPR void do_check_arg_id(int arg_id);
+
+ public:
+  using char_type = Char;
+  using iterator = const Char*;
+
+  constexpr explicit parse_context(basic_string_view<Char> fmt,
+                                   int next_arg_id = 0)
+      : fmt_(fmt), next_arg_id_(next_arg_id) {}
+
+  /// Returns an iterator to the beginning of the format string range being
+  /// parsed.
+  constexpr auto begin() const noexcept -> iterator { return fmt_.begin(); }
+
+  /// Returns an iterator past the end of the format string range being parsed.
+  constexpr auto end() const noexcept -> iterator { return fmt_.end(); }
+
+  /// Advances the begin iterator to `it`.
+  FMT_CONSTEXPR void advance_to(iterator it) {
+    fmt_.remove_prefix(detail::to_unsigned(it - begin()));
+  }
+
+  /// Reports an error if using the manual argument indexing; otherwise returns
+  /// the next argument index and switches to the automatic indexing.
+  FMT_CONSTEXPR auto next_arg_id() -> int {
+    if (next_arg_id_ < 0) {
+      report_error("cannot switch from manual to automatic argument indexing");
+      return 0;
+    }
+    int id = next_arg_id_++;
+    do_check_arg_id(id);
+    return id;
+  }
+
+  /// Reports an error if using the automatic argument indexing; otherwise
+  /// switches to the manual indexing.
+  FMT_CONSTEXPR void check_arg_id(int id) {
+    if (next_arg_id_ > 0) {
+      report_error("cannot switch from automatic to manual argument indexing");
+      return;
+    }
+    next_arg_id_ = -1;
+    do_check_arg_id(id);
+  }
+  FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {
+    next_arg_id_ = -1;
+  }
+  FMT_CONSTEXPR void check_dynamic_spec(int arg_id);
+};
+
+#ifndef FMT_USE_LOCALE
+#  define FMT_USE_LOCALE (FMT_OPTIMIZE_SIZE <= 1)
+#endif
+
+// A type-erased reference to std::locale to avoid the heavy <locale> include.
+class locale_ref {
+#if FMT_USE_LOCALE
+ private:
+  const void* locale_;  // A type-erased pointer to std::locale.
+
+ public:
+  constexpr locale_ref() : locale_(nullptr) {}
+
+  template <typename Locale, FMT_ENABLE_IF(sizeof(Locale::collate) != 0)>
+  locale_ref(const Locale& loc);
+
+  inline explicit operator bool() const noexcept { return locale_ != nullptr; }
+#endif  // FMT_USE_LOCALE
+
+ public:
+  template <typename Locale> auto get() const -> Locale;
+};
+
+FMT_END_EXPORT
+
+namespace detail {
+
+// Specifies if `T` is a code unit type.
+template <typename T> struct is_code_unit : std::false_type {};
+template <> struct is_code_unit<char> : std::true_type {};
+template <> struct is_code_unit<wchar_t> : std::true_type {};
+template <> struct is_code_unit<char16_t> : std::true_type {};
+template <> struct is_code_unit<char32_t> : std::true_type {};
+#ifdef __cpp_char8_t
+template <> struct is_code_unit<char8_t> : bool_constant<is_utf8_enabled> {};
+#endif
+
+// Constructs fmt::basic_string_view<Char> from types implicitly convertible
+// to it, deducing Char. Explicitly convertible types such as the ones returned
+// from FMT_STRING are intentionally excluded.
+template <typename Char, FMT_ENABLE_IF(is_code_unit<Char>::value)>
+constexpr auto to_string_view(const Char* s) -> basic_string_view<Char> {
+  return s;
+}
+template <typename T, FMT_ENABLE_IF(is_std_string_like<T>::value)>
+constexpr auto to_string_view(const T& s)
+    -> basic_string_view<typename T::value_type> {
+  return s;
+}
+template <typename Char>
+constexpr auto to_string_view(basic_string_view<Char> s)
+    -> basic_string_view<Char> {
+  return s;
+}
+
+template <typename T, typename Enable = void>
+struct has_to_string_view : std::false_type {};
+// detail:: is intentional since to_string_view is not an extension point.
+template <typename T>
+struct has_to_string_view<
+    T, void_t<decltype(detail::to_string_view(std::declval<T>()))>>
+    : std::true_type {};
+
+/// String's character (code unit) type. detail:: is intentional to prevent ADL.
+template <typename S,
+          typename V = decltype(detail::to_string_view(std::declval<S>()))>
+using char_t = typename V::value_type;
+
+enum class type {
+  none_type,
+  // Integer types should go first,
+  int_type,
+  uint_type,
+  long_long_type,
+  ulong_long_type,
+  int128_type,
+  uint128_type,
+  bool_type,
+  char_type,
+  last_integer_type = char_type,
+  // followed by floating-point types.
+  float_type,
+  double_type,
+  long_double_type,
+  last_numeric_type = long_double_type,
+  cstring_type,
+  string_type,
+  pointer_type,
+  custom_type
+};
+
+// Maps core type T to the corresponding type enum constant.
+template <typename T, typename Char>
+struct type_constant : std::integral_constant<type, type::custom_type> {};
+
+#define FMT_TYPE_CONSTANT(Type, constant) \
+  template <typename Char>                \
+  struct type_constant<Type, Char>        \
+      : std::integral_constant<type, type::constant> {}
+
+FMT_TYPE_CONSTANT(int, int_type);
+FMT_TYPE_CONSTANT(unsigned, uint_type);
+FMT_TYPE_CONSTANT(long long, long_long_type);
+FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
+FMT_TYPE_CONSTANT(int128_opt, int128_type);
+FMT_TYPE_CONSTANT(uint128_opt, uint128_type);
+FMT_TYPE_CONSTANT(bool, bool_type);
+FMT_TYPE_CONSTANT(Char, char_type);
+FMT_TYPE_CONSTANT(float, float_type);
+FMT_TYPE_CONSTANT(double, double_type);
+FMT_TYPE_CONSTANT(long double, long_double_type);
+FMT_TYPE_CONSTANT(const Char*, cstring_type);
+FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
+FMT_TYPE_CONSTANT(const void*, pointer_type);
+
+constexpr auto is_integral_type(type t) -> bool {
+  return t > type::none_type && t <= type::last_integer_type;
+}
+constexpr auto is_arithmetic_type(type t) -> bool {
+  return t > type::none_type && t <= type::last_numeric_type;
+}
+
+constexpr auto set(type rhs) -> int { return 1 << static_cast<int>(rhs); }
+constexpr auto in(type t, int set) -> bool {
+  return ((set >> static_cast<int>(t)) & 1) != 0;
+}
+
+// Bitsets of types.
+enum {
+  sint_set =
+      set(type::int_type) | set(type::long_long_type) | set(type::int128_type),
+  uint_set = set(type::uint_type) | set(type::ulong_long_type) |
+             set(type::uint128_type),
+  bool_set = set(type::bool_type),
+  char_set = set(type::char_type),
+  float_set = set(type::float_type) | set(type::double_type) |
+              set(type::long_double_type),
+  string_set = set(type::string_type),
+  cstring_set = set(type::cstring_type),
+  pointer_set = set(type::pointer_type)
+};
+
+struct view {};
+
+template <typename T, typename Enable = std::true_type>
+struct is_view : std::false_type {};
+template <typename T>
+struct is_view<T, bool_constant<sizeof(T) != 0>> : std::is_base_of<view, T> {};
+
+template <typename Char, typename T> struct named_arg;
+template <typename T> struct is_named_arg : std::false_type {};
+template <typename T> struct is_static_named_arg : std::false_type {};
+
+template <typename Char, typename T>
+struct is_named_arg<named_arg<Char, T>> : std::true_type {};
+
+template <typename Char, typename T> struct named_arg : view {
+  const Char* name;
+  const T& value;
+
+  named_arg(const Char* n, const T& v) : name(n), value(v) {}
+  static_assert(!is_named_arg<T>::value, "nested named arguments");
+};
+
+template <bool B = false> constexpr auto count() -> int { return B ? 1 : 0; }
+template <bool B1, bool B2, bool... Tail> constexpr auto count() -> int {
+  return (B1 ? 1 : 0) + count<B2, Tail...>();
+}
+
+template <typename... T> constexpr auto count_named_args() -> int {
+  return count<is_named_arg<T>::value...>();
+}
+template <typename... T> constexpr auto count_static_named_args() -> int {
+  return count<is_static_named_arg<T>::value...>();
+}
+
+template <typename Char> struct named_arg_info {
+  const Char* name;
+  int id;
+};
+
+// named_args is non-const to suppress a bogus -Wmaybe-uninitialized in gcc 13.
+template <typename Char>
+FMT_CONSTEXPR void check_for_duplicate(named_arg_info<Char>* named_args,
+                                       int named_arg_index,
+                                       basic_string_view<Char> arg_name) {
+  for (int i = 0; i < named_arg_index; ++i) {
+    if (named_args[i].name == arg_name) report_error("duplicate named arg");
+  }
+}
+
+template <typename Char, typename T, FMT_ENABLE_IF(!is_named_arg<T>::value)>
+void init_named_arg(named_arg_info<Char>*, int& arg_index, int&, const T&) {
+  ++arg_index;
+}
+template <typename Char, typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
+void init_named_arg(named_arg_info<Char>* named_args, int& arg_index,
+                    int& named_arg_index, const T& arg) {
+  check_for_duplicate<Char>(named_args, named_arg_index, arg.name);
+  named_args[named_arg_index++] = {arg.name, arg_index++};
+}
+
+template <typename T, typename Char,
+          FMT_ENABLE_IF(!is_static_named_arg<T>::value)>
+FMT_CONSTEXPR void init_static_named_arg(named_arg_info<Char>*, int& arg_index,
+                                         int&) {
+  ++arg_index;
+}
+template <typename T, typename Char,
+          FMT_ENABLE_IF(is_static_named_arg<T>::value)>
+FMT_CONSTEXPR void init_static_named_arg(named_arg_info<Char>* named_args,
+                                         int& arg_index, int& named_arg_index) {
+  check_for_duplicate<Char>(named_args, named_arg_index, T::name);
+  named_args[named_arg_index++] = {T::name, arg_index++};
+}
+
+// To minimize the number of types we need to deal with, long is translated
+// either to int or to long long depending on its size.
+enum { long_short = sizeof(long) == sizeof(int) && FMT_BUILTIN_TYPES };
+using long_type = conditional_t<long_short, int, long long>;
+using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
+
+template <typename T>
+using format_as_result =
+    remove_cvref_t<decltype(format_as(std::declval<const T&>()))>;
+template <typename T>
+using format_as_member_result =
+    remove_cvref_t<decltype(formatter<T>::format_as(std::declval<const T&>()))>;
+
+template <typename T, typename Enable = std::true_type>
+struct use_format_as : std::false_type {};
+// format_as member is only used to avoid injection into the std namespace.
+template <typename T, typename Enable = std::true_type>
+struct use_format_as_member : std::false_type {};
+
+// Only map owning types because mapping views can be unsafe.
+template <typename T>
+struct use_format_as<
+    T, bool_constant<std::is_arithmetic<format_as_result<T>>::value>>
+    : std::true_type {};
+template <typename T>
+struct use_format_as_member<
+    T, bool_constant<std::is_arithmetic<format_as_member_result<T>>::value>>
+    : std::true_type {};
+
+template <typename T, typename U = remove_const_t<T>>
+using use_formatter =
+    bool_constant<(std::is_class<T>::value || std::is_enum<T>::value ||
+                   std::is_union<T>::value || std::is_array<T>::value) &&
+                  !has_to_string_view<T>::value && !is_named_arg<T>::value &&
+                  !use_format_as<T>::value && !use_format_as_member<U>::value>;
+
+template <typename Char, typename T, typename U = remove_const_t<T>>
+auto has_formatter_impl(T* p, buffered_context<Char>* ctx = nullptr)
+    -> decltype(formatter<U, Char>().format(*p, *ctx), std::true_type());
+template <typename Char> auto has_formatter_impl(...) -> std::false_type;
+
+// T can be const-qualified to check if it is const-formattable.
+template <typename T, typename Char> constexpr auto has_formatter() -> bool {
+  return decltype(has_formatter_impl<Char>(static_cast<T*>(nullptr)))::value;
+}
+
+// Maps formatting argument types to natively supported types or user-defined
+// types with formatters. Returns void on errors to be SFINAE-friendly.
+template <typename Char> struct type_mapper {
+  static auto map(signed char) -> int;
+  static auto map(unsigned char) -> unsigned;
+  static auto map(short) -> int;
+  static auto map(unsigned short) -> unsigned;
+  static auto map(int) -> int;
+  static auto map(unsigned) -> unsigned;
+  static auto map(long) -> long_type;
+  static auto map(unsigned long) -> ulong_type;
+  static auto map(long long) -> long long;
+  static auto map(unsigned long long) -> unsigned long long;
+  static auto map(int128_opt) -> int128_opt;
+  static auto map(uint128_opt) -> uint128_opt;
+  static auto map(bool) -> bool;
+
+  template <int N>
+  static auto map(bitint<N>) -> conditional_t<N <= 64, long long, void>;
+  template <int N>
+  static auto map(ubitint<N>)
+      -> conditional_t<N <= 64, unsigned long long, void>;
+
+  template <typename T, FMT_ENABLE_IF(is_code_unit<T>::value)>
+  static auto map(T) -> conditional_t<
+      std::is_same<T, char>::value || std::is_same<T, Char>::value, Char, void>;
+
+  static auto map(float) -> float;
+  static auto map(double) -> double;
+  static auto map(long double) -> long double;
+
+  static auto map(Char*) -> const Char*;
+  static auto map(const Char*) -> const Char*;
+  template <typename T, typename C = char_t<T>,
+            FMT_ENABLE_IF(!std::is_pointer<T>::value)>
+  static auto map(const T&) -> conditional_t<std::is_same<C, Char>::value,
+                                             basic_string_view<C>, void>;
+
+  static auto map(void*) -> const void*;
+  static auto map(const void*) -> const void*;
+  static auto map(volatile void*) -> const void*;
+  static auto map(const volatile void*) -> const void*;
+  static auto map(nullptr_t) -> const void*;
+  template <typename T, FMT_ENABLE_IF(std::is_pointer<T>::value ||
+                                      std::is_member_pointer<T>::value)>
+  static auto map(const T&) -> void;
+
+  template <typename T, FMT_ENABLE_IF(use_format_as<T>::value)>
+  static auto map(const T& x) -> decltype(map(format_as(x)));
+  template <typename T, FMT_ENABLE_IF(use_format_as_member<T>::value)>
+  static auto map(const T& x) -> decltype(map(formatter<T>::format_as(x)));
+
+  template <typename T, FMT_ENABLE_IF(use_formatter<T>::value)>
+  static auto map(T&) -> conditional_t<has_formatter<T, Char>(), T&, void>;
+
+  template <typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
+  static auto map(const T& named_arg) -> decltype(map(named_arg.value));
+};
+
+// detail:: is used to workaround a bug in MSVC 2017.
+template <typename T, typename Char>
+using mapped_t = decltype(detail::type_mapper<Char>::map(std::declval<T&>()));
+
+// A type constant after applying type_mapper.
+template <typename T, typename Char = char>
+using mapped_type_constant = type_constant<mapped_t<T, Char>, Char>;
+
+template <typename T, typename Context,
+          type TYPE =
+              mapped_type_constant<T, typename Context::char_type>::value>
+using stored_type_constant = std::integral_constant<
+    type, Context::builtin_types || TYPE == type::int_type ? TYPE
+                                                           : type::custom_type>;
+// A parse context with extra data used only in compile-time checks.
+template <typename Char>
+class compile_parse_context : public parse_context<Char> {
+ private:
+  int num_args_;
+  const type* types_;
+  using base = parse_context<Char>;
+
+ public:
+  FMT_CONSTEXPR explicit compile_parse_context(basic_string_view<Char> fmt,
+                                               int num_args, const type* types,
+                                               int next_arg_id = 0)
+      : base(fmt, next_arg_id), num_args_(num_args), types_(types) {}
+
+  constexpr auto num_args() const -> int { return num_args_; }
+  constexpr auto arg_type(int id) const -> type { return types_[id]; }
+
+  FMT_CONSTEXPR auto next_arg_id() -> int {
+    int id = base::next_arg_id();
+    if (id >= num_args_) report_error("argument not found");
+    return id;
+  }
+
+  FMT_CONSTEXPR void check_arg_id(int id) {
+    base::check_arg_id(id);
+    if (id >= num_args_) report_error("argument not found");
+  }
+  using base::check_arg_id;
+
+  FMT_CONSTEXPR void check_dynamic_spec(int arg_id) {
+    ignore_unused(arg_id);
+    if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id]))
+      report_error("width/precision is not integer");
+  }
+};
+
+// An argument reference.
+template <typename Char> union arg_ref {
+  FMT_CONSTEXPR arg_ref(int idx = 0) : index(idx) {}
+  FMT_CONSTEXPR arg_ref(basic_string_view<Char> n) : name(n) {}
+
+  int index;
+  basic_string_view<Char> name;
+};
+
+// Format specifiers with width and precision resolved at formatting rather
+// than parsing time to allow reusing the same parsed specifiers with
+// different sets of arguments (precompilation of format strings).
+template <typename Char = char> struct dynamic_format_specs : format_specs {
+  arg_ref<Char> width_ref;
+  arg_ref<Char> precision_ref;
+};
+
+// Converts a character to ASCII. Returns '\0' on conversion failure.
+template <typename Char, FMT_ENABLE_IF(std::is_integral<Char>::value)>
+constexpr auto to_ascii(Char c) -> char {
+  return c <= 0xff ? static_cast<char>(c) : '\0';
+}
+
+// Returns the number of code units in a code point or 1 on error.
+template <typename Char>
+FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int {
+  if (const_check(sizeof(Char) != 1)) return 1;
+  auto c = static_cast<unsigned char>(*begin);
+  return static_cast<int>((0x3a55000000000000ull >> (2 * (c >> 3))) & 3) + 1;
+}
+
+// Parses the range [begin, end) as an unsigned integer. This function assumes
+// that the range is non-empty and the first character is a digit.
+template <typename Char>
+FMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end,
+                                         int error_value) noexcept -> int {
+  FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', "");
+  unsigned value = 0, prev = 0;
+  auto p = begin;
+  do {
+    prev = value;
+    value = value * 10 + unsigned(*p - '0');
+    ++p;
+  } while (p != end && '0' <= *p && *p <= '9');
+  auto num_digits = p - begin;
+  begin = p;
+  int digits10 = static_cast<int>(sizeof(int) * CHAR_BIT * 3 / 10);
+  if (num_digits <= digits10) return static_cast<int>(value);
+  // Check for overflow.
+  unsigned max = INT_MAX;
+  return num_digits == digits10 + 1 &&
+                 prev * 10ull + unsigned(p[-1] - '0') <= max
+             ? static_cast<int>(value)
+             : error_value;
+}
+
+FMT_CONSTEXPR inline auto parse_align(char c) -> align {
+  switch (c) {
+  case '<': return align::left;
+  case '>': return align::right;
+  case '^': return align::center;
+  }
+  return align::none;
+}
+
+template <typename Char> constexpr auto is_name_start(Char c) -> bool {
+  return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_';
+}
+
+template <typename Char, typename Handler>
+FMT_CONSTEXPR auto parse_arg_id(const Char* begin, const Char* end,
+                                Handler&& handler) -> const Char* {
+  Char c = *begin;
+  if (c >= '0' && c <= '9') {
+    int index = 0;
+    if (c != '0')
+      index = parse_nonnegative_int(begin, end, INT_MAX);
+    else
+      ++begin;
+    if (begin == end || (*begin != '}' && *begin != ':'))
+      report_error("invalid format string");
+    else
+      handler.on_index(index);
+    return begin;
+  }
+  if (FMT_OPTIMIZE_SIZE > 1 || !is_name_start(c)) {
+    report_error("invalid format string");
+    return begin;
+  }
+  auto it = begin;
+  do {
+    ++it;
+  } while (it != end && (is_name_start(*it) || ('0' <= *it && *it <= '9')));
+  handler.on_name({begin, to_unsigned(it - begin)});
+  return it;
+}
+
+template <typename Char> struct dynamic_spec_handler {
+  parse_context<Char>& ctx;
+  arg_ref<Char>& ref;
+  arg_id_kind& kind;
+
+  FMT_CONSTEXPR void on_index(int id) {
+    ref = id;
+    kind = arg_id_kind::index;
+    ctx.check_arg_id(id);
+    ctx.check_dynamic_spec(id);
+  }
+  FMT_CONSTEXPR void on_name(basic_string_view<Char> id) {
+    ref = id;
+    kind = arg_id_kind::name;
+    ctx.check_arg_id(id);
+  }
+};
+
+template <typename Char> struct parse_dynamic_spec_result {
+  const Char* end;
+  arg_id_kind kind;
+};
+
+// Parses integer | "{" [arg_id] "}".
+template <typename Char>
+FMT_CONSTEXPR auto parse_dynamic_spec(const Char* begin, const Char* end,
+                                      int& value, arg_ref<Char>& ref,
+                                      parse_context<Char>& ctx)
+    -> parse_dynamic_spec_result<Char> {
+  FMT_ASSERT(begin != end, "");
+  auto kind = arg_id_kind::none;
+  if ('0' <= *begin && *begin <= '9') {
+    int val = parse_nonnegative_int(begin, end, -1);
+    if (val == -1) report_error("number is too big");
+    value = val;
+  } else {
+    if (*begin == '{') {
+      ++begin;
+      if (begin != end) {
+        Char c = *begin;
+        if (c == '}' || c == ':') {
+          int id = ctx.next_arg_id();
+          ref = id;
+          kind = arg_id_kind::index;
+          ctx.check_dynamic_spec(id);
+        } else {
+          begin = parse_arg_id(begin, end,
+                               dynamic_spec_handler<Char>{ctx, ref, kind});
+        }
+      }
+      if (begin != end && *begin == '}') return {++begin, kind};
+    }
+    report_error("invalid format string");
+  }
+  return {begin, kind};
+}
+
+template <typename Char>
+FMT_CONSTEXPR auto parse_width(const Char* begin, const Char* end,
+                               format_specs& specs, arg_ref<Char>& width_ref,
+                               parse_context<Char>& ctx) -> const Char* {
+  auto result = parse_dynamic_spec(begin, end, specs.width, width_ref, ctx);
+  specs.set_dynamic_width(result.kind);
+  return result.end;
+}
+
+template <typename Char>
+FMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end,
+                                   format_specs& specs,
+                                   arg_ref<Char>& precision_ref,
+                                   parse_context<Char>& ctx) -> const Char* {
+  ++begin;
+  if (begin == end) {
+    report_error("invalid precision");
+    return begin;
+  }
+  auto result =
+      parse_dynamic_spec(begin, end, specs.precision, precision_ref, ctx);
+  specs.set_dynamic_precision(result.kind);
+  return result.end;
+}
+
+enum class state { start, align, sign, hash, zero, width, precision, locale };
+
+// Parses standard format specifiers.
+template <typename Char>
+FMT_CONSTEXPR auto parse_format_specs(const Char* begin, const Char* end,
+                                      dynamic_format_specs<Char>& specs,
+                                      parse_context<Char>& ctx, type arg_type)
+    -> const Char* {
+  auto c = '\0';
+  if (end - begin > 1) {
+    auto next = to_ascii(begin[1]);
+    c = parse_align(next) == align::none ? to_ascii(*begin) : '\0';
+  } else {
+    if (begin == end) return begin;
+    c = to_ascii(*begin);
+  }
+
+  struct {
+    state current_state = state::start;
+    FMT_CONSTEXPR void operator()(state s, bool valid = true) {
+      if (current_state >= s || !valid)
+        report_error("invalid format specifier");
+      current_state = s;
+    }
+  } enter_state;
+
+  using pres = presentation_type;
+  constexpr auto integral_set = sint_set | uint_set | bool_set | char_set;
+  struct {
+    const Char*& begin;
+    format_specs& specs;
+    type arg_type;
+
+    FMT_CONSTEXPR auto operator()(pres pres_type, int set) -> const Char* {
+      if (!in(arg_type, set)) report_error("invalid format specifier");
+      specs.set_type(pres_type);
+      return begin + 1;
+    }
+  } parse_presentation_type{begin, specs, arg_type};
+
+  for (;;) {
+    switch (c) {
+    case '<':
+    case '>':
+    case '^':
+      enter_state(state::align);
+      specs.set_align(parse_align(c));
+      ++begin;
+      break;
+    case '+':
+    case ' ':
+      specs.set_sign(c == ' ' ? sign::space : sign::plus);
+      FMT_FALLTHROUGH;
+    case '-':
+      enter_state(state::sign, in(arg_type, sint_set | float_set));
+      ++begin;
+      break;
+    case '#':
+      enter_state(state::hash, is_arithmetic_type(arg_type));
+      specs.set_alt();
+      ++begin;
+      break;
+    case '0':
+      enter_state(state::zero);
+      if (!is_arithmetic_type(arg_type))
+        report_error("format specifier requires numeric argument");
+      if (specs.align() == align::none) {
+        // Ignore 0 if align is specified for compatibility with std::format.
+        specs.set_align(align::numeric);
+        specs.set_fill('0');
+      }
+      ++begin;
+      break;
+      // clang-format off
+    case '1': case '2': case '3': case '4': case '5':
+    case '6': case '7': case '8': case '9': case '{':
+      // clang-format on
+      enter_state(state::width);
+      begin = parse_width(begin, end, specs, specs.width_ref, ctx);
+      break;
+    case '.':
+      enter_state(state::precision,
+                  in(arg_type, float_set | string_set | cstring_set));
+      begin = parse_precision(begin, end, specs, specs.precision_ref, ctx);
+      break;
+    case 'L':
+      enter_state(state::locale, is_arithmetic_type(arg_type));
+      specs.set_localized();
+      ++begin;
+      break;
+    case 'd': return parse_presentation_type(pres::dec, integral_set);
+    case 'X': specs.set_upper(); FMT_FALLTHROUGH;
+    case 'x': return parse_presentation_type(pres::hex, integral_set);
+    case 'o': return parse_presentation_type(pres::oct, integral_set);
+    case 'B': specs.set_upper(); FMT_FALLTHROUGH;
+    case 'b': return parse_presentation_type(pres::bin, integral_set);
+    case 'E': specs.set_upper(); FMT_FALLTHROUGH;
+    case 'e': return parse_presentation_type(pres::exp, float_set);
+    case 'F': specs.set_upper(); FMT_FALLTHROUGH;
+    case 'f': return parse_presentation_type(pres::fixed, float_set);
+    case 'G': specs.set_upper(); FMT_FALLTHROUGH;
+    case 'g': return parse_presentation_type(pres::general, float_set);
+    case 'A': specs.set_upper(); FMT_FALLTHROUGH;
+    case 'a': return parse_presentation_type(pres::hexfloat, float_set);
+    case 'c':
+      if (arg_type == type::bool_type) report_error("invalid format specifier");
+      return parse_presentation_type(pres::chr, integral_set);
+    case 's':
+      return parse_presentation_type(pres::string,
+                                     bool_set | string_set | cstring_set);
+    case 'p':
+      return parse_presentation_type(pres::pointer, pointer_set | cstring_set);
+    case '?':
+      return parse_presentation_type(pres::debug,
+                                     char_set | string_set | cstring_set);
+    case '}': return begin;
+    default:  {
+      if (*begin == '}') return begin;
+      // Parse fill and alignment.
+      auto fill_end = begin + code_point_length(begin);
+      if (end - fill_end <= 0) {
+        report_error("invalid format specifier");
+        return begin;
+      }
+      if (*begin == '{') {
+        report_error("invalid fill character '{'");
+        return begin;
+      }
+      auto alignment = parse_align(to_ascii(*fill_end));
+      enter_state(state::align, alignment != align::none);
+      specs.set_fill(
+          basic_string_view<Char>(begin, to_unsigned(fill_end - begin)));
+      specs.set_align(alignment);
+      begin = fill_end + 1;
+    }
+    }
+    if (begin == end) return begin;
+    c = to_ascii(*begin);
+  }
+}
+
+template <typename Char, typename Handler>
+FMT_CONSTEXPR FMT_INLINE auto parse_replacement_field(const Char* begin,
+                                                      const Char* end,
+                                                      Handler&& handler)
+    -> const Char* {
+  ++begin;
+  if (begin == end) {
+    handler.on_error("invalid format string");
+    return end;
+  }
+  int arg_id = 0;
+  switch (*begin) {
+  case '}':
+    handler.on_replacement_field(handler.on_arg_id(), begin);
+    return begin + 1;
+  case '{': handler.on_text(begin, begin + 1); return begin + 1;
+  case ':': arg_id = handler.on_arg_id(); break;
+  default:  {
+    struct id_adapter {
+      Handler& handler;
+      int arg_id;
+
+      FMT_CONSTEXPR void on_index(int id) { arg_id = handler.on_arg_id(id); }
+      FMT_CONSTEXPR void on_name(basic_string_view<Char> id) {
+        arg_id = handler.on_arg_id(id);
+      }
+    } adapter = {handler, 0};
+    begin = parse_arg_id(begin, end, adapter);
+    arg_id = adapter.arg_id;
+    Char c = begin != end ? *begin : Char();
+    if (c == '}') {
+      handler.on_replacement_field(arg_id, begin);
+      return begin + 1;
+    }
+    if (c != ':') {
+      handler.on_error("missing '}' in format string");
+      return end;
+    }
+    break;
+  }
+  }
+  begin = handler.on_format_specs(arg_id, begin + 1, end);
+  if (begin == end || *begin != '}')
+    return handler.on_error("unknown format specifier"), end;
+  return begin + 1;
+}
+
+template <typename Char, typename Handler>
+FMT_CONSTEXPR void parse_format_string(basic_string_view<Char> fmt,
+                                       Handler&& handler) {
+  auto begin = fmt.data(), end = begin + fmt.size();
+  auto p = begin;
+  while (p != end) {
+    auto c = *p++;
+    if (c == '{') {
+      handler.on_text(begin, p - 1);
+      begin = p = parse_replacement_field(p - 1, end, handler);
+    } else if (c == '}') {
+      if (p == end || *p != '}')
+        return handler.on_error("unmatched '}' in format string");
+      handler.on_text(begin, p);
+      begin = ++p;
+    }
+  }
+  handler.on_text(begin, end);
+}
+
+// Checks char specs and returns true iff the presentation type is char-like.
+FMT_CONSTEXPR inline auto check_char_specs(const format_specs& specs) -> bool {
+  auto type = specs.type();
+  if (type != presentation_type::none && type != presentation_type::chr &&
+      type != presentation_type::debug) {
+    return false;
+  }
+  if (specs.align() == align::numeric || specs.sign() != sign::none ||
+      specs.alt()) {
+    report_error("invalid format specifier for char");
+  }
+  return true;
+}
+
+// A base class for compile-time strings.
+struct compile_string {};
+
+template <typename T, typename Char>
+FMT_VISIBILITY("hidden")  // Suppress an ld warning on macOS (#3769).
+FMT_CONSTEXPR auto invoke_parse(parse_context<Char>& ctx) -> const Char* {
+  using mapped_type = remove_cvref_t<mapped_t<T, Char>>;
+  constexpr bool formattable =
+      std::is_constructible<formatter<mapped_type, Char>>::value;
+  if (!formattable) return ctx.begin();  // Error is reported in the value ctor.
+  using formatted_type = conditional_t<formattable, mapped_type, int>;
+  return formatter<formatted_type, Char>().parse(ctx);
+}
+
+template <typename... T> struct arg_pack {};
+
+template <typename Char, int NUM_ARGS, int NUM_NAMED_ARGS, bool DYNAMIC_NAMES>
+class format_string_checker {
+ private:
+  type types_[max_of<size_t>(1, NUM_ARGS)];
+  named_arg_info<Char> named_args_[max_of<size_t>(1, NUM_NAMED_ARGS)];
+  compile_parse_context<Char> context_;
+
+  using parse_func = auto (*)(parse_context<Char>&) -> const Char*;
+  parse_func parse_funcs_[max_of<size_t>(1, NUM_ARGS)];
+
+ public:
+  template <typename... T>
+  FMT_CONSTEXPR explicit format_string_checker(basic_string_view<Char> fmt,
+                                               arg_pack<T...>)
+      : types_{mapped_type_constant<T, Char>::value...},
+        named_args_{},
+        context_(fmt, NUM_ARGS, types_),
+        parse_funcs_{&invoke_parse<T, Char>...} {
+    int arg_index = 0, named_arg_index = 0;
+    FMT_APPLY_VARIADIC(
+        init_static_named_arg<T>(named_args_, arg_index, named_arg_index));
+    ignore_unused(arg_index, named_arg_index);
+  }
+
+  FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
+
+  FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); }
+  FMT_CONSTEXPR auto on_arg_id(int id) -> int {
+    context_.check_arg_id(id);
+    return id;
+  }
+  FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
+    for (int i = 0; i < NUM_NAMED_ARGS; ++i) {
+      if (named_args_[i].name == id) return named_args_[i].id;
+    }
+    if (!DYNAMIC_NAMES) on_error("argument not found");
+    return -1;
+  }
+
+  FMT_CONSTEXPR void on_replacement_field(int id, const Char* begin) {
+    on_format_specs(id, begin, begin);  // Call parse() on empty specs.
+  }
+
+  FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char* end)
+      -> const Char* {
+    context_.advance_to(begin);
+    if (id >= 0 && id < NUM_ARGS) return parse_funcs_[id](context_);
+
+    // If id is out of range, it means we do not know the type and cannot parse
+    // the format at compile time. Instead, skip over content until we finish
+    // the format spec, accounting for any nested replacements.
+    for (int bracket_count = 0;
+         begin != end && (bracket_count > 0 || *begin != '}'); ++begin) {
+      if (*begin == '{')
+        ++bracket_count;
+      else if (*begin == '}')
+        --bracket_count;
+    }
+    return begin;
+  }
+
+  FMT_NORETURN FMT_CONSTEXPR void on_error(const char* message) {
+    report_error(message);
+  }
+};
+
+/// A contiguous memory buffer with an optional growing ability. It is an
+/// internal class and shouldn't be used directly, only via `memory_buffer`.
+template <typename T> class buffer {
+ private:
+  T* ptr_;
+  size_t size_;
+  size_t capacity_;
+
+  using grow_fun = void (*)(buffer& buf, size_t capacity);
+  grow_fun grow_;
+
+ protected:
+  // Don't initialize ptr_ since it is not accessed to save a few cycles.
+  FMT_MSC_WARNING(suppress : 26495)
+  FMT_CONSTEXPR buffer(grow_fun grow, size_t sz) noexcept
+      : size_(sz), capacity_(sz), grow_(grow) {}
+
+  constexpr buffer(grow_fun grow, T* p = nullptr, size_t sz = 0,
+                   size_t cap = 0) noexcept
+      : ptr_(p), size_(sz), capacity_(cap), grow_(grow) {}
+
+  FMT_CONSTEXPR20 ~buffer() = default;
+  buffer(buffer&&) = default;
+
+  /// Sets the buffer data and capacity.
+  FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept {
+    ptr_ = buf_data;
+    capacity_ = buf_capacity;
+  }
+
+ public:
+  using value_type = T;
+  using const_reference = const T&;
+
+  buffer(const buffer&) = delete;
+  void operator=(const buffer&) = delete;
+
+  auto begin() noexcept -> T* { return ptr_; }
+  auto end() noexcept -> T* { return ptr_ + size_; }
+
+  auto begin() const noexcept -> const T* { return ptr_; }
+  auto end() const noexcept -> const T* { return ptr_ + size_; }
+
+  /// Returns the size of this buffer.
+  constexpr auto size() const noexcept -> size_t { return size_; }
+
+  /// Returns the capacity of this buffer.
+  constexpr auto capacity() const noexcept -> size_t { return capacity_; }
+
+  /// Returns a pointer to the buffer data (not null-terminated).
+  FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; }
+  FMT_CONSTEXPR auto data() const noexcept -> const T* { return ptr_; }
+
+  /// Clears this buffer.
+  FMT_CONSTEXPR void clear() { size_ = 0; }
+
+  // Tries resizing the buffer to contain `count` elements. If T is a POD type
+  // the new elements may not be initialized.
+  FMT_CONSTEXPR void try_resize(size_t count) {
+    try_reserve(count);
+    size_ = min_of(count, capacity_);
+  }
+
+  // Tries increasing the buffer capacity to `new_capacity`. It can increase the
+  // capacity by a smaller amount than requested but guarantees there is space
+  // for at least one additional element either by increasing the capacity or by
+  // flushing the buffer if it is full.
+  FMT_CONSTEXPR void try_reserve(size_t new_capacity) {
+    if (new_capacity > capacity_) grow_(*this, new_capacity);
+  }
+
+  FMT_CONSTEXPR void push_back(const T& value) {
+    try_reserve(size_ + 1);
+    ptr_[size_++] = value;
+  }
+
+  /// Appends data to the end of the buffer.
+  template <typename U>
+// Workaround for MSVC2019 to fix error C2893: Failed to specialize function
+// template 'void fmt::v11::detail::buffer<T>::append(const U *,const U *)'.
+#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1940
+  FMT_CONSTEXPR20
+#endif
+      void
+      append(const U* begin, const U* end) {
+    while (begin != end) {
+      auto count = to_unsigned(end - begin);
+      try_reserve(size_ + count);
+      auto free_cap = capacity_ - size_;
+      if (free_cap < count) count = free_cap;
+      // A loop is faster than memcpy on small sizes.
+      T* out = ptr_ + size_;
+      for (size_t i = 0; i < count; ++i) out[i] = begin[i];
+      size_ += count;
+      begin += count;
+    }
+  }
+
+  template <typename Idx> FMT_CONSTEXPR auto operator[](Idx index) -> T& {
+    return ptr_[index];
+  }
+  template <typename Idx>
+  FMT_CONSTEXPR auto operator[](Idx index) const -> const T& {
+    return ptr_[index];
+  }
+};
+
+struct buffer_traits {
+  constexpr explicit buffer_traits(size_t) {}
+  constexpr auto count() const -> size_t { return 0; }
+  constexpr auto limit(size_t size) const -> size_t { return size; }
+};
+
+class fixed_buffer_traits {
+ private:
+  size_t count_ = 0;
+  size_t limit_;
+
+ public:
+  constexpr explicit fixed_buffer_traits(size_t limit) : limit_(limit) {}
+  constexpr auto count() const -> size_t { return count_; }
+  FMT_CONSTEXPR auto limit(size_t size) -> size_t {
+    size_t n = limit_ > count_ ? limit_ - count_ : 0;
+    count_ += size;
+    return min_of(size, n);
+  }
+};
+
+// A buffer that writes to an output iterator when flushed.
+template <typename OutputIt, typename T, typename Traits = buffer_traits>
+class iterator_buffer : public Traits, public buffer<T> {
+ private:
+  OutputIt out_;
+  enum { buffer_size = 256 };
+  T data_[buffer_size];
+
+  static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {
+    if (buf.size() == buffer_size) static_cast<iterator_buffer&>(buf).flush();
+  }
+
+  void flush() {
+    auto size = this->size();
+    this->clear();
+    const T* begin = data_;
+    const T* end = begin + this->limit(size);
+    while (begin != end) *out_++ = *begin++;
+  }
+
+ public:
+  explicit iterator_buffer(OutputIt out, size_t n = buffer_size)
+      : Traits(n), buffer<T>(grow, data_, 0, buffer_size), out_(out) {}
+  iterator_buffer(iterator_buffer&& other) noexcept
+      : Traits(other),
+        buffer<T>(grow, data_, 0, buffer_size),
+        out_(other.out_) {}
+  ~iterator_buffer() {
+    // Don't crash if flush fails during unwinding.
+    FMT_TRY { flush(); }
+    FMT_CATCH(...) {}
+  }
+
+  auto out() -> OutputIt {
+    flush();
+    return out_;
+  }
+  auto count() const -> size_t { return Traits::count() + this->size(); }
+};
+
+template <typename T>
+class iterator_buffer<T*, T, fixed_buffer_traits> : public fixed_buffer_traits,
+                                                    public buffer<T> {
+ private:
+  T* out_;
+  enum { buffer_size = 256 };
+  T data_[buffer_size];
+
+  static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {
+    if (buf.size() == buf.capacity())
+      static_cast<iterator_buffer&>(buf).flush();
+  }
+
+  void flush() {
+    size_t n = this->limit(this->size());
+    if (this->data() == out_) {
+      out_ += n;
+      this->set(data_, buffer_size);
+    }
+    this->clear();
+  }
+
+ public:
+  explicit iterator_buffer(T* out, size_t n = buffer_size)
+      : fixed_buffer_traits(n), buffer<T>(grow, out, 0, n), out_(out) {}
+  iterator_buffer(iterator_buffer&& other) noexcept
+      : fixed_buffer_traits(other),
+        buffer<T>(static_cast<iterator_buffer&&>(other)),
+        out_(other.out_) {
+    if (this->data() != out_) {
+      this->set(data_, buffer_size);
+      this->clear();
+    }
+  }
+  ~iterator_buffer() { flush(); }
+
+  auto out() -> T* {
+    flush();
+    return out_;
+  }
+  auto count() const -> size_t {
+    return fixed_buffer_traits::count() + this->size();
+  }
+};
+
+template <typename T> class iterator_buffer<T*, T> : public buffer<T> {
+ public:
+  explicit iterator_buffer(T* out, size_t = 0)
+      : buffer<T>([](buffer<T>&, size_t) {}, out, 0, ~size_t()) {}
+
+  auto out() -> T* { return &*this->end(); }
+};
+
+template <typename Container>
+class container_buffer : public buffer<typename Container::value_type> {
+ private:
+  using value_type = typename Container::value_type;
+
+  static FMT_CONSTEXPR void grow(buffer<value_type>& buf, size_t capacity) {
+    auto& self = static_cast<container_buffer&>(buf);
+    self.container.resize(capacity);
+    self.set(&self.container[0], capacity);
+  }
+
+ public:
+  Container& container;
+
+  explicit container_buffer(Container& c)
+      : buffer<value_type>(grow, c.size()), container(c) {}
+};
+
+// A buffer that writes to a container with the contiguous storage.
+template <typename OutputIt>
+class iterator_buffer<
+    OutputIt,
+    enable_if_t<is_back_insert_iterator<OutputIt>::value &&
+                    is_contiguous<typename OutputIt::container_type>::value,
+                typename OutputIt::container_type::value_type>>
+    : public container_buffer<typename OutputIt::container_type> {
+ private:
+  using base = container_buffer<typename OutputIt::container_type>;
+
+ public:
+  explicit iterator_buffer(typename OutputIt::container_type& c) : base(c) {}
+  explicit iterator_buffer(OutputIt out, size_t = 0)
+      : base(get_container(out)) {}
+
+  auto out() -> OutputIt { return OutputIt(this->container); }
+};
+
+// A buffer that counts the number of code units written discarding the output.
+template <typename T = char> class counting_buffer : public buffer<T> {
+ private:
+  enum { buffer_size = 256 };
+  T data_[buffer_size];
+  size_t count_ = 0;
+
+  static FMT_CONSTEXPR void grow(buffer<T>& buf, size_t) {
+    if (buf.size() != buffer_size) return;
+    static_cast<counting_buffer&>(buf).count_ += buf.size();
+    buf.clear();
+  }
+
+ public:
+  FMT_CONSTEXPR counting_buffer() : buffer<T>(grow, data_, 0, buffer_size) {}
+
+  constexpr auto count() const noexcept -> size_t {
+    return count_ + this->size();
+  }
+};
+
+template <typename T>
+struct is_back_insert_iterator<basic_appender<T>> : std::true_type {};
+
+template <typename OutputIt, typename InputIt, typename = void>
+struct has_back_insert_iterator_container_append : std::false_type {};
+template <typename OutputIt, typename InputIt>
+struct has_back_insert_iterator_container_append<
+    OutputIt, InputIt,
+    void_t<decltype(get_container(std::declval<OutputIt>())
+                        .append(std::declval<InputIt>(),
+                                std::declval<InputIt>()))>> : std::true_type {};
+
+template <typename OutputIt, typename InputIt, typename = void>
+struct has_back_insert_iterator_container_insert_at_end : std::false_type {};
+
+template <typename OutputIt, typename InputIt>
+struct has_back_insert_iterator_container_insert_at_end<
+    OutputIt, InputIt,
+    void_t<decltype(get_container(std::declval<OutputIt>())
+                        .insert(get_container(std::declval<OutputIt>()).end(),
+                                std::declval<InputIt>(),
+                                std::declval<InputIt>()))>> : std::true_type {};
+
+// An optimized version of std::copy with the output value type (T).
+template <typename T, typename InputIt, typename OutputIt,
+          FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value&&
+                            has_back_insert_iterator_container_append<
+                                OutputIt, InputIt>::value)>
+FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out)
+    -> OutputIt {
+  get_container(out).append(begin, end);
+  return out;
+}
+
+template <typename T, typename InputIt, typename OutputIt,
+          FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value &&
+                        !has_back_insert_iterator_container_append<
+                            OutputIt, InputIt>::value &&
+                        has_back_insert_iterator_container_insert_at_end<
+                            OutputIt, InputIt>::value)>
+FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out)
+    -> OutputIt {
+  auto& c = get_container(out);
+  c.insert(c.end(), begin, end);
+  return out;
+}
+
+template <typename T, typename InputIt, typename OutputIt,
+          FMT_ENABLE_IF(!(is_back_insert_iterator<OutputIt>::value &&
+                          (has_back_insert_iterator_container_append<
+                               OutputIt, InputIt>::value ||
+                           has_back_insert_iterator_container_insert_at_end<
+                               OutputIt, InputIt>::value)))>
+FMT_CONSTEXPR auto copy(InputIt begin, InputIt end, OutputIt out) -> OutputIt {
+  while (begin != end) *out++ = static_cast<T>(*begin++);
+  return out;
+}
+
+template <typename T, typename V, typename OutputIt>
+FMT_CONSTEXPR auto copy(basic_string_view<V> s, OutputIt out) -> OutputIt {
+  return copy<T>(s.begin(), s.end(), out);
+}
+
+template <typename It, typename Enable = std::true_type>
+struct is_buffer_appender : std::false_type {};
+template <typename It>
+struct is_buffer_appender<
+    It, bool_constant<
+            is_back_insert_iterator<It>::value &&
+            std::is_base_of<buffer<typename It::container_type::value_type>,
+                            typename It::container_type>::value>>
+    : std::true_type {};
+
+// Maps an output iterator to a buffer.
+template <typename T, typename OutputIt,
+          FMT_ENABLE_IF(!is_buffer_appender<OutputIt>::value)>
+auto get_buffer(OutputIt out) -> iterator_buffer<OutputIt, T> {
+  return iterator_buffer<OutputIt, T>(out);
+}
+template <typename T, typename OutputIt,
+          FMT_ENABLE_IF(is_buffer_appender<OutputIt>::value)>
+auto get_buffer(OutputIt out) -> buffer<T>& {
+  return get_container(out);
+}
+
+template <typename Buf, typename OutputIt>
+auto get_iterator(Buf& buf, OutputIt) -> decltype(buf.out()) {
+  return buf.out();
+}
+template <typename T, typename OutputIt>
+auto get_iterator(buffer<T>&, OutputIt out) -> OutputIt {
+  return out;
+}
+
+// This type is intentionally undefined, only used for errors.
+template <typename T, typename Char> struct type_is_unformattable_for;
+
+template <typename Char> struct string_value {
+  const Char* data;
+  size_t size;
+  auto str() const -> basic_string_view<Char> { return {data, size}; }
+};
+
+template <typename Context> struct custom_value {
+  using char_type = typename Context::char_type;
+  void* value;
+  void (*format)(void* arg, parse_context<char_type>& parse_ctx, Context& ctx);
+};
+
+template <typename Char> struct named_arg_value {
+  const named_arg_info<Char>* data;
+  size_t size;
+};
+
+struct custom_tag {};
+
+#if !FMT_BUILTIN_TYPES
+#  define FMT_BUILTIN , monostate
+#else
+#  define FMT_BUILTIN
+#endif
+
+// A formatting argument value.
+template <typename Context> class value {
+ public:
+  using char_type = typename Context::char_type;
+
+  union {
+    monostate no_value;
+    int int_value;
+    unsigned uint_value;
+    long long long_long_value;
+    unsigned long long ulong_long_value;
+    int128_opt int128_value;
+    uint128_opt uint128_value;
+    bool bool_value;
+    char_type char_value;
+    float float_value;
+    double double_value;
+    long double long_double_value;
+    const void* pointer;
+    string_value<char_type> string;
+    custom_value<Context> custom;
+    named_arg_value<char_type> named_args;
+  };
+
+  constexpr FMT_INLINE value() : no_value() {}
+  constexpr FMT_INLINE value(signed char x) : int_value(x) {}
+  constexpr FMT_INLINE value(unsigned char x FMT_BUILTIN) : uint_value(x) {}
+  constexpr FMT_INLINE value(signed short x) : int_value(x) {}
+  constexpr FMT_INLINE value(unsigned short x FMT_BUILTIN) : uint_value(x) {}
+  constexpr FMT_INLINE value(int x) : int_value(x) {}
+  constexpr FMT_INLINE value(unsigned x FMT_BUILTIN) : uint_value(x) {}
+  FMT_CONSTEXPR FMT_INLINE value(long x FMT_BUILTIN) : value(long_type(x)) {}
+  FMT_CONSTEXPR FMT_INLINE value(unsigned long x FMT_BUILTIN)
+      : value(ulong_type(x)) {}
+  constexpr FMT_INLINE value(long long x FMT_BUILTIN) : long_long_value(x) {}
+  constexpr FMT_INLINE value(unsigned long long x FMT_BUILTIN)
+      : ulong_long_value(x) {}
+  FMT_INLINE value(int128_opt x FMT_BUILTIN) : int128_value(x) {}
+  FMT_INLINE value(uint128_opt x FMT_BUILTIN) : uint128_value(x) {}
+  constexpr FMT_INLINE value(bool x FMT_BUILTIN) : bool_value(x) {}
+
+  template <int N>
+  constexpr FMT_INLINE value(bitint<N> x FMT_BUILTIN) : long_long_value(x) {
+    static_assert(N <= 64, "unsupported _BitInt");
+  }
+  template <int N>
+  constexpr FMT_INLINE value(ubitint<N> x FMT_BUILTIN) : ulong_long_value(x) {
+    static_assert(N <= 64, "unsupported _BitInt");
+  }
+
+  template <typename T, FMT_ENABLE_IF(is_code_unit<T>::value)>
+  constexpr FMT_INLINE value(T x FMT_BUILTIN) : char_value(x) {
+    static_assert(
+        std::is_same<T, char>::value || std::is_same<T, char_type>::value,
+        "mixing character types is disallowed");
+  }
+
+  constexpr FMT_INLINE value(float x FMT_BUILTIN) : float_value(x) {}
+  constexpr FMT_INLINE value(double x FMT_BUILTIN) : double_value(x) {}
+  FMT_INLINE value(long double x FMT_BUILTIN) : long_double_value(x) {}
+
+  FMT_CONSTEXPR FMT_INLINE value(char_type* x FMT_BUILTIN) {
+    string.data = x;
+    if (is_constant_evaluated()) string.size = 0;
+  }
+  FMT_CONSTEXPR FMT_INLINE value(const char_type* x FMT_BUILTIN) {
+    string.data = x;
+    if (is_constant_evaluated()) string.size = 0;
+  }
+  template <typename T, typename C = char_t<T>,
+            FMT_ENABLE_IF(!std::is_pointer<T>::value)>
+  FMT_CONSTEXPR value(const T& x FMT_BUILTIN) {
+    static_assert(std::is_same<C, char_type>::value,
+                  "mixing character types is disallowed");
+    auto sv = to_string_view(x);
+    string.data = sv.data();
+    string.size = sv.size();
+  }
+  FMT_INLINE value(void* x FMT_BUILTIN) : pointer(x) {}
+  FMT_INLINE value(const void* x FMT_BUILTIN) : pointer(x) {}
+  FMT_INLINE value(volatile void* x FMT_BUILTIN)
+      : pointer(const_cast<const void*>(x)) {}
+  FMT_INLINE value(const volatile void* x FMT_BUILTIN)
+      : pointer(const_cast<const void*>(x)) {}
+  FMT_INLINE value(nullptr_t) : pointer(nullptr) {}
+
+  template <typename T, FMT_ENABLE_IF(std::is_pointer<T>::value ||
+                                      std::is_member_pointer<T>::value)>
+  value(const T&) {
+    // Formatting of arbitrary pointers is disallowed. If you want to format a
+    // pointer cast it to `void*` or `const void*`. In particular, this forbids
+    // formatting of `[const] volatile char*` printed as bool by iostreams.
+    static_assert(sizeof(T) == 0,
+                  "formatting of non-void pointers is disallowed");
+  }
+
+  template <typename T, FMT_ENABLE_IF(use_format_as<T>::value)>
+  value(const T& x) : value(format_as(x)) {}
+  template <typename T, FMT_ENABLE_IF(use_format_as_member<T>::value)>
+  value(const T& x) : value(formatter<T>::format_as(x)) {}
+
+  template <typename T, FMT_ENABLE_IF(is_named_arg<T>::value)>
+  value(const T& named_arg) : value(named_arg.value) {}
+
+  template <typename T,
+            FMT_ENABLE_IF(use_formatter<T>::value || !FMT_BUILTIN_TYPES)>
+  FMT_CONSTEXPR20 FMT_INLINE value(T& x) : value(x, custom_tag()) {}
+
+  FMT_ALWAYS_INLINE value(const named_arg_info<char_type>* args, size_t size)
+      : named_args{args, size} {}
+
+ private:
+  template <typename T, FMT_ENABLE_IF(has_formatter<T, char_type>())>
+  FMT_CONSTEXPR value(T& x, custom_tag) {
+    using value_type = remove_const_t<T>;
+    // T may overload operator& e.g. std::vector<bool>::reference in libc++.
+    if (!is_constant_evaluated()) {
+      custom.value =
+          const_cast<char*>(&reinterpret_cast<const volatile char&>(x));
+    } else {
+      custom.value = nullptr;
+#if defined(__cpp_if_constexpr)
+      if constexpr (std::is_same<decltype(&x), remove_reference_t<T>*>::value)
+        custom.value = const_cast<value_type*>(&x);
+#endif
+    }
+    custom.format = format_custom<value_type>;
+  }
+
+  template <typename T, FMT_ENABLE_IF(!has_formatter<T, char_type>())>
+  FMT_CONSTEXPR value(const T&, custom_tag) {
+    // Cannot format an argument; to make type T formattable provide a
+    // formatter<T> specialization: https://fmt.dev/latest/api.html#udt.
+    type_is_unformattable_for<T, char_type> _;
+  }
+
+  // Formats an argument of a custom type, such as a user-defined class.
+  template <typename T>
+  static void format_custom(void* arg, parse_context<char_type>& parse_ctx,
+                            Context& ctx) {
+    auto f = formatter<T, char_type>();
+    parse_ctx.advance_to(f.parse(parse_ctx));
+    using qualified_type =
+        conditional_t<has_formatter<const T, char_type>(), const T, T>;
+    // format must be const for compatibility with std::format and compilation.
+    const auto& cf = f;
+    ctx.advance_to(cf.format(*static_cast<qualified_type*>(arg), ctx));
+  }
+};
+
+enum { packed_arg_bits = 4 };
+// Maximum number of arguments with packed types.
+enum { max_packed_args = 62 / packed_arg_bits };
+enum : unsigned long long { is_unpacked_bit = 1ULL << 63 };
+enum : unsigned long long { has_named_args_bit = 1ULL << 62 };
+
+template <typename It, typename T, typename Enable = void>
+struct is_output_iterator : std::false_type {};
+
+template <> struct is_output_iterator<appender, char> : std::true_type {};
+
+template <typename It, typename T>
+struct is_output_iterator<
+    It, T,
+    enable_if_t<std::is_assignable<decltype(*std::declval<decay_t<It>&>()++),
+                                   T>::value>> : std::true_type {};
+
+template <typename> constexpr auto encode_types() -> unsigned long long {
+  return 0;
+}
+
+template <typename Context, typename First, typename... T>
+constexpr auto encode_types() -> unsigned long long {
+  return static_cast<unsigned>(stored_type_constant<First, Context>::value) |
+         (encode_types<Context, T...>() << packed_arg_bits);
+}
+
+template <typename Context, typename... T, size_t NUM_ARGS = sizeof...(T)>
+constexpr auto make_descriptor() -> unsigned long long {
+  return NUM_ARGS <= max_packed_args ? encode_types<Context, T...>()
+                                     : is_unpacked_bit | NUM_ARGS;
+}
+
+template <typename Context, int NUM_ARGS>
+using arg_t = conditional_t<NUM_ARGS <= max_packed_args, value<Context>,
+                            basic_format_arg<Context>>;
+
+template <typename Context, int NUM_ARGS, int NUM_NAMED_ARGS,
+          unsigned long long DESC>
+struct named_arg_store {
+  // args_[0].named_args points to named_args to avoid bloating format_args.
+  arg_t<Context, NUM_ARGS> args[1u + NUM_ARGS];
+  named_arg_info<typename Context::char_type>
+      named_args[static_cast<size_t>(NUM_NAMED_ARGS)];
+
+  template <typename... T>
+  FMT_CONSTEXPR FMT_ALWAYS_INLINE named_arg_store(T&... values)
+      : args{{named_args, NUM_NAMED_ARGS}, values...} {
+    int arg_index = 0, named_arg_index = 0;
+    FMT_APPLY_VARIADIC(
+        init_named_arg(named_args, arg_index, named_arg_index, values));
+  }
+
+  named_arg_store(named_arg_store&& rhs) {
+    args[0] = {named_args, NUM_NAMED_ARGS};
+    for (size_t i = 1; i < sizeof(args) / sizeof(*args); ++i)
+      args[i] = rhs.args[i];
+    for (size_t i = 0; i < NUM_NAMED_ARGS; ++i)
+      named_args[i] = rhs.named_args[i];
+  }
+
+  named_arg_store(const named_arg_store& rhs) = delete;
+  auto operator=(const named_arg_store& rhs) -> named_arg_store& = delete;
+  auto operator=(named_arg_store&& rhs) -> named_arg_store& = delete;
+  operator const arg_t<Context, NUM_ARGS>*() const { return args + 1; }
+};
+
+// An array of references to arguments. It can be implicitly converted to
+// `basic_format_args` for passing into type-erased formatting functions
+// such as `vformat`. It is a plain struct to reduce binary size in debug mode.
+template <typename Context, int NUM_ARGS, int NUM_NAMED_ARGS,
+          unsigned long long DESC>
+struct format_arg_store {
+  // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
+  using type =
+      conditional_t<NUM_NAMED_ARGS == 0,
+                    arg_t<Context, NUM_ARGS>[max_of<size_t>(1, NUM_ARGS)],
+                    named_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC>>;
+  type args;
+};
+
+// TYPE can be different from type_constant<T>, e.g. for __float128.
+template <typename T, typename Char, type TYPE> struct native_formatter {
+ private:
+  dynamic_format_specs<Char> specs_;
+
+ public:
+  using nonlocking = void;
+
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    if (ctx.begin() == ctx.end() || *ctx.begin() == '}') return ctx.begin();
+    auto end = parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, TYPE);
+    if (const_check(TYPE == type::char_type)) check_char_specs(specs_);
+    return end;
+  }
+
+  template <type U = TYPE,
+            FMT_ENABLE_IF(U == type::string_type || U == type::cstring_type ||
+                          U == type::char_type)>
+  FMT_CONSTEXPR void set_debug_format(bool set = true) {
+    specs_.set_type(set ? presentation_type::debug : presentation_type::none);
+  }
+
+  FMT_PRAGMA_CLANG(diagnostic ignored "-Wundefined-inline")
+  template <typename FormatContext>
+  FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const
+      -> decltype(ctx.out());
+};
+
+template <typename T, typename Enable = void>
+struct locking
+    : bool_constant<mapped_type_constant<T>::value == type::custom_type> {};
+template <typename T>
+struct locking<T, void_t<typename formatter<remove_cvref_t<T>>::nonlocking>>
+    : std::false_type {};
+
+template <typename T = int> FMT_CONSTEXPR inline auto is_locking() -> bool {
+  return locking<T>::value;
+}
+template <typename T1, typename T2, typename... Tail>
+FMT_CONSTEXPR inline auto is_locking() -> bool {
+  return locking<T1>::value || is_locking<T2, Tail...>();
+}
+
+FMT_API void vformat_to(buffer<char>& buf, string_view fmt, format_args args,
+                        locale_ref loc = {});
+
+#if FMT_WIN32
+FMT_API void vprint_mojibake(FILE*, string_view, format_args, bool);
+#else  // format_args is passed by reference since it is defined later.
+inline void vprint_mojibake(FILE*, string_view, const format_args&, bool) {}
+#endif
+}  // namespace detail
+
+// The main public API.
+
+template <typename Char>
+FMT_CONSTEXPR void parse_context<Char>::do_check_arg_id(int arg_id) {
+  // Argument id is only checked at compile time during parsing because
+  // formatting has its own validation.
+  if (detail::is_constant_evaluated() && use_constexpr_cast) {
+    auto ctx = static_cast<detail::compile_parse_context<Char>*>(this);
+    if (arg_id >= ctx->num_args()) report_error("argument not found");
+  }
+}
+
+template <typename Char>
+FMT_CONSTEXPR void parse_context<Char>::check_dynamic_spec(int arg_id) {
+  using detail::compile_parse_context;
+  if (detail::is_constant_evaluated() && use_constexpr_cast)
+    static_cast<compile_parse_context<Char>*>(this)->check_dynamic_spec(arg_id);
+}
+
+FMT_BEGIN_EXPORT
+
+// An output iterator that appends to a buffer. It is used instead of
+// back_insert_iterator to reduce symbol sizes and avoid <iterator> dependency.
+template <typename T> class basic_appender {
+ protected:
+  detail::buffer<T>* container;
+
+ public:
+  using container_type = detail::buffer<T>;
+
+  FMT_CONSTEXPR basic_appender(detail::buffer<T>& buf) : container(&buf) {}
+
+  FMT_CONSTEXPR20 auto operator=(T c) -> basic_appender& {
+    container->push_back(c);
+    return *this;
+  }
+  FMT_CONSTEXPR20 auto operator*() -> basic_appender& { return *this; }
+  FMT_CONSTEXPR20 auto operator++() -> basic_appender& { return *this; }
+  FMT_CONSTEXPR20 auto operator++(int) -> basic_appender { return *this; }
+};
+
+// A formatting argument. Context is a template parameter for the compiled API
+// where output can be unbuffered.
+template <typename Context> class basic_format_arg {
+ private:
+  detail::value<Context> value_;
+  detail::type type_;
+
+  friend class basic_format_args<Context>;
+
+  using char_type = typename Context::char_type;
+
+ public:
+  class handle {
+   private:
+    detail::custom_value<Context> custom_;
+
+   public:
+    explicit handle(detail::custom_value<Context> custom) : custom_(custom) {}
+
+    void format(parse_context<char_type>& parse_ctx, Context& ctx) const {
+      custom_.format(custom_.value, parse_ctx, ctx);
+    }
+  };
+
+  constexpr basic_format_arg() : type_(detail::type::none_type) {}
+  basic_format_arg(const detail::named_arg_info<char_type>* args, size_t size)
+      : value_(args, size) {}
+  template <typename T>
+  basic_format_arg(T&& val)
+      : value_(val), type_(detail::stored_type_constant<T, Context>::value) {}
+
+  constexpr explicit operator bool() const noexcept {
+    return type_ != detail::type::none_type;
+  }
+  auto type() const -> detail::type { return type_; }
+
+  /**
+   * Visits an argument dispatching to the appropriate visit method based on
+   * the argument type. For example, if the argument type is `double` then
+   * `vis(value)` will be called with the value of type `double`.
+   */
+  template <typename Visitor>
+  FMT_CONSTEXPR FMT_INLINE auto visit(Visitor&& vis) const -> decltype(vis(0)) {
+    using detail::map;
+    switch (type_) {
+    case detail::type::none_type:        break;
+    case detail::type::int_type:         return vis(value_.int_value);
+    case detail::type::uint_type:        return vis(value_.uint_value);
+    case detail::type::long_long_type:   return vis(value_.long_long_value);
+    case detail::type::ulong_long_type:  return vis(value_.ulong_long_value);
+    case detail::type::int128_type:      return vis(map(value_.int128_value));
+    case detail::type::uint128_type:     return vis(map(value_.uint128_value));
+    case detail::type::bool_type:        return vis(value_.bool_value);
+    case detail::type::char_type:        return vis(value_.char_value);
+    case detail::type::float_type:       return vis(value_.float_value);
+    case detail::type::double_type:      return vis(value_.double_value);
+    case detail::type::long_double_type: return vis(value_.long_double_value);
+    case detail::type::cstring_type:     return vis(value_.string.data);
+    case detail::type::string_type:      return vis(value_.string.str());
+    case detail::type::pointer_type:     return vis(value_.pointer);
+    case detail::type::custom_type:      return vis(handle(value_.custom));
+    }
+    return vis(monostate());
+  }
+
+  auto format_custom(const char_type* parse_begin,
+                     parse_context<char_type>& parse_ctx, Context& ctx)
+      -> bool {
+    if (type_ != detail::type::custom_type) return false;
+    parse_ctx.advance_to(parse_begin);
+    value_.custom.format(value_.custom.value, parse_ctx, ctx);
+    return true;
+  }
+};
+
+/**
+ * A view of a collection of formatting arguments. To avoid lifetime issues it
+ * should only be used as a parameter type in type-erased functions such as
+ * `vformat`:
+ *
+ *     void vlog(fmt::string_view fmt, fmt::format_args args);  // OK
+ *     fmt::format_args args = fmt::make_format_args();  // Dangling reference
+ */
+template <typename Context> class basic_format_args {
+ private:
+  // A descriptor that contains information about formatting arguments.
+  // If the number of arguments is less or equal to max_packed_args then
+  // argument types are passed in the descriptor. This reduces binary code size
+  // per formatting function call.
+  unsigned long long desc_;
+  union {
+    // If is_packed() returns true then argument values are stored in values_;
+    // otherwise they are stored in args_. This is done to improve cache
+    // locality and reduce compiled code size since storing larger objects
+    // may require more code (at least on x86-64) even if the same amount of
+    // data is actually copied to stack. It saves ~10% on the bloat test.
+    const detail::value<Context>* values_;
+    const basic_format_arg<Context>* args_;
+  };
+
+  constexpr auto is_packed() const -> bool {
+    return (desc_ & detail::is_unpacked_bit) == 0;
+  }
+  constexpr auto has_named_args() const -> bool {
+    return (desc_ & detail::has_named_args_bit) != 0;
+  }
+
+  FMT_CONSTEXPR auto type(int index) const -> detail::type {
+    int shift = index * detail::packed_arg_bits;
+    unsigned mask = (1 << detail::packed_arg_bits) - 1;
+    return static_cast<detail::type>((desc_ >> shift) & mask);
+  }
+
+  template <int NUM_ARGS, int NUM_NAMED_ARGS, unsigned long long DESC>
+  using store =
+      detail::format_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC>;
+
+ public:
+  using format_arg = basic_format_arg<Context>;
+
+  constexpr basic_format_args() : desc_(0), args_(nullptr) {}
+
+  /// Constructs a `basic_format_args` object from `format_arg_store`.
+  template <int NUM_ARGS, int NUM_NAMED_ARGS, unsigned long long DESC,
+            FMT_ENABLE_IF(NUM_ARGS <= detail::max_packed_args)>
+  constexpr FMT_ALWAYS_INLINE basic_format_args(
+      const store<NUM_ARGS, NUM_NAMED_ARGS, DESC>& s)
+      : desc_(DESC | (NUM_NAMED_ARGS != 0 ? +detail::has_named_args_bit : 0)),
+        values_(s.args) {}
+
+  template <int NUM_ARGS, int NUM_NAMED_ARGS, unsigned long long DESC,
+            FMT_ENABLE_IF(NUM_ARGS > detail::max_packed_args)>
+  constexpr basic_format_args(const store<NUM_ARGS, NUM_NAMED_ARGS, DESC>& s)
+      : desc_(DESC | (NUM_NAMED_ARGS != 0 ? +detail::has_named_args_bit : 0)),
+        args_(s.args) {}
+
+  /// Constructs a `basic_format_args` object from a dynamic list of arguments.
+  constexpr basic_format_args(const format_arg* args, int count,
+                              bool has_named = false)
+      : desc_(detail::is_unpacked_bit | detail::to_unsigned(count) |
+              (has_named ? +detail::has_named_args_bit : 0)),
+        args_(args) {}
+
+  /// Returns the argument with the specified id.
+  FMT_CONSTEXPR auto get(int id) const -> format_arg {
+    auto arg = format_arg();
+    if (!is_packed()) {
+      if (id < max_size()) arg = args_[id];
+      return arg;
+    }
+    if (static_cast<unsigned>(id) >= detail::max_packed_args) return arg;
+    arg.type_ = type(id);
+    if (arg.type_ != detail::type::none_type) arg.value_ = values_[id];
+    return arg;
+  }
+
+  template <typename Char>
+  auto get(basic_string_view<Char> name) const -> format_arg {
+    int id = get_id(name);
+    return id >= 0 ? get(id) : format_arg();
+  }
+
+  template <typename Char>
+  FMT_CONSTEXPR auto get_id(basic_string_view<Char> name) const -> int {
+    if (!has_named_args()) return -1;
+    const auto& named_args =
+        (is_packed() ? values_[-1] : args_[-1].value_).named_args;
+    for (size_t i = 0; i < named_args.size; ++i) {
+      if (named_args.data[i].name == name) return named_args.data[i].id;
+    }
+    return -1;
+  }
+
+  auto max_size() const -> int {
+    unsigned long long max_packed = detail::max_packed_args;
+    return static_cast<int>(is_packed() ? max_packed
+                                        : desc_ & ~detail::is_unpacked_bit);
+  }
+};
+
+// A formatting context.
+class context {
+ private:
+  appender out_;
+  format_args args_;
+  FMT_NO_UNIQUE_ADDRESS locale_ref loc_;
+
+ public:
+  using char_type = char;  ///< The character type for the output.
+  using iterator = appender;
+  using format_arg = basic_format_arg<context>;
+  enum { builtin_types = FMT_BUILTIN_TYPES };
+
+  /// Constructs a `context` object. References to the arguments are stored
+  /// in the object so make sure they have appropriate lifetimes.
+  FMT_CONSTEXPR context(iterator out, format_args args, locale_ref loc = {})
+      : out_(out), args_(args), loc_(loc) {}
+  context(context&&) = default;
+  context(const context&) = delete;
+  void operator=(const context&) = delete;
+
+  FMT_CONSTEXPR auto arg(int id) const -> format_arg { return args_.get(id); }
+  inline auto arg(string_view name) const -> format_arg {
+    return args_.get(name);
+  }
+  FMT_CONSTEXPR auto arg_id(string_view name) const -> int {
+    return args_.get_id(name);
+  }
+  auto args() const -> const format_args& { return args_; }
+
+  // Returns an iterator to the beginning of the output range.
+  FMT_CONSTEXPR auto out() const -> iterator { return out_; }
+
+  // Advances the begin iterator to `it`.
+  FMT_CONSTEXPR void advance_to(iterator) {}
+
+  FMT_CONSTEXPR auto locale() const -> locale_ref { return loc_; }
+};
+
+template <typename Char = char> struct runtime_format_string {
+  basic_string_view<Char> str;
+};
+
+/**
+ * Creates a runtime format string.
+ *
+ * **Example**:
+ *
+ *     // Check format string at runtime instead of compile-time.
+ *     fmt::print(fmt::runtime("{:d}"), "I am not a number");
+ */
+inline auto runtime(string_view s) -> runtime_format_string<> { return {{s}}; }
+
+/// A compile-time format string. Use `format_string` in the public API to
+/// prevent type deduction.
+template <typename... T> struct fstring {
+ private:
+  static constexpr int num_static_named_args =
+      detail::count_static_named_args<T...>();
+
+  using checker = detail::format_string_checker<
+      char, static_cast<int>(sizeof...(T)), num_static_named_args,
+      num_static_named_args != detail::count_named_args<T...>()>;
+
+  using arg_pack = detail::arg_pack<T...>;
+
+ public:
+  string_view str;
+  using t = fstring;
+
+  // Reports a compile-time error if S is not a valid format string for T.
+  template <size_t N>
+  FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const char (&s)[N]) : str(s, N - 1) {
+    using namespace detail;
+    static_assert(count<(is_view<remove_cvref_t<T>>::value &&
+                         std::is_reference<T>::value)...>() == 0,
+                  "passing views as lvalues is disallowed");
+    if (FMT_USE_CONSTEVAL) parse_format_string<char>(s, checker(s, arg_pack()));
+#ifdef FMT_ENFORCE_COMPILE_STRING
+    static_assert(
+        FMT_USE_CONSTEVAL && sizeof(s) != 0,
+        "FMT_ENFORCE_COMPILE_STRING requires format strings to use FMT_STRING");
+#endif
+  }
+  template <typename S,
+            FMT_ENABLE_IF(std::is_convertible<const S&, string_view>::value)>
+  FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const S& s) : str(s) {
+    auto sv = string_view(str);
+    if (FMT_USE_CONSTEVAL)
+      detail::parse_format_string<char>(sv, checker(sv, arg_pack()));
+#ifdef FMT_ENFORCE_COMPILE_STRING
+    static_assert(
+        FMT_USE_CONSTEVAL && sizeof(s) != 0,
+        "FMT_ENFORCE_COMPILE_STRING requires format strings to use FMT_STRING");
+#endif
+  }
+  template <typename S,
+            FMT_ENABLE_IF(std::is_base_of<detail::compile_string, S>::value&&
+                              std::is_same<typename S::char_type, char>::value)>
+  FMT_ALWAYS_INLINE fstring(const S&) : str(S()) {
+    FMT_CONSTEXPR auto sv = string_view(S());
+    FMT_CONSTEXPR int unused =
+        (parse_format_string(sv, checker(sv, arg_pack())), 0);
+    detail::ignore_unused(unused);
+  }
+  fstring(runtime_format_string<> fmt) : str(fmt.str) {}
+
+  // Returning by reference generates better code in debug mode.
+  FMT_ALWAYS_INLINE operator const string_view&() const { return str; }
+  auto get() const -> string_view { return str; }
+};
+
+template <typename... T> using format_string = typename fstring<T...>::t;
+
+template <typename T, typename Char = char>
+using is_formattable = bool_constant<!std::is_same<
+    detail::mapped_t<conditional_t<std::is_void<T>::value, int*, T>, Char>,
+    void>::value>;
+#ifdef __cpp_concepts
+template <typename T, typename Char = char>
+concept formattable = is_formattable<remove_reference_t<T>, Char>::value;
+#endif
+
+// A formatter specialization for natively supported types.
+template <typename T, typename Char>
+struct formatter<T, Char,
+                 enable_if_t<detail::type_constant<T, Char>::value !=
+                             detail::type::custom_type>>
+    : detail::native_formatter<T, Char, detail::type_constant<T, Char>::value> {
+};
+
+/**
+ * Constructs an object that stores references to arguments and can be
+ * implicitly converted to `format_args`. `Context` can be omitted in which case
+ * it defaults to `context`. See `arg` for lifetime considerations.
+ */
+// Take arguments by lvalue references to avoid some lifetime issues, e.g.
+//   auto args = make_format_args(std::string());
+template <typename Context = context, typename... T,
+          int NUM_ARGS = sizeof...(T),
+          int NUM_NAMED_ARGS = detail::count_named_args<T...>(),
+          unsigned long long DESC = detail::make_descriptor<Context, T...>()>
+constexpr FMT_ALWAYS_INLINE auto make_format_args(T&... args)
+    -> detail::format_arg_store<Context, NUM_ARGS, NUM_NAMED_ARGS, DESC> {
+  // Suppress warnings for pathological types convertible to detail::value.
+  FMT_PRAGMA_GCC(diagnostic ignored "-Wconversion")
+  return {{args...}};
+}
+
+template <typename... T>
+using vargs =
+    detail::format_arg_store<context, sizeof...(T),
+                             detail::count_named_args<T...>(),
+                             detail::make_descriptor<context, T...>()>;
+
+/**
+ * Returns a named argument to be used in a formatting function.
+ * It should only be used in a call to a formatting function.
+ *
+ * **Example**:
+ *
+ *     fmt::print("The answer is {answer}.", fmt::arg("answer", 42));
+ */
+template <typename Char, typename T>
+inline auto arg(const Char* name, const T& arg) -> detail::named_arg<Char, T> {
+  return {name, arg};
+}
+
+/// Formats a string and writes the output to `out`.
+template <typename OutputIt,
+          FMT_ENABLE_IF(detail::is_output_iterator<remove_cvref_t<OutputIt>,
+                                                   char>::value)>
+auto vformat_to(OutputIt&& out, string_view fmt, format_args args)
+    -> remove_cvref_t<OutputIt> {
+  auto&& buf = detail::get_buffer<char>(out);
+  detail::vformat_to(buf, fmt, args, {});
+  return detail::get_iterator(buf, out);
+}
+
+/**
+ * Formats `args` according to specifications in `fmt`, writes the result to
+ * the output iterator `out` and returns the iterator past the end of the output
+ * range. `format_to` does not append a terminating null character.
+ *
+ * **Example**:
+ *
+ *     auto out = std::vector<char>();
+ *     fmt::format_to(std::back_inserter(out), "{}", 42);
+ */
+template <typename OutputIt, typename... T,
+          FMT_ENABLE_IF(detail::is_output_iterator<remove_cvref_t<OutputIt>,
+                                                   char>::value)>
+FMT_INLINE auto format_to(OutputIt&& out, format_string<T...> fmt, T&&... args)
+    -> remove_cvref_t<OutputIt> {
+  return vformat_to(out, fmt.str, vargs<T...>{{args...}});
+}
+
+template <typename OutputIt> struct format_to_n_result {
+  /// Iterator past the end of the output range.
+  OutputIt out;
+  /// Total (not truncated) output size.
+  size_t size;
+};
+
+template <typename OutputIt, typename... T,
+          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
+auto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args)
+    -> format_to_n_result<OutputIt> {
+  using traits = detail::fixed_buffer_traits;
+  auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n);
+  detail::vformat_to(buf, fmt, args, {});
+  return {buf.out(), buf.count()};
+}
+
+/**
+ * Formats `args` according to specifications in `fmt`, writes up to `n`
+ * characters of the result to the output iterator `out` and returns the total
+ * (not truncated) output size and the iterator past the end of the output
+ * range. `format_to_n` does not append a terminating null character.
+ */
+template <typename OutputIt, typename... T,
+          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
+FMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string<T...> fmt,
+                            T&&... args) -> format_to_n_result<OutputIt> {
+  return vformat_to_n(out, n, fmt.str, vargs<T...>{{args...}});
+}
+
+struct format_to_result {
+  /// Pointer to just after the last successful write in the array.
+  char* out;
+  /// Specifies if the output was truncated.
+  bool truncated;
+
+  FMT_CONSTEXPR operator char*() const {
+    // Report truncation to prevent silent data loss.
+    if (truncated) report_error("output is truncated");
+    return out;
+  }
+};
+
+template <size_t N>
+auto vformat_to(char (&out)[N], string_view fmt, format_args args)
+    -> format_to_result {
+  auto result = vformat_to_n(out, N, fmt, args);
+  return {result.out, result.size > N};
+}
+
+template <size_t N, typename... T>
+FMT_INLINE auto format_to(char (&out)[N], format_string<T...> fmt, T&&... args)
+    -> format_to_result {
+  auto result = vformat_to_n(out, N, fmt.str, vargs<T...>{{args...}});
+  return {result.out, result.size > N};
+}
+
+/// Returns the number of chars in the output of `format(fmt, args...)`.
+template <typename... T>
+FMT_NODISCARD FMT_INLINE auto formatted_size(format_string<T...> fmt,
+                                             T&&... args) -> size_t {
+  auto buf = detail::counting_buffer<>();
+  detail::vformat_to(buf, fmt.str, vargs<T...>{{args...}}, {});
+  return buf.count();
+}
+
+FMT_API void vprint(string_view fmt, format_args args);
+FMT_API void vprint(FILE* f, string_view fmt, format_args args);
+FMT_API void vprintln(FILE* f, string_view fmt, format_args args);
+FMT_API void vprint_buffered(FILE* f, string_view fmt, format_args args);
+
+/**
+ * Formats `args` according to specifications in `fmt` and writes the output
+ * to `stdout`.
+ *
+ * **Example**:
+ *
+ *     fmt::print("The answer is {}.", 42);
+ */
+template <typename... T>
+FMT_INLINE void print(format_string<T...> fmt, T&&... args) {
+  vargs<T...> va = {{args...}};
+  if (detail::const_check(!detail::use_utf8))
+    return detail::vprint_mojibake(stdout, fmt.str, va, false);
+  return detail::is_locking<T...>() ? vprint_buffered(stdout, fmt.str, va)
+                                    : vprint(fmt.str, va);
+}
+
+/**
+ * Formats `args` according to specifications in `fmt` and writes the
+ * output to the file `f`.
+ *
+ * **Example**:
+ *
+ *     fmt::print(stderr, "Don't {}!", "panic");
+ */
+template <typename... T>
+FMT_INLINE void print(FILE* f, format_string<T...> fmt, T&&... args) {
+  vargs<T...> va = {{args...}};
+  if (detail::const_check(!detail::use_utf8))
+    return detail::vprint_mojibake(f, fmt.str, va, false);
+  return detail::is_locking<T...>() ? vprint_buffered(f, fmt.str, va)
+                                    : vprint(f, fmt.str, va);
+}
+
+/// Formats `args` according to specifications in `fmt` and writes the output
+/// to the file `f` followed by a newline.
+template <typename... T>
+FMT_INLINE void println(FILE* f, format_string<T...> fmt, T&&... args) {
+  vargs<T...> va = {{args...}};
+  return detail::const_check(detail::use_utf8)
+             ? vprintln(f, fmt.str, va)
+             : detail::vprint_mojibake(f, fmt.str, va, true);
+}
+
+/// Formats `args` according to specifications in `fmt` and writes the output
+/// to `stdout` followed by a newline.
+template <typename... T>
+FMT_INLINE void println(format_string<T...> fmt, T&&... args) {
+  return fmt::println(stdout, fmt, static_cast<T&&>(args)...);
+}
+
+FMT_PRAGMA_CLANG(diagnostic pop)
+FMT_PRAGMA_GCC(pop_options)
+FMT_END_EXPORT
+FMT_END_NAMESPACE
+
+#ifdef FMT_HEADER_ONLY
+#  include "format.h"
+#endif
+#endif  // FMT_BASE_H_

+ 2241 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/chrono.h

@@ -0,0 +1,2241 @@
+// Formatting library for C++ - chrono support
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_CHRONO_H_
+#define FMT_CHRONO_H_
+
+#ifndef FMT_MODULE
+#  include <algorithm>
+#  include <chrono>
+#  include <cmath>    // std::isfinite
+#  include <cstring>  // std::memcpy
+#  include <ctime>
+#  include <iterator>
+#  include <locale>
+#  include <ostream>
+#  include <type_traits>
+#endif
+
+#include "format.h"
+
+FMT_BEGIN_NAMESPACE
+
+// Enable safe chrono durations, unless explicitly disabled.
+#ifndef FMT_SAFE_DURATION_CAST
+#  define FMT_SAFE_DURATION_CAST 1
+#endif
+#if FMT_SAFE_DURATION_CAST
+
+// For conversion between std::chrono::durations without undefined
+// behaviour or erroneous results.
+// This is a stripped down version of duration_cast, for inclusion in fmt.
+// See https://github.com/pauldreik/safe_duration_cast
+//
+// Copyright Paul Dreik 2019
+namespace safe_duration_cast {
+
+// DEPRECATED!
+template <typename To, typename From,
+          FMT_ENABLE_IF(!std::is_same<From, To>::value &&
+                        std::numeric_limits<From>::is_signed ==
+                            std::numeric_limits<To>::is_signed)>
+FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)
+    -> To {
+  ec = 0;
+  using F = std::numeric_limits<From>;
+  using T = std::numeric_limits<To>;
+  static_assert(F::is_integer, "From must be integral");
+  static_assert(T::is_integer, "To must be integral");
+
+  // A and B are both signed, or both unsigned.
+  if (detail::const_check(F::digits <= T::digits)) {
+    // From fits in To without any problem.
+  } else {
+    // From does not always fit in To, resort to a dynamic check.
+    if (from < (T::min)() || from > (T::max)()) {
+      // outside range.
+      ec = 1;
+      return {};
+    }
+  }
+  return static_cast<To>(from);
+}
+
+/// Converts From to To, without loss. If the dynamic value of from
+/// can't be converted to To without loss, ec is set.
+template <typename To, typename From,
+          FMT_ENABLE_IF(!std::is_same<From, To>::value &&
+                        std::numeric_limits<From>::is_signed !=
+                            std::numeric_limits<To>::is_signed)>
+FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)
+    -> To {
+  ec = 0;
+  using F = std::numeric_limits<From>;
+  using T = std::numeric_limits<To>;
+  static_assert(F::is_integer, "From must be integral");
+  static_assert(T::is_integer, "To must be integral");
+
+  if (detail::const_check(F::is_signed && !T::is_signed)) {
+    // From may be negative, not allowed!
+    if (fmt::detail::is_negative(from)) {
+      ec = 1;
+      return {};
+    }
+    // From is positive. Can it always fit in To?
+    if (detail::const_check(F::digits > T::digits) &&
+        from > static_cast<From>(detail::max_value<To>())) {
+      ec = 1;
+      return {};
+    }
+  }
+
+  if (detail::const_check(!F::is_signed && T::is_signed &&
+                          F::digits >= T::digits) &&
+      from > static_cast<From>(detail::max_value<To>())) {
+    ec = 1;
+    return {};
+  }
+  return static_cast<To>(from);  // Lossless conversion.
+}
+
+template <typename To, typename From,
+          FMT_ENABLE_IF(std::is_same<From, To>::value)>
+FMT_CONSTEXPR auto lossless_integral_conversion(const From from, int& ec)
+    -> To {
+  ec = 0;
+  return from;
+}  // function
+
+// clang-format off
+/**
+ * converts From to To if possible, otherwise ec is set.
+ *
+ * input                            |    output
+ * ---------------------------------|---------------
+ * NaN                              | NaN
+ * Inf                              | Inf
+ * normal, fits in output           | converted (possibly lossy)
+ * normal, does not fit in output   | ec is set
+ * subnormal                        | best effort
+ * -Inf                             | -Inf
+ */
+// clang-format on
+template <typename To, typename From,
+          FMT_ENABLE_IF(!std::is_same<From, To>::value)>
+FMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To {
+  ec = 0;
+  using T = std::numeric_limits<To>;
+  static_assert(std::is_floating_point<From>::value, "From must be floating");
+  static_assert(std::is_floating_point<To>::value, "To must be floating");
+
+  // catch the only happy case
+  if (std::isfinite(from)) {
+    if (from >= T::lowest() && from <= (T::max)()) {
+      return static_cast<To>(from);
+    }
+    // not within range.
+    ec = 1;
+    return {};
+  }
+
+  // nan and inf will be preserved
+  return static_cast<To>(from);
+}  // function
+
+template <typename To, typename From,
+          FMT_ENABLE_IF(std::is_same<From, To>::value)>
+FMT_CONSTEXPR auto safe_float_conversion(const From from, int& ec) -> To {
+  ec = 0;
+  static_assert(std::is_floating_point<From>::value, "From must be floating");
+  return from;
+}
+
+/// Safe duration_cast between floating point durations
+template <typename To, typename FromRep, typename FromPeriod,
+          FMT_ENABLE_IF(std::is_floating_point<FromRep>::value),
+          FMT_ENABLE_IF(std::is_floating_point<typename To::rep>::value)>
+auto safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
+                        int& ec) -> To {
+  using From = std::chrono::duration<FromRep, FromPeriod>;
+  ec = 0;
+
+  // the basic idea is that we need to convert from count() in the from type
+  // to count() in the To type, by multiplying it with this:
+  struct Factor
+      : std::ratio_divide<typename From::period, typename To::period> {};
+
+  static_assert(Factor::num > 0, "num must be positive");
+  static_assert(Factor::den > 0, "den must be positive");
+
+  // the conversion is like this: multiply from.count() with Factor::num
+  // /Factor::den and convert it to To::rep, all this without
+  // overflow/underflow. let's start by finding a suitable type that can hold
+  // both To, From and Factor::num
+  using IntermediateRep =
+      typename std::common_type<typename From::rep, typename To::rep,
+                                decltype(Factor::num)>::type;
+
+  // force conversion of From::rep -> IntermediateRep to be safe,
+  // even if it will never happen be narrowing in this context.
+  IntermediateRep count =
+      safe_float_conversion<IntermediateRep>(from.count(), ec);
+  if (ec) {
+    return {};
+  }
+
+  // multiply with Factor::num without overflow or underflow
+  if (detail::const_check(Factor::num != 1)) {
+    constexpr auto max1 = detail::max_value<IntermediateRep>() /
+                          static_cast<IntermediateRep>(Factor::num);
+    if (count > max1) {
+      ec = 1;
+      return {};
+    }
+    constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() /
+                          static_cast<IntermediateRep>(Factor::num);
+    if (count < min1) {
+      ec = 1;
+      return {};
+    }
+    count *= static_cast<IntermediateRep>(Factor::num);
+  }
+
+  // this can't go wrong, right? den>0 is checked earlier.
+  if (detail::const_check(Factor::den != 1)) {
+    using common_t = typename std::common_type<IntermediateRep, intmax_t>::type;
+    count /= static_cast<common_t>(Factor::den);
+  }
+
+  // convert to the to type, safely
+  using ToRep = typename To::rep;
+
+  const ToRep tocount = safe_float_conversion<ToRep>(count, ec);
+  if (ec) {
+    return {};
+  }
+  return To{tocount};
+}
+}  // namespace safe_duration_cast
+#endif
+
+namespace detail {
+
+// Check if std::chrono::utc_time is available.
+#ifdef FMT_USE_UTC_TIME
+// Use the provided definition.
+#elif defined(__cpp_lib_chrono)
+#  define FMT_USE_UTC_TIME (__cpp_lib_chrono >= 201907L)
+#else
+#  define FMT_USE_UTC_TIME 0
+#endif
+#if FMT_USE_UTC_TIME
+using utc_clock = std::chrono::utc_clock;
+#else
+struct utc_clock {
+  template <typename T> void to_sys(T);
+};
+#endif
+
+// Check if std::chrono::local_time is available.
+#ifdef FMT_USE_LOCAL_TIME
+// Use the provided definition.
+#elif defined(__cpp_lib_chrono)
+#  define FMT_USE_LOCAL_TIME (__cpp_lib_chrono >= 201907L)
+#else
+#  define FMT_USE_LOCAL_TIME 0
+#endif
+#if FMT_USE_LOCAL_TIME
+using local_t = std::chrono::local_t;
+#else
+struct local_t {};
+#endif
+
+}  // namespace detail
+
+template <typename Duration>
+using sys_time = std::chrono::time_point<std::chrono::system_clock, Duration>;
+
+template <typename Duration>
+using utc_time = std::chrono::time_point<detail::utc_clock, Duration>;
+
+template <class Duration>
+using local_time = std::chrono::time_point<detail::local_t, Duration>;
+
+namespace detail {
+
+// Prevents expansion of a preceding token as a function-style macro.
+// Usage: f FMT_NOMACRO()
+#define FMT_NOMACRO
+
+template <typename T = void> struct null {};
+inline auto gmtime_r(...) -> null<> { return null<>(); }
+inline auto gmtime_s(...) -> null<> { return null<>(); }
+
+// It is defined here and not in ostream.h because the latter has expensive
+// includes.
+template <typename StreamBuf> class formatbuf : public StreamBuf {
+ private:
+  using char_type = typename StreamBuf::char_type;
+  using streamsize = decltype(std::declval<StreamBuf>().sputn(nullptr, 0));
+  using int_type = typename StreamBuf::int_type;
+  using traits_type = typename StreamBuf::traits_type;
+
+  buffer<char_type>& buffer_;
+
+ public:
+  explicit formatbuf(buffer<char_type>& buf) : buffer_(buf) {}
+
+ protected:
+  // The put area is always empty. This makes the implementation simpler and has
+  // the advantage that the streambuf and the buffer are always in sync and
+  // sputc never writes into uninitialized memory. A disadvantage is that each
+  // call to sputc always results in a (virtual) call to overflow. There is no
+  // disadvantage here for sputn since this always results in a call to xsputn.
+
+  auto overflow(int_type ch) -> int_type override {
+    if (!traits_type::eq_int_type(ch, traits_type::eof()))
+      buffer_.push_back(static_cast<char_type>(ch));
+    return ch;
+  }
+
+  auto xsputn(const char_type* s, streamsize count) -> streamsize override {
+    buffer_.append(s, s + count);
+    return count;
+  }
+};
+
+inline auto get_classic_locale() -> const std::locale& {
+  static const auto& locale = std::locale::classic();
+  return locale;
+}
+
+template <typename CodeUnit> struct codecvt_result {
+  static constexpr size_t max_size = 32;
+  CodeUnit buf[max_size];
+  CodeUnit* end;
+};
+
+template <typename CodeUnit>
+void write_codecvt(codecvt_result<CodeUnit>& out, string_view in,
+                   const std::locale& loc) {
+  FMT_PRAGMA_CLANG(diagnostic push)
+  FMT_PRAGMA_CLANG(diagnostic ignored "-Wdeprecated")
+  auto& f = std::use_facet<std::codecvt<CodeUnit, char, std::mbstate_t>>(loc);
+  FMT_PRAGMA_CLANG(diagnostic pop)
+  auto mb = std::mbstate_t();
+  const char* from_next = nullptr;
+  auto result = f.in(mb, in.begin(), in.end(), from_next, std::begin(out.buf),
+                     std::end(out.buf), out.end);
+  if (result != std::codecvt_base::ok)
+    FMT_THROW(format_error("failed to format time"));
+}
+
+template <typename OutputIt>
+auto write_encoded_tm_str(OutputIt out, string_view in, const std::locale& loc)
+    -> OutputIt {
+  if (const_check(detail::use_utf8) && loc != get_classic_locale()) {
+    // char16_t and char32_t codecvts are broken in MSVC (linkage errors) and
+    // gcc-4.
+#if FMT_MSC_VERSION != 0 ||  \
+    (defined(__GLIBCXX__) && \
+     (!defined(_GLIBCXX_USE_DUAL_ABI) || _GLIBCXX_USE_DUAL_ABI == 0))
+    // The _GLIBCXX_USE_DUAL_ABI macro is always defined in libstdc++ from gcc-5
+    // and newer.
+    using code_unit = wchar_t;
+#else
+    using code_unit = char32_t;
+#endif
+
+    using unit_t = codecvt_result<code_unit>;
+    unit_t unit;
+    write_codecvt(unit, in, loc);
+    // In UTF-8 is used one to four one-byte code units.
+    auto u =
+        to_utf8<code_unit, basic_memory_buffer<char, unit_t::max_size * 4>>();
+    if (!u.convert({unit.buf, to_unsigned(unit.end - unit.buf)}))
+      FMT_THROW(format_error("failed to format time"));
+    return copy<char>(u.c_str(), u.c_str() + u.size(), out);
+  }
+  return copy<char>(in.data(), in.data() + in.size(), out);
+}
+
+template <typename Char, typename OutputIt,
+          FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
+auto write_tm_str(OutputIt out, string_view sv, const std::locale& loc)
+    -> OutputIt {
+  codecvt_result<Char> unit;
+  write_codecvt(unit, sv, loc);
+  return copy<Char>(unit.buf, unit.end, out);
+}
+
+template <typename Char, typename OutputIt,
+          FMT_ENABLE_IF(std::is_same<Char, char>::value)>
+auto write_tm_str(OutputIt out, string_view sv, const std::locale& loc)
+    -> OutputIt {
+  return write_encoded_tm_str(out, sv, loc);
+}
+
+template <typename Char>
+inline void do_write(buffer<Char>& buf, const std::tm& time,
+                     const std::locale& loc, char format, char modifier) {
+  auto&& format_buf = formatbuf<std::basic_streambuf<Char>>(buf);
+  auto&& os = std::basic_ostream<Char>(&format_buf);
+  os.imbue(loc);
+  const auto& facet = std::use_facet<std::time_put<Char>>(loc);
+  auto end = facet.put(os, os, Char(' '), &time, format, modifier);
+  if (end.failed()) FMT_THROW(format_error("failed to format time"));
+}
+
+template <typename Char, typename OutputIt,
+          FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
+auto write(OutputIt out, const std::tm& time, const std::locale& loc,
+           char format, char modifier = 0) -> OutputIt {
+  auto&& buf = get_buffer<Char>(out);
+  do_write<Char>(buf, time, loc, format, modifier);
+  return get_iterator(buf, out);
+}
+
+template <typename Char, typename OutputIt,
+          FMT_ENABLE_IF(std::is_same<Char, char>::value)>
+auto write(OutputIt out, const std::tm& time, const std::locale& loc,
+           char format, char modifier = 0) -> OutputIt {
+  auto&& buf = basic_memory_buffer<Char>();
+  do_write<char>(buf, time, loc, format, modifier);
+  return write_encoded_tm_str(out, string_view(buf.data(), buf.size()), loc);
+}
+
+template <typename T, typename U>
+using is_similar_arithmetic_type =
+    bool_constant<(std::is_integral<T>::value && std::is_integral<U>::value) ||
+                  (std::is_floating_point<T>::value &&
+                   std::is_floating_point<U>::value)>;
+
+FMT_NORETURN inline void throw_duration_error() {
+  FMT_THROW(format_error("cannot format duration"));
+}
+
+// Cast one integral duration to another with an overflow check.
+template <typename To, typename FromRep, typename FromPeriod,
+          FMT_ENABLE_IF(std::is_integral<FromRep>::value&&
+                            std::is_integral<typename To::rep>::value)>
+auto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {
+#if !FMT_SAFE_DURATION_CAST
+  return std::chrono::duration_cast<To>(from);
+#else
+  // The conversion factor: to.count() == factor * from.count().
+  using factor = std::ratio_divide<FromPeriod, typename To::period>;
+
+  using common_rep = typename std::common_type<FromRep, typename To::rep,
+                                               decltype(factor::num)>::type;
+  common_rep count = from.count();  // This conversion is lossless.
+
+  // Multiply from.count() by factor and check for overflow.
+  if (const_check(factor::num != 1)) {
+    if (count > max_value<common_rep>() / factor::num) throw_duration_error();
+    const auto min = (std::numeric_limits<common_rep>::min)() / factor::num;
+    if (const_check(!std::is_unsigned<common_rep>::value) && count < min)
+      throw_duration_error();
+    count *= factor::num;
+  }
+  if (const_check(factor::den != 1)) count /= factor::den;
+  int ec = 0;
+  auto to =
+      To(safe_duration_cast::lossless_integral_conversion<typename To::rep>(
+          count, ec));
+  if (ec) throw_duration_error();
+  return to;
+#endif
+}
+
+template <typename To, typename FromRep, typename FromPeriod,
+          FMT_ENABLE_IF(std::is_floating_point<FromRep>::value&&
+                            std::is_floating_point<typename To::rep>::value)>
+auto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {
+#if FMT_SAFE_DURATION_CAST
+  // Preserve infinity and NaN.
+  if (!isfinite(from.count())) return static_cast<To>(from.count());
+  // Throwing version of safe_duration_cast is only available for
+  // integer to integer or float to float casts.
+  int ec;
+  To to = safe_duration_cast::safe_duration_cast<To>(from, ec);
+  if (ec) throw_duration_error();
+  return to;
+#else
+  // Standard duration cast, may overflow.
+  return std::chrono::duration_cast<To>(from);
+#endif
+}
+
+template <typename To, typename FromRep, typename FromPeriod,
+          FMT_ENABLE_IF(
+              !is_similar_arithmetic_type<FromRep, typename To::rep>::value)>
+auto duration_cast(std::chrono::duration<FromRep, FromPeriod> from) -> To {
+  // Mixed integer <-> float cast is not supported by safe duration_cast.
+  return std::chrono::duration_cast<To>(from);
+}
+
+template <typename Duration>
+auto to_time_t(sys_time<Duration> time_point) -> std::time_t {
+  // Cannot use std::chrono::system_clock::to_time_t since this would first
+  // require a cast to std::chrono::system_clock::time_point, which could
+  // overflow.
+  return detail::duration_cast<std::chrono::duration<std::time_t>>(
+             time_point.time_since_epoch())
+      .count();
+}
+
+}  // namespace detail
+
+FMT_BEGIN_EXPORT
+
+/**
+ * Converts given time since epoch as `std::time_t` value into calendar time,
+ * expressed in Coordinated Universal Time (UTC). Unlike `std::gmtime`, this
+ * function is thread-safe on most platforms.
+ */
+inline auto gmtime(std::time_t time) -> std::tm {
+  struct dispatcher {
+    std::time_t time_;
+    std::tm tm_;
+
+    inline dispatcher(std::time_t t) : time_(t) {}
+
+    inline auto run() -> bool {
+      using namespace fmt::detail;
+      return handle(gmtime_r(&time_, &tm_));
+    }
+
+    inline auto handle(std::tm* tm) -> bool { return tm != nullptr; }
+
+    inline auto handle(detail::null<>) -> bool {
+      using namespace fmt::detail;
+      return fallback(gmtime_s(&tm_, &time_));
+    }
+
+    inline auto fallback(int res) -> bool { return res == 0; }
+
+#if !FMT_MSC_VERSION
+    inline auto fallback(detail::null<>) -> bool {
+      std::tm* tm = std::gmtime(&time_);
+      if (tm) tm_ = *tm;
+      return tm != nullptr;
+    }
+#endif
+  };
+  auto gt = dispatcher(time);
+  // Too big time values may be unsupported.
+  if (!gt.run()) FMT_THROW(format_error("time_t value out of range"));
+  return gt.tm_;
+}
+
+template <typename Duration>
+inline auto gmtime(sys_time<Duration> time_point) -> std::tm {
+  return gmtime(detail::to_time_t(time_point));
+}
+
+namespace detail {
+
+// Writes two-digit numbers a, b and c separated by sep to buf.
+// The method by Pavel Novikov based on
+// https://johnnylee-sde.github.io/Fast-unsigned-integer-to-time-string/.
+inline void write_digit2_separated(char* buf, unsigned a, unsigned b,
+                                   unsigned c, char sep) {
+  unsigned long long digits =
+      a | (b << 24) | (static_cast<unsigned long long>(c) << 48);
+  // Convert each value to BCD.
+  // We have x = a * 10 + b and we want to convert it to BCD y = a * 16 + b.
+  // The difference is
+  //   y - x = a * 6
+  // a can be found from x:
+  //   a = floor(x / 10)
+  // then
+  //   y = x + a * 6 = x + floor(x / 10) * 6
+  // floor(x / 10) is (x * 205) >> 11 (needs 16 bits).
+  digits += (((digits * 205) >> 11) & 0x000f00000f00000f) * 6;
+  // Put low nibbles to high bytes and high nibbles to low bytes.
+  digits = ((digits & 0x00f00000f00000f0) >> 4) |
+           ((digits & 0x000f00000f00000f) << 8);
+  auto usep = static_cast<unsigned long long>(sep);
+  // Add ASCII '0' to each digit byte and insert separators.
+  digits |= 0x3030003030003030 | (usep << 16) | (usep << 40);
+
+  constexpr size_t len = 8;
+  if (const_check(is_big_endian())) {
+    char tmp[len];
+    std::memcpy(tmp, &digits, len);
+    std::reverse_copy(tmp, tmp + len, buf);
+  } else {
+    std::memcpy(buf, &digits, len);
+  }
+}
+
+template <typename Period>
+FMT_CONSTEXPR inline auto get_units() -> const char* {
+  if (std::is_same<Period, std::atto>::value) return "as";
+  if (std::is_same<Period, std::femto>::value) return "fs";
+  if (std::is_same<Period, std::pico>::value) return "ps";
+  if (std::is_same<Period, std::nano>::value) return "ns";
+  if (std::is_same<Period, std::micro>::value)
+    return detail::use_utf8 ? "µs" : "us";
+  if (std::is_same<Period, std::milli>::value) return "ms";
+  if (std::is_same<Period, std::centi>::value) return "cs";
+  if (std::is_same<Period, std::deci>::value) return "ds";
+  if (std::is_same<Period, std::ratio<1>>::value) return "s";
+  if (std::is_same<Period, std::deca>::value) return "das";
+  if (std::is_same<Period, std::hecto>::value) return "hs";
+  if (std::is_same<Period, std::kilo>::value) return "ks";
+  if (std::is_same<Period, std::mega>::value) return "Ms";
+  if (std::is_same<Period, std::giga>::value) return "Gs";
+  if (std::is_same<Period, std::tera>::value) return "Ts";
+  if (std::is_same<Period, std::peta>::value) return "Ps";
+  if (std::is_same<Period, std::exa>::value) return "Es";
+  if (std::is_same<Period, std::ratio<60>>::value) return "min";
+  if (std::is_same<Period, std::ratio<3600>>::value) return "h";
+  if (std::is_same<Period, std::ratio<86400>>::value) return "d";
+  return nullptr;
+}
+
+enum class numeric_system {
+  standard,
+  // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale.
+  alternative
+};
+
+// Glibc extensions for formatting numeric values.
+enum class pad_type {
+  // Pad a numeric result string with zeros (the default).
+  zero,
+  // Do not pad a numeric result string.
+  none,
+  // Pad a numeric result string with spaces.
+  space,
+};
+
+template <typename OutputIt>
+auto write_padding(OutputIt out, pad_type pad, int width) -> OutputIt {
+  if (pad == pad_type::none) return out;
+  return detail::fill_n(out, width, pad == pad_type::space ? ' ' : '0');
+}
+
+template <typename OutputIt>
+auto write_padding(OutputIt out, pad_type pad) -> OutputIt {
+  if (pad != pad_type::none) *out++ = pad == pad_type::space ? ' ' : '0';
+  return out;
+}
+
+// Parses a put_time-like format string and invokes handler actions.
+template <typename Char, typename Handler>
+FMT_CONSTEXPR auto parse_chrono_format(const Char* begin, const Char* end,
+                                       Handler&& handler) -> const Char* {
+  if (begin == end || *begin == '}') return begin;
+  if (*begin != '%') FMT_THROW(format_error("invalid format"));
+  auto ptr = begin;
+  while (ptr != end) {
+    pad_type pad = pad_type::zero;
+    auto c = *ptr;
+    if (c == '}') break;
+    if (c != '%') {
+      ++ptr;
+      continue;
+    }
+    if (begin != ptr) handler.on_text(begin, ptr);
+    ++ptr;  // consume '%'
+    if (ptr == end) FMT_THROW(format_error("invalid format"));
+    c = *ptr;
+    switch (c) {
+    case '_':
+      pad = pad_type::space;
+      ++ptr;
+      break;
+    case '-':
+      pad = pad_type::none;
+      ++ptr;
+      break;
+    }
+    if (ptr == end) FMT_THROW(format_error("invalid format"));
+    c = *ptr++;
+    switch (c) {
+    case '%': handler.on_text(ptr - 1, ptr); break;
+    case 'n': {
+      const Char newline[] = {'\n'};
+      handler.on_text(newline, newline + 1);
+      break;
+    }
+    case 't': {
+      const Char tab[] = {'\t'};
+      handler.on_text(tab, tab + 1);
+      break;
+    }
+    // Year:
+    case 'Y': handler.on_year(numeric_system::standard, pad); break;
+    case 'y': handler.on_short_year(numeric_system::standard); break;
+    case 'C': handler.on_century(numeric_system::standard); break;
+    case 'G': handler.on_iso_week_based_year(); break;
+    case 'g': handler.on_iso_week_based_short_year(); break;
+    // Day of the week:
+    case 'a': handler.on_abbr_weekday(); break;
+    case 'A': handler.on_full_weekday(); break;
+    case 'w': handler.on_dec0_weekday(numeric_system::standard); break;
+    case 'u': handler.on_dec1_weekday(numeric_system::standard); break;
+    // Month:
+    case 'b':
+    case 'h': handler.on_abbr_month(); break;
+    case 'B': handler.on_full_month(); break;
+    case 'm': handler.on_dec_month(numeric_system::standard, pad); break;
+    // Day of the year/month:
+    case 'U':
+      handler.on_dec0_week_of_year(numeric_system::standard, pad);
+      break;
+    case 'W':
+      handler.on_dec1_week_of_year(numeric_system::standard, pad);
+      break;
+    case 'V': handler.on_iso_week_of_year(numeric_system::standard, pad); break;
+    case 'j': handler.on_day_of_year(pad); break;
+    case 'd': handler.on_day_of_month(numeric_system::standard, pad); break;
+    case 'e':
+      handler.on_day_of_month(numeric_system::standard, pad_type::space);
+      break;
+    // Hour, minute, second:
+    case 'H': handler.on_24_hour(numeric_system::standard, pad); break;
+    case 'I': handler.on_12_hour(numeric_system::standard, pad); break;
+    case 'M': handler.on_minute(numeric_system::standard, pad); break;
+    case 'S': handler.on_second(numeric_system::standard, pad); break;
+    // Other:
+    case 'c': handler.on_datetime(numeric_system::standard); break;
+    case 'x': handler.on_loc_date(numeric_system::standard); break;
+    case 'X': handler.on_loc_time(numeric_system::standard); break;
+    case 'D': handler.on_us_date(); break;
+    case 'F': handler.on_iso_date(); break;
+    case 'r': handler.on_12_hour_time(); break;
+    case 'R': handler.on_24_hour_time(); break;
+    case 'T': handler.on_iso_time(); break;
+    case 'p': handler.on_am_pm(); break;
+    case 'Q': handler.on_duration_value(); break;
+    case 'q': handler.on_duration_unit(); break;
+    case 'z': handler.on_utc_offset(numeric_system::standard); break;
+    case 'Z': handler.on_tz_name(); break;
+    // Alternative representation:
+    case 'E': {
+      if (ptr == end) FMT_THROW(format_error("invalid format"));
+      c = *ptr++;
+      switch (c) {
+      case 'Y': handler.on_year(numeric_system::alternative, pad); break;
+      case 'y': handler.on_offset_year(); break;
+      case 'C': handler.on_century(numeric_system::alternative); break;
+      case 'c': handler.on_datetime(numeric_system::alternative); break;
+      case 'x': handler.on_loc_date(numeric_system::alternative); break;
+      case 'X': handler.on_loc_time(numeric_system::alternative); break;
+      case 'z': handler.on_utc_offset(numeric_system::alternative); break;
+      default:  FMT_THROW(format_error("invalid format"));
+      }
+      break;
+    }
+    case 'O':
+      if (ptr == end) FMT_THROW(format_error("invalid format"));
+      c = *ptr++;
+      switch (c) {
+      case 'y': handler.on_short_year(numeric_system::alternative); break;
+      case 'm': handler.on_dec_month(numeric_system::alternative, pad); break;
+      case 'U':
+        handler.on_dec0_week_of_year(numeric_system::alternative, pad);
+        break;
+      case 'W':
+        handler.on_dec1_week_of_year(numeric_system::alternative, pad);
+        break;
+      case 'V':
+        handler.on_iso_week_of_year(numeric_system::alternative, pad);
+        break;
+      case 'd':
+        handler.on_day_of_month(numeric_system::alternative, pad);
+        break;
+      case 'e':
+        handler.on_day_of_month(numeric_system::alternative, pad_type::space);
+        break;
+      case 'w': handler.on_dec0_weekday(numeric_system::alternative); break;
+      case 'u': handler.on_dec1_weekday(numeric_system::alternative); break;
+      case 'H': handler.on_24_hour(numeric_system::alternative, pad); break;
+      case 'I': handler.on_12_hour(numeric_system::alternative, pad); break;
+      case 'M': handler.on_minute(numeric_system::alternative, pad); break;
+      case 'S': handler.on_second(numeric_system::alternative, pad); break;
+      case 'z': handler.on_utc_offset(numeric_system::alternative); break;
+      default:  FMT_THROW(format_error("invalid format"));
+      }
+      break;
+    default: FMT_THROW(format_error("invalid format"));
+    }
+    begin = ptr;
+  }
+  if (begin != ptr) handler.on_text(begin, ptr);
+  return ptr;
+}
+
+template <typename Derived> struct null_chrono_spec_handler {
+  FMT_CONSTEXPR void unsupported() {
+    static_cast<Derived*>(this)->unsupported();
+  }
+  FMT_CONSTEXPR void on_year(numeric_system, pad_type) { unsupported(); }
+  FMT_CONSTEXPR void on_short_year(numeric_system) { unsupported(); }
+  FMT_CONSTEXPR void on_offset_year() { unsupported(); }
+  FMT_CONSTEXPR void on_century(numeric_system) { unsupported(); }
+  FMT_CONSTEXPR void on_iso_week_based_year() { unsupported(); }
+  FMT_CONSTEXPR void on_iso_week_based_short_year() { unsupported(); }
+  FMT_CONSTEXPR void on_abbr_weekday() { unsupported(); }
+  FMT_CONSTEXPR void on_full_weekday() { unsupported(); }
+  FMT_CONSTEXPR void on_dec0_weekday(numeric_system) { unsupported(); }
+  FMT_CONSTEXPR void on_dec1_weekday(numeric_system) { unsupported(); }
+  FMT_CONSTEXPR void on_abbr_month() { unsupported(); }
+  FMT_CONSTEXPR void on_full_month() { unsupported(); }
+  FMT_CONSTEXPR void on_dec_month(numeric_system, pad_type) { unsupported(); }
+  FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system, pad_type) {
+    unsupported();
+  }
+  FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system, pad_type) {
+    unsupported();
+  }
+  FMT_CONSTEXPR void on_iso_week_of_year(numeric_system, pad_type) {
+    unsupported();
+  }
+  FMT_CONSTEXPR void on_day_of_year(pad_type) { unsupported(); }
+  FMT_CONSTEXPR void on_day_of_month(numeric_system, pad_type) {
+    unsupported();
+  }
+  FMT_CONSTEXPR void on_24_hour(numeric_system) { unsupported(); }
+  FMT_CONSTEXPR void on_12_hour(numeric_system) { unsupported(); }
+  FMT_CONSTEXPR void on_minute(numeric_system) { unsupported(); }
+  FMT_CONSTEXPR void on_second(numeric_system) { unsupported(); }
+  FMT_CONSTEXPR void on_datetime(numeric_system) { unsupported(); }
+  FMT_CONSTEXPR void on_loc_date(numeric_system) { unsupported(); }
+  FMT_CONSTEXPR void on_loc_time(numeric_system) { unsupported(); }
+  FMT_CONSTEXPR void on_us_date() { unsupported(); }
+  FMT_CONSTEXPR void on_iso_date() { unsupported(); }
+  FMT_CONSTEXPR void on_12_hour_time() { unsupported(); }
+  FMT_CONSTEXPR void on_24_hour_time() { unsupported(); }
+  FMT_CONSTEXPR void on_iso_time() { unsupported(); }
+  FMT_CONSTEXPR void on_am_pm() { unsupported(); }
+  FMT_CONSTEXPR void on_duration_value() { unsupported(); }
+  FMT_CONSTEXPR void on_duration_unit() { unsupported(); }
+  FMT_CONSTEXPR void on_utc_offset(numeric_system) { unsupported(); }
+  FMT_CONSTEXPR void on_tz_name() { unsupported(); }
+};
+
+class tm_format_checker : public null_chrono_spec_handler<tm_format_checker> {
+ private:
+  bool has_timezone_ = false;
+
+ public:
+  constexpr explicit tm_format_checker(bool has_timezone)
+      : has_timezone_(has_timezone) {}
+
+  FMT_NORETURN inline void unsupported() {
+    FMT_THROW(format_error("no format"));
+  }
+
+  template <typename Char>
+  FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
+  FMT_CONSTEXPR void on_year(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_short_year(numeric_system) {}
+  FMT_CONSTEXPR void on_offset_year() {}
+  FMT_CONSTEXPR void on_century(numeric_system) {}
+  FMT_CONSTEXPR void on_iso_week_based_year() {}
+  FMT_CONSTEXPR void on_iso_week_based_short_year() {}
+  FMT_CONSTEXPR void on_abbr_weekday() {}
+  FMT_CONSTEXPR void on_full_weekday() {}
+  FMT_CONSTEXPR void on_dec0_weekday(numeric_system) {}
+  FMT_CONSTEXPR void on_dec1_weekday(numeric_system) {}
+  FMT_CONSTEXPR void on_abbr_month() {}
+  FMT_CONSTEXPR void on_full_month() {}
+  FMT_CONSTEXPR void on_dec_month(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_dec0_week_of_year(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_dec1_week_of_year(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_iso_week_of_year(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_day_of_year(pad_type) {}
+  FMT_CONSTEXPR void on_day_of_month(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_second(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_datetime(numeric_system) {}
+  FMT_CONSTEXPR void on_loc_date(numeric_system) {}
+  FMT_CONSTEXPR void on_loc_time(numeric_system) {}
+  FMT_CONSTEXPR void on_us_date() {}
+  FMT_CONSTEXPR void on_iso_date() {}
+  FMT_CONSTEXPR void on_12_hour_time() {}
+  FMT_CONSTEXPR void on_24_hour_time() {}
+  FMT_CONSTEXPR void on_iso_time() {}
+  FMT_CONSTEXPR void on_am_pm() {}
+  FMT_CONSTEXPR void on_utc_offset(numeric_system) {
+    if (!has_timezone_) FMT_THROW(format_error("no timezone"));
+  }
+  FMT_CONSTEXPR void on_tz_name() {
+    if (!has_timezone_) FMT_THROW(format_error("no timezone"));
+  }
+};
+
+inline auto tm_wday_full_name(int wday) -> const char* {
+  static constexpr const char* full_name_list[] = {
+      "Sunday",   "Monday", "Tuesday", "Wednesday",
+      "Thursday", "Friday", "Saturday"};
+  return wday >= 0 && wday <= 6 ? full_name_list[wday] : "?";
+}
+inline auto tm_wday_short_name(int wday) -> const char* {
+  static constexpr const char* short_name_list[] = {"Sun", "Mon", "Tue", "Wed",
+                                                    "Thu", "Fri", "Sat"};
+  return wday >= 0 && wday <= 6 ? short_name_list[wday] : "???";
+}
+
+inline auto tm_mon_full_name(int mon) -> const char* {
+  static constexpr const char* full_name_list[] = {
+      "January", "February", "March",     "April",   "May",      "June",
+      "July",    "August",   "September", "October", "November", "December"};
+  return mon >= 0 && mon <= 11 ? full_name_list[mon] : "?";
+}
+inline auto tm_mon_short_name(int mon) -> const char* {
+  static constexpr const char* short_name_list[] = {
+      "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
+  };
+  return mon >= 0 && mon <= 11 ? short_name_list[mon] : "???";
+}
+
+template <typename T, typename = void>
+struct has_tm_gmtoff : std::false_type {};
+template <typename T>
+struct has_tm_gmtoff<T, void_t<decltype(T::tm_gmtoff)>> : std::true_type {};
+
+template <typename T, typename = void> struct has_tm_zone : std::false_type {};
+template <typename T>
+struct has_tm_zone<T, void_t<decltype(T::tm_zone)>> : std::true_type {};
+
+template <typename T, FMT_ENABLE_IF(has_tm_zone<T>::value)>
+auto set_tm_zone(T& time, char* tz) -> bool {
+  time.tm_zone = tz;
+  return true;
+}
+template <typename T, FMT_ENABLE_IF(!has_tm_zone<T>::value)>
+auto set_tm_zone(T&, char*) -> bool {
+  return false;
+}
+
+inline auto utc() -> char* {
+  static char tz[] = "UTC";
+  return tz;
+}
+
+// Converts value to Int and checks that it's in the range [0, upper).
+template <typename T, typename Int, FMT_ENABLE_IF(std::is_integral<T>::value)>
+inline auto to_nonnegative_int(T value, Int upper) -> Int {
+  if (!std::is_unsigned<Int>::value &&
+      (value < 0 || to_unsigned(value) > to_unsigned(upper))) {
+    FMT_THROW(format_error("chrono value is out of range"));
+  }
+  return static_cast<Int>(value);
+}
+template <typename T, typename Int, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+inline auto to_nonnegative_int(T value, Int upper) -> Int {
+  auto int_value = static_cast<Int>(value);
+  if (int_value < 0 || value > static_cast<T>(upper))
+    FMT_THROW(format_error("invalid value"));
+  return int_value;
+}
+
+constexpr auto pow10(std::uint32_t n) -> long long {
+  return n == 0 ? 1 : 10 * pow10(n - 1);
+}
+
+// Counts the number of fractional digits in the range [0, 18] according to the
+// C++20 spec. If more than 18 fractional digits are required then returns 6 for
+// microseconds precision.
+template <long long Num, long long Den, int N = 0,
+          bool Enabled = (N < 19) && (Num <= max_value<long long>() / 10)>
+struct count_fractional_digits {
+  static constexpr int value =
+      Num % Den == 0 ? N : count_fractional_digits<Num * 10, Den, N + 1>::value;
+};
+
+// Base case that doesn't instantiate any more templates
+// in order to avoid overflow.
+template <long long Num, long long Den, int N>
+struct count_fractional_digits<Num, Den, N, false> {
+  static constexpr int value = (Num % Den == 0) ? N : 6;
+};
+
+// Format subseconds which are given as an integer type with an appropriate
+// number of digits.
+template <typename Char, typename OutputIt, typename Duration>
+void write_fractional_seconds(OutputIt& out, Duration d, int precision = -1) {
+  constexpr auto num_fractional_digits =
+      count_fractional_digits<Duration::period::num,
+                              Duration::period::den>::value;
+
+  using subsecond_precision = std::chrono::duration<
+      typename std::common_type<typename Duration::rep,
+                                std::chrono::seconds::rep>::type,
+      std::ratio<1, pow10(num_fractional_digits)>>;
+
+  const auto fractional = d - detail::duration_cast<std::chrono::seconds>(d);
+  const auto subseconds =
+      std::chrono::treat_as_floating_point<
+          typename subsecond_precision::rep>::value
+          ? fractional.count()
+          : detail::duration_cast<subsecond_precision>(fractional).count();
+  auto n = static_cast<uint32_or_64_or_128_t<long long>>(subseconds);
+  const int num_digits = count_digits(n);
+
+  int leading_zeroes = (std::max)(0, num_fractional_digits - num_digits);
+  if (precision < 0) {
+    FMT_ASSERT(!std::is_floating_point<typename Duration::rep>::value, "");
+    if (std::ratio_less<typename subsecond_precision::period,
+                        std::chrono::seconds::period>::value) {
+      *out++ = '.';
+      out = detail::fill_n(out, leading_zeroes, '0');
+      out = format_decimal<Char>(out, n, num_digits);
+    }
+  } else if (precision > 0) {
+    *out++ = '.';
+    leading_zeroes = min_of(leading_zeroes, precision);
+    int remaining = precision - leading_zeroes;
+    out = detail::fill_n(out, leading_zeroes, '0');
+    if (remaining < num_digits) {
+      int num_truncated_digits = num_digits - remaining;
+      n /= to_unsigned(pow10(to_unsigned(num_truncated_digits)));
+      if (n != 0) out = format_decimal<Char>(out, n, remaining);
+      return;
+    }
+    if (n != 0) {
+      out = format_decimal<Char>(out, n, num_digits);
+      remaining -= num_digits;
+    }
+    out = detail::fill_n(out, remaining, '0');
+  }
+}
+
+// Format subseconds which are given as a floating point type with an
+// appropriate number of digits. We cannot pass the Duration here, as we
+// explicitly need to pass the Rep value in the duration_formatter.
+template <typename Duration>
+void write_floating_seconds(memory_buffer& buf, Duration duration,
+                            int num_fractional_digits = -1) {
+  using rep = typename Duration::rep;
+  FMT_ASSERT(std::is_floating_point<rep>::value, "");
+
+  auto val = duration.count();
+
+  if (num_fractional_digits < 0) {
+    // For `std::round` with fallback to `round`:
+    // On some toolchains `std::round` is not available (e.g. GCC 6).
+    using namespace std;
+    num_fractional_digits =
+        count_fractional_digits<Duration::period::num,
+                                Duration::period::den>::value;
+    if (num_fractional_digits < 6 && static_cast<rep>(round(val)) != val)
+      num_fractional_digits = 6;
+  }
+
+  fmt::format_to(std::back_inserter(buf), FMT_STRING("{:.{}f}"),
+                 std::fmod(val * static_cast<rep>(Duration::period::num) /
+                               static_cast<rep>(Duration::period::den),
+                           static_cast<rep>(60)),
+                 num_fractional_digits);
+}
+
+template <typename OutputIt, typename Char,
+          typename Duration = std::chrono::seconds>
+class tm_writer {
+ private:
+  static constexpr int days_per_week = 7;
+
+  const std::locale& loc_;
+  bool is_classic_;
+  OutputIt out_;
+  const Duration* subsecs_;
+  const std::tm& tm_;
+
+  auto tm_sec() const noexcept -> int {
+    FMT_ASSERT(tm_.tm_sec >= 0 && tm_.tm_sec <= 61, "");
+    return tm_.tm_sec;
+  }
+  auto tm_min() const noexcept -> int {
+    FMT_ASSERT(tm_.tm_min >= 0 && tm_.tm_min <= 59, "");
+    return tm_.tm_min;
+  }
+  auto tm_hour() const noexcept -> int {
+    FMT_ASSERT(tm_.tm_hour >= 0 && tm_.tm_hour <= 23, "");
+    return tm_.tm_hour;
+  }
+  auto tm_mday() const noexcept -> int {
+    FMT_ASSERT(tm_.tm_mday >= 1 && tm_.tm_mday <= 31, "");
+    return tm_.tm_mday;
+  }
+  auto tm_mon() const noexcept -> int {
+    FMT_ASSERT(tm_.tm_mon >= 0 && tm_.tm_mon <= 11, "");
+    return tm_.tm_mon;
+  }
+  auto tm_year() const noexcept -> long long { return 1900ll + tm_.tm_year; }
+  auto tm_wday() const noexcept -> int {
+    FMT_ASSERT(tm_.tm_wday >= 0 && tm_.tm_wday <= 6, "");
+    return tm_.tm_wday;
+  }
+  auto tm_yday() const noexcept -> int {
+    FMT_ASSERT(tm_.tm_yday >= 0 && tm_.tm_yday <= 365, "");
+    return tm_.tm_yday;
+  }
+
+  auto tm_hour12() const noexcept -> int {
+    auto h = tm_hour();
+    auto z = h < 12 ? h : h - 12;
+    return z == 0 ? 12 : z;
+  }
+
+  // POSIX and the C Standard are unclear or inconsistent about what %C and %y
+  // do if the year is negative or exceeds 9999. Use the convention that %C
+  // concatenated with %y yields the same output as %Y, and that %Y contains at
+  // least 4 characters, with more only if necessary.
+  auto split_year_lower(long long year) const noexcept -> int {
+    auto l = year % 100;
+    if (l < 0) l = -l;  // l in [0, 99]
+    return static_cast<int>(l);
+  }
+
+  // Algorithm: https://en.wikipedia.org/wiki/ISO_week_date.
+  auto iso_year_weeks(long long curr_year) const noexcept -> int {
+    auto prev_year = curr_year - 1;
+    auto curr_p =
+        (curr_year + curr_year / 4 - curr_year / 100 + curr_year / 400) %
+        days_per_week;
+    auto prev_p =
+        (prev_year + prev_year / 4 - prev_year / 100 + prev_year / 400) %
+        days_per_week;
+    return 52 + ((curr_p == 4 || prev_p == 3) ? 1 : 0);
+  }
+  auto iso_week_num(int tm_yday, int tm_wday) const noexcept -> int {
+    return (tm_yday + 11 - (tm_wday == 0 ? days_per_week : tm_wday)) /
+           days_per_week;
+  }
+  auto tm_iso_week_year() const noexcept -> long long {
+    auto year = tm_year();
+    auto w = iso_week_num(tm_yday(), tm_wday());
+    if (w < 1) return year - 1;
+    if (w > iso_year_weeks(year)) return year + 1;
+    return year;
+  }
+  auto tm_iso_week_of_year() const noexcept -> int {
+    auto year = tm_year();
+    auto w = iso_week_num(tm_yday(), tm_wday());
+    if (w < 1) return iso_year_weeks(year - 1);
+    if (w > iso_year_weeks(year)) return 1;
+    return w;
+  }
+
+  void write1(int value) {
+    *out_++ = static_cast<char>('0' + to_unsigned(value) % 10);
+  }
+  void write2(int value) {
+    const char* d = digits2(to_unsigned(value) % 100);
+    *out_++ = *d++;
+    *out_++ = *d;
+  }
+  void write2(int value, pad_type pad) {
+    unsigned int v = to_unsigned(value) % 100;
+    if (v >= 10) {
+      const char* d = digits2(v);
+      *out_++ = *d++;
+      *out_++ = *d;
+    } else {
+      out_ = detail::write_padding(out_, pad);
+      *out_++ = static_cast<char>('0' + v);
+    }
+  }
+
+  void write_year_extended(long long year, pad_type pad) {
+    // At least 4 characters.
+    int width = 4;
+    bool negative = year < 0;
+    if (negative) {
+      year = 0 - year;
+      --width;
+    }
+    uint32_or_64_or_128_t<long long> n = to_unsigned(year);
+    const int num_digits = count_digits(n);
+    if (negative && pad == pad_type::zero) *out_++ = '-';
+    if (width > num_digits)
+      out_ = detail::write_padding(out_, pad, width - num_digits);
+    if (negative && pad != pad_type::zero) *out_++ = '-';
+    out_ = format_decimal<Char>(out_, n, num_digits);
+  }
+  void write_year(long long year, pad_type pad) {
+    write_year_extended(year, pad);
+  }
+
+  void write_utc_offset(long long offset, numeric_system ns) {
+    if (offset < 0) {
+      *out_++ = '-';
+      offset = -offset;
+    } else {
+      *out_++ = '+';
+    }
+    offset /= 60;
+    write2(static_cast<int>(offset / 60));
+    if (ns != numeric_system::standard) *out_++ = ':';
+    write2(static_cast<int>(offset % 60));
+  }
+
+  template <typename T, FMT_ENABLE_IF(has_tm_gmtoff<T>::value)>
+  void format_utc_offset(const T& tm, numeric_system ns) {
+    write_utc_offset(tm.tm_gmtoff, ns);
+  }
+  template <typename T, FMT_ENABLE_IF(!has_tm_gmtoff<T>::value)>
+  void format_utc_offset(const T&, numeric_system ns) {
+    write_utc_offset(0, ns);
+  }
+
+  template <typename T, FMT_ENABLE_IF(has_tm_zone<T>::value)>
+  void format_tz_name(const T& tm) {
+    out_ = write_tm_str<Char>(out_, tm.tm_zone, loc_);
+  }
+  template <typename T, FMT_ENABLE_IF(!has_tm_zone<T>::value)>
+  void format_tz_name(const T&) {
+    out_ = std::copy_n(utc(), 3, out_);
+  }
+
+  void format_localized(char format, char modifier = 0) {
+    out_ = write<Char>(out_, tm_, loc_, format, modifier);
+  }
+
+ public:
+  tm_writer(const std::locale& loc, OutputIt out, const std::tm& tm,
+            const Duration* subsecs = nullptr)
+      : loc_(loc),
+        is_classic_(loc_ == get_classic_locale()),
+        out_(out),
+        subsecs_(subsecs),
+        tm_(tm) {}
+
+  auto out() const -> OutputIt { return out_; }
+
+  FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {
+    out_ = copy<Char>(begin, end, out_);
+  }
+
+  void on_abbr_weekday() {
+    if (is_classic_)
+      out_ = write(out_, tm_wday_short_name(tm_wday()));
+    else
+      format_localized('a');
+  }
+  void on_full_weekday() {
+    if (is_classic_)
+      out_ = write(out_, tm_wday_full_name(tm_wday()));
+    else
+      format_localized('A');
+  }
+  void on_dec0_weekday(numeric_system ns) {
+    if (is_classic_ || ns == numeric_system::standard) return write1(tm_wday());
+    format_localized('w', 'O');
+  }
+  void on_dec1_weekday(numeric_system ns) {
+    if (is_classic_ || ns == numeric_system::standard) {
+      auto wday = tm_wday();
+      write1(wday == 0 ? days_per_week : wday);
+    } else {
+      format_localized('u', 'O');
+    }
+  }
+
+  void on_abbr_month() {
+    if (is_classic_)
+      out_ = write(out_, tm_mon_short_name(tm_mon()));
+    else
+      format_localized('b');
+  }
+  void on_full_month() {
+    if (is_classic_)
+      out_ = write(out_, tm_mon_full_name(tm_mon()));
+    else
+      format_localized('B');
+  }
+
+  void on_datetime(numeric_system ns) {
+    if (is_classic_) {
+      on_abbr_weekday();
+      *out_++ = ' ';
+      on_abbr_month();
+      *out_++ = ' ';
+      on_day_of_month(numeric_system::standard, pad_type::space);
+      *out_++ = ' ';
+      on_iso_time();
+      *out_++ = ' ';
+      on_year(numeric_system::standard, pad_type::space);
+    } else {
+      format_localized('c', ns == numeric_system::standard ? '\0' : 'E');
+    }
+  }
+  void on_loc_date(numeric_system ns) {
+    if (is_classic_)
+      on_us_date();
+    else
+      format_localized('x', ns == numeric_system::standard ? '\0' : 'E');
+  }
+  void on_loc_time(numeric_system ns) {
+    if (is_classic_)
+      on_iso_time();
+    else
+      format_localized('X', ns == numeric_system::standard ? '\0' : 'E');
+  }
+  void on_us_date() {
+    char buf[8];
+    write_digit2_separated(buf, to_unsigned(tm_mon() + 1),
+                           to_unsigned(tm_mday()),
+                           to_unsigned(split_year_lower(tm_year())), '/');
+    out_ = copy<Char>(std::begin(buf), std::end(buf), out_);
+  }
+  void on_iso_date() {
+    auto year = tm_year();
+    char buf[10];
+    size_t offset = 0;
+    if (year >= 0 && year < 10000) {
+      write2digits(buf, static_cast<size_t>(year / 100));
+    } else {
+      offset = 4;
+      write_year_extended(year, pad_type::zero);
+      year = 0;
+    }
+    write_digit2_separated(buf + 2, static_cast<unsigned>(year % 100),
+                           to_unsigned(tm_mon() + 1), to_unsigned(tm_mday()),
+                           '-');
+    out_ = copy<Char>(std::begin(buf) + offset, std::end(buf), out_);
+  }
+
+  void on_utc_offset(numeric_system ns) { format_utc_offset(tm_, ns); }
+  void on_tz_name() { format_tz_name(tm_); }
+
+  void on_year(numeric_system ns, pad_type pad) {
+    if (is_classic_ || ns == numeric_system::standard)
+      return write_year(tm_year(), pad);
+    format_localized('Y', 'E');
+  }
+  void on_short_year(numeric_system ns) {
+    if (is_classic_ || ns == numeric_system::standard)
+      return write2(split_year_lower(tm_year()));
+    format_localized('y', 'O');
+  }
+  void on_offset_year() {
+    if (is_classic_) return write2(split_year_lower(tm_year()));
+    format_localized('y', 'E');
+  }
+
+  void on_century(numeric_system ns) {
+    if (is_classic_ || ns == numeric_system::standard) {
+      auto year = tm_year();
+      auto upper = year / 100;
+      if (year >= -99 && year < 0) {
+        // Zero upper on negative year.
+        *out_++ = '-';
+        *out_++ = '0';
+      } else if (upper >= 0 && upper < 100) {
+        write2(static_cast<int>(upper));
+      } else {
+        out_ = write<Char>(out_, upper);
+      }
+    } else {
+      format_localized('C', 'E');
+    }
+  }
+
+  void on_dec_month(numeric_system ns, pad_type pad) {
+    if (is_classic_ || ns == numeric_system::standard)
+      return write2(tm_mon() + 1, pad);
+    format_localized('m', 'O');
+  }
+
+  void on_dec0_week_of_year(numeric_system ns, pad_type pad) {
+    if (is_classic_ || ns == numeric_system::standard)
+      return write2((tm_yday() + days_per_week - tm_wday()) / days_per_week,
+                    pad);
+    format_localized('U', 'O');
+  }
+  void on_dec1_week_of_year(numeric_system ns, pad_type pad) {
+    if (is_classic_ || ns == numeric_system::standard) {
+      auto wday = tm_wday();
+      write2((tm_yday() + days_per_week -
+              (wday == 0 ? (days_per_week - 1) : (wday - 1))) /
+                 days_per_week,
+             pad);
+    } else {
+      format_localized('W', 'O');
+    }
+  }
+  void on_iso_week_of_year(numeric_system ns, pad_type pad) {
+    if (is_classic_ || ns == numeric_system::standard)
+      return write2(tm_iso_week_of_year(), pad);
+    format_localized('V', 'O');
+  }
+
+  void on_iso_week_based_year() {
+    write_year(tm_iso_week_year(), pad_type::zero);
+  }
+  void on_iso_week_based_short_year() {
+    write2(split_year_lower(tm_iso_week_year()));
+  }
+
+  void on_day_of_year(pad_type pad) {
+    auto yday = tm_yday() + 1;
+    auto digit1 = yday / 100;
+    if (digit1 != 0)
+      write1(digit1);
+    else
+      out_ = detail::write_padding(out_, pad);
+    write2(yday % 100, pad);
+  }
+
+  void on_day_of_month(numeric_system ns, pad_type pad) {
+    if (is_classic_ || ns == numeric_system::standard)
+      return write2(tm_mday(), pad);
+    format_localized('d', 'O');
+  }
+
+  void on_24_hour(numeric_system ns, pad_type pad) {
+    if (is_classic_ || ns == numeric_system::standard)
+      return write2(tm_hour(), pad);
+    format_localized('H', 'O');
+  }
+  void on_12_hour(numeric_system ns, pad_type pad) {
+    if (is_classic_ || ns == numeric_system::standard)
+      return write2(tm_hour12(), pad);
+    format_localized('I', 'O');
+  }
+  void on_minute(numeric_system ns, pad_type pad) {
+    if (is_classic_ || ns == numeric_system::standard)
+      return write2(tm_min(), pad);
+    format_localized('M', 'O');
+  }
+
+  void on_second(numeric_system ns, pad_type pad) {
+    if (is_classic_ || ns == numeric_system::standard) {
+      write2(tm_sec(), pad);
+      if (subsecs_) {
+        if (std::is_floating_point<typename Duration::rep>::value) {
+          auto buf = memory_buffer();
+          write_floating_seconds(buf, *subsecs_);
+          if (buf.size() > 1) {
+            // Remove the leading "0", write something like ".123".
+            out_ = copy<Char>(buf.begin() + 1, buf.end(), out_);
+          }
+        } else {
+          write_fractional_seconds<Char>(out_, *subsecs_);
+        }
+      }
+    } else {
+      // Currently no formatting of subseconds when a locale is set.
+      format_localized('S', 'O');
+    }
+  }
+
+  void on_12_hour_time() {
+    if (is_classic_) {
+      char buf[8];
+      write_digit2_separated(buf, to_unsigned(tm_hour12()),
+                             to_unsigned(tm_min()), to_unsigned(tm_sec()), ':');
+      out_ = copy<Char>(std::begin(buf), std::end(buf), out_);
+      *out_++ = ' ';
+      on_am_pm();
+    } else {
+      format_localized('r');
+    }
+  }
+  void on_24_hour_time() {
+    write2(tm_hour());
+    *out_++ = ':';
+    write2(tm_min());
+  }
+  void on_iso_time() {
+    on_24_hour_time();
+    *out_++ = ':';
+    on_second(numeric_system::standard, pad_type::zero);
+  }
+
+  void on_am_pm() {
+    if (is_classic_) {
+      *out_++ = tm_hour() < 12 ? 'A' : 'P';
+      *out_++ = 'M';
+    } else {
+      format_localized('p');
+    }
+  }
+
+  // These apply to chrono durations but not tm.
+  void on_duration_value() {}
+  void on_duration_unit() {}
+};
+
+struct chrono_format_checker : null_chrono_spec_handler<chrono_format_checker> {
+  bool has_precision_integral = false;
+
+  FMT_NORETURN inline void unsupported() { FMT_THROW(format_error("no date")); }
+
+  template <typename Char>
+  FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
+  FMT_CONSTEXPR void on_day_of_year(pad_type) {}
+  FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_second(numeric_system, pad_type) {}
+  FMT_CONSTEXPR void on_12_hour_time() {}
+  FMT_CONSTEXPR void on_24_hour_time() {}
+  FMT_CONSTEXPR void on_iso_time() {}
+  FMT_CONSTEXPR void on_am_pm() {}
+  FMT_CONSTEXPR void on_duration_value() const {
+    if (has_precision_integral)
+      FMT_THROW(format_error("precision not allowed for this argument type"));
+  }
+  FMT_CONSTEXPR void on_duration_unit() {}
+};
+
+template <typename T,
+          FMT_ENABLE_IF(std::is_integral<T>::value&& has_isfinite<T>::value)>
+inline auto isfinite(T) -> bool {
+  return true;
+}
+
+template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+inline auto mod(T x, int y) -> T {
+  return x % static_cast<T>(y);
+}
+template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+inline auto mod(T x, int y) -> T {
+  return std::fmod(x, static_cast<T>(y));
+}
+
+// If T is an integral type, maps T to its unsigned counterpart, otherwise
+// leaves it unchanged (unlike std::make_unsigned).
+template <typename T, bool INTEGRAL = std::is_integral<T>::value>
+struct make_unsigned_or_unchanged {
+  using type = T;
+};
+
+template <typename T> struct make_unsigned_or_unchanged<T, true> {
+  using type = typename std::make_unsigned<T>::type;
+};
+
+template <typename Rep, typename Period,
+          FMT_ENABLE_IF(std::is_integral<Rep>::value)>
+inline auto get_milliseconds(std::chrono::duration<Rep, Period> d)
+    -> std::chrono::duration<Rep, std::milli> {
+  // This may overflow and/or the result may not fit in the target type.
+#if FMT_SAFE_DURATION_CAST
+  using common_seconds_type =
+      typename std::common_type<decltype(d), std::chrono::seconds>::type;
+  auto d_as_common = detail::duration_cast<common_seconds_type>(d);
+  auto d_as_whole_seconds =
+      detail::duration_cast<std::chrono::seconds>(d_as_common);
+  // This conversion should be nonproblematic.
+  auto diff = d_as_common - d_as_whole_seconds;
+  auto ms = detail::duration_cast<std::chrono::duration<Rep, std::milli>>(diff);
+  return ms;
+#else
+  auto s = detail::duration_cast<std::chrono::seconds>(d);
+  return detail::duration_cast<std::chrono::milliseconds>(d - s);
+#endif
+}
+
+template <typename Char, typename Rep, typename OutputIt,
+          FMT_ENABLE_IF(std::is_integral<Rep>::value)>
+auto format_duration_value(OutputIt out, Rep val, int) -> OutputIt {
+  return write<Char>(out, val);
+}
+
+template <typename Char, typename Rep, typename OutputIt,
+          FMT_ENABLE_IF(std::is_floating_point<Rep>::value)>
+auto format_duration_value(OutputIt out, Rep val, int precision) -> OutputIt {
+  auto specs = format_specs();
+  specs.precision = precision;
+  specs.set_type(precision >= 0 ? presentation_type::fixed
+                                : presentation_type::general);
+  return write<Char>(out, val, specs);
+}
+
+template <typename Char, typename OutputIt>
+auto copy_unit(string_view unit, OutputIt out, Char) -> OutputIt {
+  return copy<Char>(unit.begin(), unit.end(), out);
+}
+
+template <typename OutputIt>
+auto copy_unit(string_view unit, OutputIt out, wchar_t) -> OutputIt {
+  // This works when wchar_t is UTF-32 because units only contain characters
+  // that have the same representation in UTF-16 and UTF-32.
+  utf8_to_utf16 u(unit);
+  return copy<wchar_t>(u.c_str(), u.c_str() + u.size(), out);
+}
+
+template <typename Char, typename Period, typename OutputIt>
+auto format_duration_unit(OutputIt out) -> OutputIt {
+  if (const char* unit = get_units<Period>())
+    return copy_unit(string_view(unit), out, Char());
+  *out++ = '[';
+  out = write<Char>(out, Period::num);
+  if (const_check(Period::den != 1)) {
+    *out++ = '/';
+    out = write<Char>(out, Period::den);
+  }
+  *out++ = ']';
+  *out++ = 's';
+  return out;
+}
+
+class get_locale {
+ private:
+  union {
+    std::locale locale_;
+  };
+  bool has_locale_ = false;
+
+ public:
+  inline get_locale(bool localized, locale_ref loc) : has_locale_(localized) {
+    if (localized)
+      ::new (&locale_) std::locale(loc.template get<std::locale>());
+  }
+  inline ~get_locale() {
+    if (has_locale_) locale_.~locale();
+  }
+  inline operator const std::locale&() const {
+    return has_locale_ ? locale_ : get_classic_locale();
+  }
+};
+
+template <typename Char, typename Rep, typename Period>
+struct duration_formatter {
+  using iterator = basic_appender<Char>;
+  iterator out;
+  // rep is unsigned to avoid overflow.
+  using rep =
+      conditional_t<std::is_integral<Rep>::value && sizeof(Rep) < sizeof(int),
+                    unsigned, typename make_unsigned_or_unchanged<Rep>::type>;
+  rep val;
+  int precision;
+  locale_ref locale;
+  bool localized = false;
+  using seconds = std::chrono::duration<rep>;
+  seconds s;
+  using milliseconds = std::chrono::duration<rep, std::milli>;
+  bool negative;
+
+  using tm_writer_type = tm_writer<iterator, Char>;
+
+  duration_formatter(iterator o, std::chrono::duration<Rep, Period> d,
+                     locale_ref loc)
+      : out(o), val(static_cast<rep>(d.count())), locale(loc), negative(false) {
+    if (d.count() < 0) {
+      val = 0 - val;
+      negative = true;
+    }
+
+    // this may overflow and/or the result may not fit in the
+    // target type.
+    // might need checked conversion (rep!=Rep)
+    s = detail::duration_cast<seconds>(std::chrono::duration<rep, Period>(val));
+  }
+
+  // returns true if nan or inf, writes to out.
+  auto handle_nan_inf() -> bool {
+    if (isfinite(val)) return false;
+    if (isnan(val)) {
+      write_nan();
+      return true;
+    }
+    // must be +-inf
+    if (val > 0)
+      std::copy_n("inf", 3, out);
+    else
+      std::copy_n("-inf", 4, out);
+    return true;
+  }
+
+  auto days() const -> Rep { return static_cast<Rep>(s.count() / 86400); }
+  auto hour() const -> Rep {
+    return static_cast<Rep>(mod((s.count() / 3600), 24));
+  }
+
+  auto hour12() const -> Rep {
+    Rep hour = static_cast<Rep>(mod((s.count() / 3600), 12));
+    return hour <= 0 ? 12 : hour;
+  }
+
+  auto minute() const -> Rep {
+    return static_cast<Rep>(mod((s.count() / 60), 60));
+  }
+  auto second() const -> Rep { return static_cast<Rep>(mod(s.count(), 60)); }
+
+  auto time() const -> std::tm {
+    auto time = std::tm();
+    time.tm_hour = to_nonnegative_int(hour(), 24);
+    time.tm_min = to_nonnegative_int(minute(), 60);
+    time.tm_sec = to_nonnegative_int(second(), 60);
+    return time;
+  }
+
+  void write_sign() {
+    if (!negative) return;
+    *out++ = '-';
+    negative = false;
+  }
+
+  void write(Rep value, int width, pad_type pad = pad_type::zero) {
+    write_sign();
+    if (isnan(value)) return write_nan();
+    uint32_or_64_or_128_t<int> n =
+        to_unsigned(to_nonnegative_int(value, max_value<int>()));
+    int num_digits = detail::count_digits(n);
+    if (width > num_digits) {
+      out = detail::write_padding(out, pad, width - num_digits);
+    }
+    out = format_decimal<Char>(out, n, num_digits);
+  }
+
+  void write_nan() { std::copy_n("nan", 3, out); }
+
+  template <typename Callback, typename... Args>
+  void format_tm(const tm& time, Callback cb, Args... args) {
+    if (isnan(val)) return write_nan();
+    get_locale loc(localized, locale);
+    auto w = tm_writer_type(loc, out, time);
+    (w.*cb)(args...);
+    out = w.out();
+  }
+
+  void on_text(const Char* begin, const Char* end) {
+    copy<Char>(begin, end, out);
+  }
+
+  // These are not implemented because durations don't have date information.
+  void on_abbr_weekday() {}
+  void on_full_weekday() {}
+  void on_dec0_weekday(numeric_system) {}
+  void on_dec1_weekday(numeric_system) {}
+  void on_abbr_month() {}
+  void on_full_month() {}
+  void on_datetime(numeric_system) {}
+  void on_loc_date(numeric_system) {}
+  void on_loc_time(numeric_system) {}
+  void on_us_date() {}
+  void on_iso_date() {}
+  void on_utc_offset(numeric_system) {}
+  void on_tz_name() {}
+  void on_year(numeric_system, pad_type) {}
+  void on_short_year(numeric_system) {}
+  void on_offset_year() {}
+  void on_century(numeric_system) {}
+  void on_iso_week_based_year() {}
+  void on_iso_week_based_short_year() {}
+  void on_dec_month(numeric_system, pad_type) {}
+  void on_dec0_week_of_year(numeric_system, pad_type) {}
+  void on_dec1_week_of_year(numeric_system, pad_type) {}
+  void on_iso_week_of_year(numeric_system, pad_type) {}
+  void on_day_of_month(numeric_system, pad_type) {}
+
+  void on_day_of_year(pad_type) {
+    if (handle_nan_inf()) return;
+    write(days(), 0);
+  }
+
+  void on_24_hour(numeric_system ns, pad_type pad) {
+    if (handle_nan_inf()) return;
+
+    if (ns == numeric_system::standard) return write(hour(), 2, pad);
+    auto time = tm();
+    time.tm_hour = to_nonnegative_int(hour(), 24);
+    format_tm(time, &tm_writer_type::on_24_hour, ns, pad);
+  }
+
+  void on_12_hour(numeric_system ns, pad_type pad) {
+    if (handle_nan_inf()) return;
+
+    if (ns == numeric_system::standard) return write(hour12(), 2, pad);
+    auto time = tm();
+    time.tm_hour = to_nonnegative_int(hour12(), 12);
+    format_tm(time, &tm_writer_type::on_12_hour, ns, pad);
+  }
+
+  void on_minute(numeric_system ns, pad_type pad) {
+    if (handle_nan_inf()) return;
+
+    if (ns == numeric_system::standard) return write(minute(), 2, pad);
+    auto time = tm();
+    time.tm_min = to_nonnegative_int(minute(), 60);
+    format_tm(time, &tm_writer_type::on_minute, ns, pad);
+  }
+
+  void on_second(numeric_system ns, pad_type pad) {
+    if (handle_nan_inf()) return;
+
+    if (ns == numeric_system::standard) {
+      if (std::is_floating_point<rep>::value) {
+        auto buf = memory_buffer();
+        write_floating_seconds(buf, std::chrono::duration<rep, Period>(val),
+                               precision);
+        if (negative) *out++ = '-';
+        if (buf.size() < 2 || buf[1] == '.')
+          out = detail::write_padding(out, pad);
+        out = copy<Char>(buf.begin(), buf.end(), out);
+      } else {
+        write(second(), 2, pad);
+        write_fractional_seconds<Char>(
+            out, std::chrono::duration<rep, Period>(val), precision);
+      }
+      return;
+    }
+    auto time = tm();
+    time.tm_sec = to_nonnegative_int(second(), 60);
+    format_tm(time, &tm_writer_type::on_second, ns, pad);
+  }
+
+  void on_12_hour_time() {
+    if (handle_nan_inf()) return;
+    format_tm(time(), &tm_writer_type::on_12_hour_time);
+  }
+
+  void on_24_hour_time() {
+    if (handle_nan_inf()) {
+      *out++ = ':';
+      handle_nan_inf();
+      return;
+    }
+
+    write(hour(), 2);
+    *out++ = ':';
+    write(minute(), 2);
+  }
+
+  void on_iso_time() {
+    on_24_hour_time();
+    *out++ = ':';
+    if (handle_nan_inf()) return;
+    on_second(numeric_system::standard, pad_type::zero);
+  }
+
+  void on_am_pm() {
+    if (handle_nan_inf()) return;
+    format_tm(time(), &tm_writer_type::on_am_pm);
+  }
+
+  void on_duration_value() {
+    if (handle_nan_inf()) return;
+    write_sign();
+    out = format_duration_value<Char>(out, val, precision);
+  }
+
+  void on_duration_unit() { out = format_duration_unit<Char, Period>(out); }
+};
+
+}  // namespace detail
+
+#if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907
+using weekday = std::chrono::weekday;
+using day = std::chrono::day;
+using month = std::chrono::month;
+using year = std::chrono::year;
+using year_month_day = std::chrono::year_month_day;
+#else
+// A fallback version of weekday.
+class weekday {
+ private:
+  unsigned char value_;
+
+ public:
+  weekday() = default;
+  constexpr explicit weekday(unsigned wd) noexcept
+      : value_(static_cast<unsigned char>(wd != 7 ? wd : 0)) {}
+  constexpr auto c_encoding() const noexcept -> unsigned { return value_; }
+};
+
+class day {
+ private:
+  unsigned char value_;
+
+ public:
+  day() = default;
+  constexpr explicit day(unsigned d) noexcept
+      : value_(static_cast<unsigned char>(d)) {}
+  constexpr explicit operator unsigned() const noexcept { return value_; }
+};
+
+class month {
+ private:
+  unsigned char value_;
+
+ public:
+  month() = default;
+  constexpr explicit month(unsigned m) noexcept
+      : value_(static_cast<unsigned char>(m)) {}
+  constexpr explicit operator unsigned() const noexcept { return value_; }
+};
+
+class year {
+ private:
+  int value_;
+
+ public:
+  year() = default;
+  constexpr explicit year(int y) noexcept : value_(y) {}
+  constexpr explicit operator int() const noexcept { return value_; }
+};
+
+class year_month_day {
+ private:
+  fmt::year year_;
+  fmt::month month_;
+  fmt::day day_;
+
+ public:
+  year_month_day() = default;
+  constexpr year_month_day(const year& y, const month& m, const day& d) noexcept
+      : year_(y), month_(m), day_(d) {}
+  constexpr auto year() const noexcept -> fmt::year { return year_; }
+  constexpr auto month() const noexcept -> fmt::month { return month_; }
+  constexpr auto day() const noexcept -> fmt::day { return day_; }
+};
+#endif  // __cpp_lib_chrono >= 201907
+
+template <typename Char>
+struct formatter<weekday, Char> : private formatter<std::tm, Char> {
+ private:
+  bool use_tm_formatter_ = false;
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    auto it = ctx.begin(), end = ctx.end();
+    if (it != end && *it == 'L') {
+      ++it;
+      this->set_localized();
+    }
+    use_tm_formatter_ = it != end && *it != '}';
+    return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;
+  }
+
+  template <typename FormatContext>
+  auto format(weekday wd, FormatContext& ctx) const -> decltype(ctx.out()) {
+    auto time = std::tm();
+    time.tm_wday = static_cast<int>(wd.c_encoding());
+    if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);
+    detail::get_locale loc(this->localized(), ctx.locale());
+    auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
+    w.on_abbr_weekday();
+    return w.out();
+  }
+};
+
+template <typename Char>
+struct formatter<day, Char> : private formatter<std::tm, Char> {
+ private:
+  bool use_tm_formatter_ = false;
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    auto it = ctx.begin(), end = ctx.end();
+    use_tm_formatter_ = it != end && *it != '}';
+    return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;
+  }
+
+  template <typename FormatContext>
+  auto format(day d, FormatContext& ctx) const -> decltype(ctx.out()) {
+    auto time = std::tm();
+    time.tm_mday = static_cast<int>(static_cast<unsigned>(d));
+    if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);
+    detail::get_locale loc(false, ctx.locale());
+    auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
+    w.on_day_of_month(detail::numeric_system::standard, detail::pad_type::zero);
+    return w.out();
+  }
+};
+
+template <typename Char>
+struct formatter<month, Char> : private formatter<std::tm, Char> {
+ private:
+  bool use_tm_formatter_ = false;
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    auto it = ctx.begin(), end = ctx.end();
+    if (it != end && *it == 'L') {
+      ++it;
+      this->set_localized();
+    }
+    use_tm_formatter_ = it != end && *it != '}';
+    return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;
+  }
+
+  template <typename FormatContext>
+  auto format(month m, FormatContext& ctx) const -> decltype(ctx.out()) {
+    auto time = std::tm();
+    time.tm_mon = static_cast<int>(static_cast<unsigned>(m)) - 1;
+    if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);
+    detail::get_locale loc(this->localized(), ctx.locale());
+    auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
+    w.on_abbr_month();
+    return w.out();
+  }
+};
+
+template <typename Char>
+struct formatter<year, Char> : private formatter<std::tm, Char> {
+ private:
+  bool use_tm_formatter_ = false;
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    auto it = ctx.begin(), end = ctx.end();
+    use_tm_formatter_ = it != end && *it != '}';
+    return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;
+  }
+
+  template <typename FormatContext>
+  auto format(year y, FormatContext& ctx) const -> decltype(ctx.out()) {
+    auto time = std::tm();
+    time.tm_year = static_cast<int>(y) - 1900;
+    if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);
+    detail::get_locale loc(false, ctx.locale());
+    auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
+    w.on_year(detail::numeric_system::standard, detail::pad_type::zero);
+    return w.out();
+  }
+};
+
+template <typename Char>
+struct formatter<year_month_day, Char> : private formatter<std::tm, Char> {
+ private:
+  bool use_tm_formatter_ = false;
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    auto it = ctx.begin(), end = ctx.end();
+    use_tm_formatter_ = it != end && *it != '}';
+    return use_tm_formatter_ ? formatter<std::tm, Char>::parse(ctx) : it;
+  }
+
+  template <typename FormatContext>
+  auto format(year_month_day val, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    auto time = std::tm();
+    time.tm_year = static_cast<int>(val.year()) - 1900;
+    time.tm_mon = static_cast<int>(static_cast<unsigned>(val.month())) - 1;
+    time.tm_mday = static_cast<int>(static_cast<unsigned>(val.day()));
+    if (use_tm_formatter_) return formatter<std::tm, Char>::format(time, ctx);
+    detail::get_locale loc(true, ctx.locale());
+    auto w = detail::tm_writer<decltype(ctx.out()), Char>(loc, ctx.out(), time);
+    w.on_iso_date();
+    return w.out();
+  }
+};
+
+template <typename Rep, typename Period, typename Char>
+struct formatter<std::chrono::duration<Rep, Period>, Char> {
+ private:
+  format_specs specs_;
+  detail::arg_ref<Char> width_ref_;
+  detail::arg_ref<Char> precision_ref_;
+  basic_string_view<Char> fmt_;
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    auto it = ctx.begin(), end = ctx.end();
+    if (it == end || *it == '}') return it;
+
+    it = detail::parse_align(it, end, specs_);
+    if (it == end) return it;
+
+    Char c = *it;
+    if ((c >= '0' && c <= '9') || c == '{') {
+      it = detail::parse_width(it, end, specs_, width_ref_, ctx);
+      if (it == end) return it;
+    }
+
+    auto checker = detail::chrono_format_checker();
+    if (*it == '.') {
+      checker.has_precision_integral = !std::is_floating_point<Rep>::value;
+      it = detail::parse_precision(it, end, specs_, precision_ref_, ctx);
+    }
+    if (it != end && *it == 'L') {
+      specs_.set_localized();
+      ++it;
+    }
+    end = detail::parse_chrono_format(it, end, checker);
+    fmt_ = {it, detail::to_unsigned(end - it)};
+    return end;
+  }
+
+  template <typename FormatContext>
+  auto format(std::chrono::duration<Rep, Period> d, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    auto specs = specs_;
+    auto precision = specs.precision;
+    specs.precision = -1;
+    auto begin = fmt_.begin(), end = fmt_.end();
+    // As a possible future optimization, we could avoid extra copying if width
+    // is not specified.
+    auto buf = basic_memory_buffer<Char>();
+    auto out = basic_appender<Char>(buf);
+    detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,
+                                ctx);
+    detail::handle_dynamic_spec(specs.dynamic_precision(), precision,
+                                precision_ref_, ctx);
+    if (begin == end || *begin == '}') {
+      out = detail::format_duration_value<Char>(out, d.count(), precision);
+      detail::format_duration_unit<Char, Period>(out);
+    } else {
+      auto f =
+          detail::duration_formatter<Char, Rep, Period>(out, d, ctx.locale());
+      f.precision = precision;
+      f.localized = specs_.localized();
+      detail::parse_chrono_format(begin, end, f);
+    }
+    return detail::write(
+        ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs);
+  }
+};
+
+template <typename Char> struct formatter<std::tm, Char> {
+ private:
+  format_specs specs_;
+  detail::arg_ref<Char> width_ref_;
+  basic_string_view<Char> fmt_ =
+      detail::string_literal<Char, '%', 'F', ' ', '%', 'T'>();
+
+ protected:
+  auto localized() const -> bool { return specs_.localized(); }
+  FMT_CONSTEXPR void set_localized() { specs_.set_localized(); }
+
+  FMT_CONSTEXPR auto do_parse(parse_context<Char>& ctx, bool has_timezone)
+      -> const Char* {
+    auto it = ctx.begin(), end = ctx.end();
+    if (it == end || *it == '}') return it;
+
+    it = detail::parse_align(it, end, specs_);
+    if (it == end) return it;
+
+    Char c = *it;
+    if ((c >= '0' && c <= '9') || c == '{') {
+      it = detail::parse_width(it, end, specs_, width_ref_, ctx);
+      if (it == end) return it;
+    }
+
+    if (*it == 'L') {
+      specs_.set_localized();
+      ++it;
+    }
+
+    end = detail::parse_chrono_format(it, end,
+                                      detail::tm_format_checker(has_timezone));
+    // Replace the default format string only if the new spec is not empty.
+    if (end != it) fmt_ = {it, detail::to_unsigned(end - it)};
+    return end;
+  }
+
+  template <typename Duration, typename FormatContext>
+  auto do_format(const std::tm& tm, FormatContext& ctx,
+                 const Duration* subsecs) const -> decltype(ctx.out()) {
+    auto specs = specs_;
+    auto buf = basic_memory_buffer<Char>();
+    auto out = basic_appender<Char>(buf);
+    detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,
+                                ctx);
+
+    auto loc_ref = specs.localized() ? ctx.locale() : locale_ref();
+    detail::get_locale loc(static_cast<bool>(loc_ref), loc_ref);
+    auto w = detail::tm_writer<basic_appender<Char>, Char, Duration>(
+        loc, out, tm, subsecs);
+    detail::parse_chrono_format(fmt_.begin(), fmt_.end(), w);
+    return detail::write(
+        ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs);
+  }
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    return do_parse(ctx, detail::has_tm_gmtoff<std::tm>::value);
+  }
+
+  template <typename FormatContext>
+  auto format(const std::tm& tm, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    return do_format<std::chrono::seconds>(tm, ctx, nullptr);
+  }
+};
+
+// DEPRECATED! Reversed order of template parameters.
+template <typename Char, typename Duration>
+struct formatter<sys_time<Duration>, Char> : private formatter<std::tm, Char> {
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    return this->do_parse(ctx, true);
+  }
+
+  template <typename FormatContext>
+  auto format(sys_time<Duration> val, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    std::tm tm = gmtime(val);
+    using period = typename Duration::period;
+    if (detail::const_check(
+            period::num == 1 && period::den == 1 &&
+            !std::is_floating_point<typename Duration::rep>::value)) {
+      detail::set_tm_zone(tm, detail::utc());
+      return formatter<std::tm, Char>::format(tm, ctx);
+    }
+    Duration epoch = val.time_since_epoch();
+    Duration subsecs = detail::duration_cast<Duration>(
+        epoch - detail::duration_cast<std::chrono::seconds>(epoch));
+    if (subsecs.count() < 0) {
+      auto second = detail::duration_cast<Duration>(std::chrono::seconds(1));
+      if (tm.tm_sec != 0) {
+        --tm.tm_sec;
+      } else {
+        tm = gmtime(val - second);
+        detail::set_tm_zone(tm, detail::utc());
+      }
+      subsecs += second;
+    }
+    return formatter<std::tm, Char>::do_format(tm, ctx, &subsecs);
+  }
+};
+
+template <typename Duration, typename Char>
+struct formatter<utc_time<Duration>, Char>
+    : formatter<sys_time<Duration>, Char> {
+  template <typename FormatContext>
+  auto format(utc_time<Duration> val, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    return formatter<sys_time<Duration>, Char>::format(
+        detail::utc_clock::to_sys(val), ctx);
+  }
+};
+
+template <typename Duration, typename Char>
+struct formatter<local_time<Duration>, Char>
+    : private formatter<std::tm, Char> {
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    return this->do_parse(ctx, false);
+  }
+
+  template <typename FormatContext>
+  auto format(local_time<Duration> val, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    auto time_since_epoch = val.time_since_epoch();
+    auto seconds_since_epoch =
+        detail::duration_cast<std::chrono::seconds>(time_since_epoch);
+    // Use gmtime to prevent time zone conversion since local_time has an
+    // unspecified time zone.
+    std::tm t = gmtime(seconds_since_epoch.count());
+    using period = typename Duration::period;
+    if (period::num == 1 && period::den == 1 &&
+        !std::is_floating_point<typename Duration::rep>::value) {
+      return formatter<std::tm, Char>::format(t, ctx);
+    }
+    auto subsecs =
+        detail::duration_cast<Duration>(time_since_epoch - seconds_since_epoch);
+    return formatter<std::tm, Char>::do_format(t, ctx, &subsecs);
+  }
+};
+
+FMT_END_EXPORT
+FMT_END_NAMESPACE
+
+#endif  // FMT_CHRONO_H_

+ 637 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/color.h

@@ -0,0 +1,637 @@
+// Formatting library for C++ - color support
+//
+// Copyright (c) 2018 - present, Victor Zverovich and fmt contributors
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_COLOR_H_
+#define FMT_COLOR_H_
+
+#include "format.h"
+
+FMT_BEGIN_NAMESPACE
+FMT_BEGIN_EXPORT
+
+enum class color : uint32_t {
+  alice_blue = 0xF0F8FF,               // rgb(240,248,255)
+  antique_white = 0xFAEBD7,            // rgb(250,235,215)
+  aqua = 0x00FFFF,                     // rgb(0,255,255)
+  aquamarine = 0x7FFFD4,               // rgb(127,255,212)
+  azure = 0xF0FFFF,                    // rgb(240,255,255)
+  beige = 0xF5F5DC,                    // rgb(245,245,220)
+  bisque = 0xFFE4C4,                   // rgb(255,228,196)
+  black = 0x000000,                    // rgb(0,0,0)
+  blanched_almond = 0xFFEBCD,          // rgb(255,235,205)
+  blue = 0x0000FF,                     // rgb(0,0,255)
+  blue_violet = 0x8A2BE2,              // rgb(138,43,226)
+  brown = 0xA52A2A,                    // rgb(165,42,42)
+  burly_wood = 0xDEB887,               // rgb(222,184,135)
+  cadet_blue = 0x5F9EA0,               // rgb(95,158,160)
+  chartreuse = 0x7FFF00,               // rgb(127,255,0)
+  chocolate = 0xD2691E,                // rgb(210,105,30)
+  coral = 0xFF7F50,                    // rgb(255,127,80)
+  cornflower_blue = 0x6495ED,          // rgb(100,149,237)
+  cornsilk = 0xFFF8DC,                 // rgb(255,248,220)
+  crimson = 0xDC143C,                  // rgb(220,20,60)
+  cyan = 0x00FFFF,                     // rgb(0,255,255)
+  dark_blue = 0x00008B,                // rgb(0,0,139)
+  dark_cyan = 0x008B8B,                // rgb(0,139,139)
+  dark_golden_rod = 0xB8860B,          // rgb(184,134,11)
+  dark_gray = 0xA9A9A9,                // rgb(169,169,169)
+  dark_green = 0x006400,               // rgb(0,100,0)
+  dark_khaki = 0xBDB76B,               // rgb(189,183,107)
+  dark_magenta = 0x8B008B,             // rgb(139,0,139)
+  dark_olive_green = 0x556B2F,         // rgb(85,107,47)
+  dark_orange = 0xFF8C00,              // rgb(255,140,0)
+  dark_orchid = 0x9932CC,              // rgb(153,50,204)
+  dark_red = 0x8B0000,                 // rgb(139,0,0)
+  dark_salmon = 0xE9967A,              // rgb(233,150,122)
+  dark_sea_green = 0x8FBC8F,           // rgb(143,188,143)
+  dark_slate_blue = 0x483D8B,          // rgb(72,61,139)
+  dark_slate_gray = 0x2F4F4F,          // rgb(47,79,79)
+  dark_turquoise = 0x00CED1,           // rgb(0,206,209)
+  dark_violet = 0x9400D3,              // rgb(148,0,211)
+  deep_pink = 0xFF1493,                // rgb(255,20,147)
+  deep_sky_blue = 0x00BFFF,            // rgb(0,191,255)
+  dim_gray = 0x696969,                 // rgb(105,105,105)
+  dodger_blue = 0x1E90FF,              // rgb(30,144,255)
+  fire_brick = 0xB22222,               // rgb(178,34,34)
+  floral_white = 0xFFFAF0,             // rgb(255,250,240)
+  forest_green = 0x228B22,             // rgb(34,139,34)
+  fuchsia = 0xFF00FF,                  // rgb(255,0,255)
+  gainsboro = 0xDCDCDC,                // rgb(220,220,220)
+  ghost_white = 0xF8F8FF,              // rgb(248,248,255)
+  gold = 0xFFD700,                     // rgb(255,215,0)
+  golden_rod = 0xDAA520,               // rgb(218,165,32)
+  gray = 0x808080,                     // rgb(128,128,128)
+  green = 0x008000,                    // rgb(0,128,0)
+  green_yellow = 0xADFF2F,             // rgb(173,255,47)
+  honey_dew = 0xF0FFF0,                // rgb(240,255,240)
+  hot_pink = 0xFF69B4,                 // rgb(255,105,180)
+  indian_red = 0xCD5C5C,               // rgb(205,92,92)
+  indigo = 0x4B0082,                   // rgb(75,0,130)
+  ivory = 0xFFFFF0,                    // rgb(255,255,240)
+  khaki = 0xF0E68C,                    // rgb(240,230,140)
+  lavender = 0xE6E6FA,                 // rgb(230,230,250)
+  lavender_blush = 0xFFF0F5,           // rgb(255,240,245)
+  lawn_green = 0x7CFC00,               // rgb(124,252,0)
+  lemon_chiffon = 0xFFFACD,            // rgb(255,250,205)
+  light_blue = 0xADD8E6,               // rgb(173,216,230)
+  light_coral = 0xF08080,              // rgb(240,128,128)
+  light_cyan = 0xE0FFFF,               // rgb(224,255,255)
+  light_golden_rod_yellow = 0xFAFAD2,  // rgb(250,250,210)
+  light_gray = 0xD3D3D3,               // rgb(211,211,211)
+  light_green = 0x90EE90,              // rgb(144,238,144)
+  light_pink = 0xFFB6C1,               // rgb(255,182,193)
+  light_salmon = 0xFFA07A,             // rgb(255,160,122)
+  light_sea_green = 0x20B2AA,          // rgb(32,178,170)
+  light_sky_blue = 0x87CEFA,           // rgb(135,206,250)
+  light_slate_gray = 0x778899,         // rgb(119,136,153)
+  light_steel_blue = 0xB0C4DE,         // rgb(176,196,222)
+  light_yellow = 0xFFFFE0,             // rgb(255,255,224)
+  lime = 0x00FF00,                     // rgb(0,255,0)
+  lime_green = 0x32CD32,               // rgb(50,205,50)
+  linen = 0xFAF0E6,                    // rgb(250,240,230)
+  magenta = 0xFF00FF,                  // rgb(255,0,255)
+  maroon = 0x800000,                   // rgb(128,0,0)
+  medium_aquamarine = 0x66CDAA,        // rgb(102,205,170)
+  medium_blue = 0x0000CD,              // rgb(0,0,205)
+  medium_orchid = 0xBA55D3,            // rgb(186,85,211)
+  medium_purple = 0x9370DB,            // rgb(147,112,219)
+  medium_sea_green = 0x3CB371,         // rgb(60,179,113)
+  medium_slate_blue = 0x7B68EE,        // rgb(123,104,238)
+  medium_spring_green = 0x00FA9A,      // rgb(0,250,154)
+  medium_turquoise = 0x48D1CC,         // rgb(72,209,204)
+  medium_violet_red = 0xC71585,        // rgb(199,21,133)
+  midnight_blue = 0x191970,            // rgb(25,25,112)
+  mint_cream = 0xF5FFFA,               // rgb(245,255,250)
+  misty_rose = 0xFFE4E1,               // rgb(255,228,225)
+  moccasin = 0xFFE4B5,                 // rgb(255,228,181)
+  navajo_white = 0xFFDEAD,             // rgb(255,222,173)
+  navy = 0x000080,                     // rgb(0,0,128)
+  old_lace = 0xFDF5E6,                 // rgb(253,245,230)
+  olive = 0x808000,                    // rgb(128,128,0)
+  olive_drab = 0x6B8E23,               // rgb(107,142,35)
+  orange = 0xFFA500,                   // rgb(255,165,0)
+  orange_red = 0xFF4500,               // rgb(255,69,0)
+  orchid = 0xDA70D6,                   // rgb(218,112,214)
+  pale_golden_rod = 0xEEE8AA,          // rgb(238,232,170)
+  pale_green = 0x98FB98,               // rgb(152,251,152)
+  pale_turquoise = 0xAFEEEE,           // rgb(175,238,238)
+  pale_violet_red = 0xDB7093,          // rgb(219,112,147)
+  papaya_whip = 0xFFEFD5,              // rgb(255,239,213)
+  peach_puff = 0xFFDAB9,               // rgb(255,218,185)
+  peru = 0xCD853F,                     // rgb(205,133,63)
+  pink = 0xFFC0CB,                     // rgb(255,192,203)
+  plum = 0xDDA0DD,                     // rgb(221,160,221)
+  powder_blue = 0xB0E0E6,              // rgb(176,224,230)
+  purple = 0x800080,                   // rgb(128,0,128)
+  rebecca_purple = 0x663399,           // rgb(102,51,153)
+  red = 0xFF0000,                      // rgb(255,0,0)
+  rosy_brown = 0xBC8F8F,               // rgb(188,143,143)
+  royal_blue = 0x4169E1,               // rgb(65,105,225)
+  saddle_brown = 0x8B4513,             // rgb(139,69,19)
+  salmon = 0xFA8072,                   // rgb(250,128,114)
+  sandy_brown = 0xF4A460,              // rgb(244,164,96)
+  sea_green = 0x2E8B57,                // rgb(46,139,87)
+  sea_shell = 0xFFF5EE,                // rgb(255,245,238)
+  sienna = 0xA0522D,                   // rgb(160,82,45)
+  silver = 0xC0C0C0,                   // rgb(192,192,192)
+  sky_blue = 0x87CEEB,                 // rgb(135,206,235)
+  slate_blue = 0x6A5ACD,               // rgb(106,90,205)
+  slate_gray = 0x708090,               // rgb(112,128,144)
+  snow = 0xFFFAFA,                     // rgb(255,250,250)
+  spring_green = 0x00FF7F,             // rgb(0,255,127)
+  steel_blue = 0x4682B4,               // rgb(70,130,180)
+  tan = 0xD2B48C,                      // rgb(210,180,140)
+  teal = 0x008080,                     // rgb(0,128,128)
+  thistle = 0xD8BFD8,                  // rgb(216,191,216)
+  tomato = 0xFF6347,                   // rgb(255,99,71)
+  turquoise = 0x40E0D0,                // rgb(64,224,208)
+  violet = 0xEE82EE,                   // rgb(238,130,238)
+  wheat = 0xF5DEB3,                    // rgb(245,222,179)
+  white = 0xFFFFFF,                    // rgb(255,255,255)
+  white_smoke = 0xF5F5F5,              // rgb(245,245,245)
+  yellow = 0xFFFF00,                   // rgb(255,255,0)
+  yellow_green = 0x9ACD32              // rgb(154,205,50)
+};                                     // enum class color
+
+enum class terminal_color : uint8_t {
+  black = 30,
+  red,
+  green,
+  yellow,
+  blue,
+  magenta,
+  cyan,
+  white,
+  bright_black = 90,
+  bright_red,
+  bright_green,
+  bright_yellow,
+  bright_blue,
+  bright_magenta,
+  bright_cyan,
+  bright_white
+};
+
+enum class emphasis : uint8_t {
+  bold = 1,
+  faint = 1 << 1,
+  italic = 1 << 2,
+  underline = 1 << 3,
+  blink = 1 << 4,
+  reverse = 1 << 5,
+  conceal = 1 << 6,
+  strikethrough = 1 << 7,
+};
+
+// rgb is a struct for red, green and blue colors.
+// Using the name "rgb" makes some editors show the color in a tooltip.
+struct rgb {
+  constexpr rgb() : r(0), g(0), b(0) {}
+  constexpr rgb(uint8_t r_, uint8_t g_, uint8_t b_) : r(r_), g(g_), b(b_) {}
+  constexpr rgb(uint32_t hex)
+      : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b(hex & 0xFF) {}
+  constexpr rgb(color hex)
+      : r((uint32_t(hex) >> 16) & 0xFF),
+        g((uint32_t(hex) >> 8) & 0xFF),
+        b(uint32_t(hex) & 0xFF) {}
+  uint8_t r;
+  uint8_t g;
+  uint8_t b;
+};
+
+namespace detail {
+
+// A bit-packed variant of an RGB color, a terminal color, or unset color.
+// see text_style for the bit-packing scheme.
+struct color_type {
+  constexpr color_type() noexcept = default;
+  constexpr color_type(color rgb_color) noexcept
+      : value_(static_cast<uint32_t>(rgb_color) | (1 << 24)) {}
+  constexpr color_type(rgb rgb_color) noexcept
+      : color_type(static_cast<color>(
+            (static_cast<uint32_t>(rgb_color.r) << 16) |
+            (static_cast<uint32_t>(rgb_color.g) << 8) | rgb_color.b)) {}
+  constexpr color_type(terminal_color term_color) noexcept
+      : value_(static_cast<uint32_t>(term_color) | (3 << 24)) {}
+
+  constexpr auto is_terminal_color() const noexcept -> bool {
+    return (value_ & (1 << 25)) != 0;
+  }
+
+  constexpr auto value() const noexcept -> uint32_t {
+    return value_ & 0xFFFFFF;
+  }
+
+  constexpr color_type(uint32_t value) noexcept : value_(value) {}
+
+  uint32_t value_ = 0;
+};
+}  // namespace detail
+
+/// A text style consisting of foreground and background colors and emphasis.
+class text_style {
+  // The information is packed as follows:
+  // ┌──┐
+  // │ 0│─┐
+  // │..│ ├── foreground color value
+  // │23│─┘
+  // ├──┤
+  // │24│─┬── discriminator for the above value. 00 if unset, 01 if it's
+  // │25│─┘   an RGB color, or 11 if it's a terminal color (10 is unused)
+  // ├──┤
+  // │26│──── overflow bit, always zero (see below)
+  // ├──┤
+  // │27│─┐
+  // │..│ │
+  // │50│ │
+  // ├──┤ │
+  // │51│ ├── background color (same format as the foreground color)
+  // │52│ │
+  // ├──┤ │
+  // │53│─┘
+  // ├──┤
+  // │54│─┐
+  // │..│ ├── emphases
+  // │61│─┘
+  // ├──┤
+  // │62│─┬── unused
+  // │63│─┘
+  // └──┘
+  // The overflow bits are there to make operator|= efficient.
+  // When ORing, we must throw if, for either the foreground or background,
+  // one style specifies a terminal color and the other specifies any color
+  // (terminal or RGB); in other words, if one discriminator is 11 and the
+  // other is 11 or 01.
+  //
+  // We do that check by adding the styles. Consider what adding does to each
+  // possible pair of discriminators:
+  //    00 + 00 = 000
+  //    01 + 00 = 001
+  //    11 + 00 = 011
+  //    01 + 01 = 010
+  //    11 + 01 = 100 (!!)
+  //    11 + 11 = 110 (!!)
+  // In the last two cases, the ones we want to catch, the third bit——the
+  // overflow bit——is set. Bingo.
+  //
+  // We must take into account the possible carry bit from the bits
+  // before the discriminator. The only potentially problematic case is
+  // 11 + 00 = 011 (a carry bit would make it 100, not good!), but a carry
+  // bit is impossible in that case, because 00 (unset color) means the
+  // 24 bits that precede the discriminator are all zero.
+  //
+  // This test can be applied to both colors simultaneously.
+
+ public:
+  FMT_CONSTEXPR text_style(emphasis em = emphasis()) noexcept
+      : style_(static_cast<uint64_t>(em) << 54) {}
+
+  FMT_CONSTEXPR auto operator|=(text_style rhs) -> text_style& {
+    if (((style_ + rhs.style_) & ((1ULL << 26) | (1ULL << 53))) != 0)
+      report_error("can't OR a terminal color");
+    style_ |= rhs.style_;
+    return *this;
+  }
+
+  friend FMT_CONSTEXPR auto operator|(text_style lhs, text_style rhs)
+      -> text_style {
+    return lhs |= rhs;
+  }
+
+  FMT_CONSTEXPR auto operator==(text_style rhs) const noexcept -> bool {
+    return style_ == rhs.style_;
+  }
+
+  FMT_CONSTEXPR auto operator!=(text_style rhs) const noexcept -> bool {
+    return !(*this == rhs);
+  }
+
+  FMT_CONSTEXPR auto has_foreground() const noexcept -> bool {
+    return (style_ & (1 << 24)) != 0;
+  }
+  FMT_CONSTEXPR auto has_background() const noexcept -> bool {
+    return (style_ & (1ULL << 51)) != 0;
+  }
+  FMT_CONSTEXPR auto has_emphasis() const noexcept -> bool {
+    return (style_ >> 54) != 0;
+  }
+  FMT_CONSTEXPR auto get_foreground() const noexcept -> detail::color_type {
+    FMT_ASSERT(has_foreground(), "no foreground specified for this style");
+    return style_ & 0x3FFFFFF;
+  }
+  FMT_CONSTEXPR auto get_background() const noexcept -> detail::color_type {
+    FMT_ASSERT(has_background(), "no background specified for this style");
+    return (style_ >> 27) & 0x3FFFFFF;
+  }
+  FMT_CONSTEXPR auto get_emphasis() const noexcept -> emphasis {
+    FMT_ASSERT(has_emphasis(), "no emphasis specified for this style");
+    return static_cast<emphasis>(style_ >> 54);
+  }
+
+ private:
+  FMT_CONSTEXPR text_style(uint64_t style) noexcept : style_(style) {}
+
+  friend FMT_CONSTEXPR auto fg(detail::color_type foreground) noexcept
+      -> text_style;
+
+  friend FMT_CONSTEXPR auto bg(detail::color_type background) noexcept
+      -> text_style;
+
+  uint64_t style_ = 0;
+};
+
+/// Creates a text style from the foreground (text) color.
+FMT_CONSTEXPR inline auto fg(detail::color_type foreground) noexcept
+    -> text_style {
+  return foreground.value_;
+}
+
+/// Creates a text style from the background color.
+FMT_CONSTEXPR inline auto bg(detail::color_type background) noexcept
+    -> text_style {
+  return static_cast<uint64_t>(background.value_) << 27;
+}
+
+FMT_CONSTEXPR inline auto operator|(emphasis lhs, emphasis rhs) noexcept
+    -> text_style {
+  return text_style(lhs) | rhs;
+}
+
+namespace detail {
+
+template <typename Char> struct ansi_color_escape {
+  FMT_CONSTEXPR ansi_color_escape(color_type text_color,
+                                  const char* esc) noexcept {
+    // If we have a terminal color, we need to output another escape code
+    // sequence.
+    if (text_color.is_terminal_color()) {
+      bool is_background = esc == string_view("\x1b[48;2;");
+      uint32_t value = text_color.value();
+      // Background ASCII codes are the same as the foreground ones but with
+      // 10 more.
+      if (is_background) value += 10u;
+
+      buffer[size++] = static_cast<Char>('\x1b');
+      buffer[size++] = static_cast<Char>('[');
+
+      if (value >= 100u) {
+        buffer[size++] = static_cast<Char>('1');
+        value %= 100u;
+      }
+      buffer[size++] = static_cast<Char>('0' + value / 10u);
+      buffer[size++] = static_cast<Char>('0' + value % 10u);
+
+      buffer[size++] = static_cast<Char>('m');
+      return;
+    }
+
+    for (int i = 0; i < 7; i++) {
+      buffer[i] = static_cast<Char>(esc[i]);
+    }
+    rgb color(text_color.value());
+    to_esc(color.r, buffer + 7, ';');
+    to_esc(color.g, buffer + 11, ';');
+    to_esc(color.b, buffer + 15, 'm');
+    size = 19;
+  }
+  FMT_CONSTEXPR ansi_color_escape(emphasis em) noexcept {
+    uint8_t em_codes[num_emphases] = {};
+    if (has_emphasis(em, emphasis::bold)) em_codes[0] = 1;
+    if (has_emphasis(em, emphasis::faint)) em_codes[1] = 2;
+    if (has_emphasis(em, emphasis::italic)) em_codes[2] = 3;
+    if (has_emphasis(em, emphasis::underline)) em_codes[3] = 4;
+    if (has_emphasis(em, emphasis::blink)) em_codes[4] = 5;
+    if (has_emphasis(em, emphasis::reverse)) em_codes[5] = 7;
+    if (has_emphasis(em, emphasis::conceal)) em_codes[6] = 8;
+    if (has_emphasis(em, emphasis::strikethrough)) em_codes[7] = 9;
+
+    buffer[size++] = static_cast<Char>('\x1b');
+    buffer[size++] = static_cast<Char>('[');
+
+    for (size_t i = 0; i < num_emphases; ++i) {
+      if (!em_codes[i]) continue;
+      buffer[size++] = static_cast<Char>('0' + em_codes[i]);
+      buffer[size++] = static_cast<Char>(';');
+    }
+
+    buffer[size - 1] = static_cast<Char>('m');
+  }
+  FMT_CONSTEXPR operator const Char*() const noexcept { return buffer; }
+
+  FMT_CONSTEXPR auto begin() const noexcept -> const Char* { return buffer; }
+  FMT_CONSTEXPR auto end() const noexcept -> const Char* {
+    return buffer + size;
+  }
+
+ private:
+  static constexpr size_t num_emphases = 8;
+  Char buffer[7u + 4u * num_emphases];
+  size_t size = 0;
+
+  static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out,
+                                   char delimiter) noexcept {
+    out[0] = static_cast<Char>('0' + c / 100);
+    out[1] = static_cast<Char>('0' + c / 10 % 10);
+    out[2] = static_cast<Char>('0' + c % 10);
+    out[3] = static_cast<Char>(delimiter);
+  }
+  static FMT_CONSTEXPR auto has_emphasis(emphasis em, emphasis mask) noexcept
+      -> bool {
+    return static_cast<uint8_t>(em) & static_cast<uint8_t>(mask);
+  }
+};
+
+template <typename Char>
+FMT_CONSTEXPR auto make_foreground_color(color_type foreground) noexcept
+    -> ansi_color_escape<Char> {
+  return ansi_color_escape<Char>(foreground, "\x1b[38;2;");
+}
+
+template <typename Char>
+FMT_CONSTEXPR auto make_background_color(color_type background) noexcept
+    -> ansi_color_escape<Char> {
+  return ansi_color_escape<Char>(background, "\x1b[48;2;");
+}
+
+template <typename Char>
+FMT_CONSTEXPR auto make_emphasis(emphasis em) noexcept
+    -> ansi_color_escape<Char> {
+  return ansi_color_escape<Char>(em);
+}
+
+template <typename Char> inline void reset_color(buffer<Char>& buffer) {
+  auto reset_color = string_view("\x1b[0m");
+  buffer.append(reset_color.begin(), reset_color.end());
+}
+
+template <typename T> struct styled_arg : view {
+  const T& value;
+  text_style style;
+  styled_arg(const T& v, text_style s) : value(v), style(s) {}
+};
+
+template <typename Char>
+void vformat_to(buffer<Char>& buf, text_style ts, basic_string_view<Char> fmt,
+                basic_format_args<buffered_context<Char>> args) {
+  if (ts.has_emphasis()) {
+    auto emphasis = make_emphasis<Char>(ts.get_emphasis());
+    buf.append(emphasis.begin(), emphasis.end());
+  }
+  if (ts.has_foreground()) {
+    auto foreground = make_foreground_color<Char>(ts.get_foreground());
+    buf.append(foreground.begin(), foreground.end());
+  }
+  if (ts.has_background()) {
+    auto background = make_background_color<Char>(ts.get_background());
+    buf.append(background.begin(), background.end());
+  }
+  vformat_to(buf, fmt, args);
+  if (ts != text_style()) reset_color<Char>(buf);
+}
+}  // namespace detail
+
+inline void vprint(FILE* f, text_style ts, string_view fmt, format_args args) {
+  auto buf = memory_buffer();
+  detail::vformat_to(buf, ts, fmt, args);
+  print(f, FMT_STRING("{}"), string_view(buf.begin(), buf.size()));
+}
+
+/**
+ * Formats a string and prints it to the specified file stream using ANSI
+ * escape sequences to specify text formatting.
+ *
+ * **Example**:
+ *
+ *     fmt::print(fmt::emphasis::bold | fg(fmt::color::red),
+ *                "Elapsed time: {0:.2f} seconds", 1.23);
+ */
+template <typename... T>
+void print(FILE* f, text_style ts, format_string<T...> fmt, T&&... args) {
+  vprint(f, ts, fmt.str, vargs<T...>{{args...}});
+}
+
+/**
+ * Formats a string and prints it to stdout using ANSI escape sequences to
+ * specify text formatting.
+ *
+ * **Example**:
+ *
+ *     fmt::print(fmt::emphasis::bold | fg(fmt::color::red),
+ *                "Elapsed time: {0:.2f} seconds", 1.23);
+ */
+template <typename... T>
+void print(text_style ts, format_string<T...> fmt, T&&... args) {
+  return print(stdout, ts, fmt, std::forward<T>(args)...);
+}
+
+inline auto vformat(text_style ts, string_view fmt, format_args args)
+    -> std::string {
+  auto buf = memory_buffer();
+  detail::vformat_to(buf, ts, fmt, args);
+  return fmt::to_string(buf);
+}
+
+/**
+ * Formats arguments and returns the result as a string using ANSI escape
+ * sequences to specify text formatting.
+ *
+ * **Example**:
+ *
+ * ```
+ * #include <fmt/color.h>
+ * std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red),
+ *                                   "The answer is {}", 42);
+ * ```
+ */
+template <typename... T>
+inline auto format(text_style ts, format_string<T...> fmt, T&&... args)
+    -> std::string {
+  return fmt::vformat(ts, fmt.str, vargs<T...>{{args...}});
+}
+
+/// Formats a string with the given text_style and writes the output to `out`.
+template <typename OutputIt,
+          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
+auto vformat_to(OutputIt out, text_style ts, string_view fmt, format_args args)
+    -> OutputIt {
+  auto&& buf = detail::get_buffer<char>(out);
+  detail::vformat_to(buf, ts, fmt, args);
+  return detail::get_iterator(buf, out);
+}
+
+/**
+ * Formats arguments with the given text style, writes the result to the output
+ * iterator `out` and returns the iterator past the end of the output range.
+ *
+ * **Example**:
+ *
+ *     std::vector<char> out;
+ *     fmt::format_to(std::back_inserter(out),
+ *                    fmt::emphasis::bold | fg(fmt::color::red), "{}", 42);
+ */
+template <typename OutputIt, typename... T,
+          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
+inline auto format_to(OutputIt out, text_style ts, format_string<T...> fmt,
+                      T&&... args) -> OutputIt {
+  return vformat_to(out, ts, fmt.str, vargs<T...>{{args...}});
+}
+
+template <typename T, typename Char>
+struct formatter<detail::styled_arg<T>, Char> : formatter<T, Char> {
+  template <typename FormatContext>
+  auto format(const detail::styled_arg<T>& arg, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    const auto& ts = arg.style;
+    auto out = ctx.out();
+
+    bool has_style = false;
+    if (ts.has_emphasis()) {
+      has_style = true;
+      auto emphasis = detail::make_emphasis<Char>(ts.get_emphasis());
+      out = detail::copy<Char>(emphasis.begin(), emphasis.end(), out);
+    }
+    if (ts.has_foreground()) {
+      has_style = true;
+      auto foreground =
+          detail::make_foreground_color<Char>(ts.get_foreground());
+      out = detail::copy<Char>(foreground.begin(), foreground.end(), out);
+    }
+    if (ts.has_background()) {
+      has_style = true;
+      auto background =
+          detail::make_background_color<Char>(ts.get_background());
+      out = detail::copy<Char>(background.begin(), background.end(), out);
+    }
+    out = formatter<T, Char>::format(arg.value, ctx);
+    if (has_style) {
+      auto reset_color = string_view("\x1b[0m");
+      out = detail::copy<Char>(reset_color.begin(), reset_color.end(), out);
+    }
+    return out;
+  }
+};
+
+/**
+ * Returns an argument that will be formatted using ANSI escape sequences,
+ * to be used in a formatting function.
+ *
+ * **Example**:
+ *
+ *     fmt::print("Elapsed time: {0:.2f} seconds",
+ *                fmt::styled(1.23, fmt::fg(fmt::color::green) |
+ *                                  fmt::bg(fmt::color::blue)));
+ */
+template <typename T>
+FMT_CONSTEXPR auto styled(const T& value, text_style ts)
+    -> detail::styled_arg<remove_cvref_t<T>> {
+  return detail::styled_arg<remove_cvref_t<T>>{value, ts};
+}
+
+FMT_END_EXPORT
+FMT_END_NAMESPACE
+
+#endif  // FMT_COLOR_H_

+ 585 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/compile.h

@@ -0,0 +1,585 @@
+// Formatting library for C++ - experimental format string compilation
+//
+// Copyright (c) 2012 - present, Victor Zverovich and fmt contributors
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_COMPILE_H_
+#define FMT_COMPILE_H_
+
+#ifndef FMT_MODULE
+#  include <iterator>  // std::back_inserter
+#endif
+
+#include "format.h"
+
+FMT_BEGIN_NAMESPACE
+
+// A compile-time string which is compiled into fast formatting code.
+FMT_EXPORT class compiled_string {};
+
+template <typename S>
+struct is_compiled_string : std::is_base_of<compiled_string, S> {};
+
+/**
+ * Converts a string literal `s` into a format string that will be parsed at
+ * compile time and converted into efficient formatting code. Requires C++17
+ * `constexpr if` compiler support.
+ *
+ * **Example**:
+ *
+ *     // Converts 42 into std::string using the most efficient method and no
+ *     // runtime format string processing.
+ *     std::string s = fmt::format(FMT_COMPILE("{}"), 42);
+ */
+#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
+#  define FMT_COMPILE(s) FMT_STRING_IMPL(s, fmt::compiled_string)
+#else
+#  define FMT_COMPILE(s) FMT_STRING(s)
+#endif
+
+/**
+ * Converts a string literal into a format string that will be parsed at
+ * compile time and converted into efficient formatting code. Requires support
+ * for class types in constant template parameters (a C++20 feature).
+ *
+ *  **Example**:
+ *
+ *     // Converts 42 into std::string using the most efficient method and no
+ *     // runtime format string processing.
+ *     using namespace fmt::literals;
+ *     std::string s = fmt::format("{}"_cf, 42);
+ */
+#if FMT_USE_NONTYPE_TEMPLATE_ARGS
+inline namespace literals {
+template <detail::fixed_string Str> constexpr auto operator""_cf() {
+  return FMT_COMPILE(Str.data);
+}
+}  // namespace literals
+#endif
+
+namespace detail {
+
+template <typename T, typename... Tail>
+constexpr auto first(const T& value, const Tail&...) -> const T& {
+  return value;
+}
+
+#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
+template <typename... T> struct type_list {};
+
+// Returns a reference to the argument at index N from [first, rest...].
+template <int N, typename T, typename... Args>
+constexpr auto get([[maybe_unused]] const T& first,
+                   [[maybe_unused]] const Args&... rest) -> const auto& {
+  static_assert(N < 1 + sizeof...(Args), "index is out of bounds");
+  if constexpr (N == 0)
+    return first;
+  else
+    return detail::get<N - 1>(rest...);
+}
+
+#  if FMT_USE_NONTYPE_TEMPLATE_ARGS
+template <int N, typename T, typename... Args, typename Char>
+constexpr auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
+  if constexpr (is_static_named_arg<T>()) {
+    if (name == T::name) return N;
+  }
+  if constexpr (sizeof...(Args) > 0)
+    return get_arg_index_by_name<N + 1, Args...>(name);
+  (void)name;  // Workaround an MSVC bug about "unused" parameter.
+  return -1;
+}
+#  endif
+
+template <typename... Args, typename Char>
+FMT_CONSTEXPR auto get_arg_index_by_name(basic_string_view<Char> name) -> int {
+#  if FMT_USE_NONTYPE_TEMPLATE_ARGS
+  if constexpr (sizeof...(Args) > 0)
+    return get_arg_index_by_name<0, Args...>(name);
+#  endif
+  (void)name;
+  return -1;
+}
+
+template <typename Char, typename... Args>
+constexpr auto get_arg_index_by_name(basic_string_view<Char> name,
+                                     type_list<Args...>) -> int {
+  return get_arg_index_by_name<Args...>(name);
+}
+
+template <int N, typename> struct get_type_impl;
+
+template <int N, typename... Args> struct get_type_impl<N, type_list<Args...>> {
+  using type =
+      remove_cvref_t<decltype(detail::get<N>(std::declval<Args>()...))>;
+};
+
+template <int N, typename T>
+using get_type = typename get_type_impl<N, T>::type;
+
+template <typename T> struct is_compiled_format : std::false_type {};
+
+template <typename Char> struct text {
+  basic_string_view<Char> data;
+  using char_type = Char;
+
+  template <typename OutputIt, typename... T>
+  constexpr auto format(OutputIt out, const T&...) const -> OutputIt {
+    return write<Char>(out, data);
+  }
+};
+
+template <typename Char>
+struct is_compiled_format<text<Char>> : std::true_type {};
+
+template <typename Char>
+constexpr auto make_text(basic_string_view<Char> s, size_t pos, size_t size)
+    -> text<Char> {
+  return {{&s[pos], size}};
+}
+
+template <typename Char> struct code_unit {
+  Char value;
+  using char_type = Char;
+
+  template <typename OutputIt, typename... T>
+  constexpr auto format(OutputIt out, const T&...) const -> OutputIt {
+    *out++ = value;
+    return out;
+  }
+};
+
+// This ensures that the argument type is convertible to `const T&`.
+template <typename T, int N, typename... Args>
+constexpr auto get_arg_checked(const Args&... args) -> const T& {
+  const auto& arg = detail::get<N>(args...);
+  if constexpr (detail::is_named_arg<remove_cvref_t<decltype(arg)>>()) {
+    return arg.value;
+  } else {
+    return arg;
+  }
+}
+
+template <typename Char>
+struct is_compiled_format<code_unit<Char>> : std::true_type {};
+
+// A replacement field that refers to argument N.
+template <typename Char, typename V, int N> struct field {
+  using char_type = Char;
+
+  template <typename OutputIt, typename... T>
+  constexpr auto format(OutputIt out, const T&... args) const -> OutputIt {
+    const V& arg = get_arg_checked<V, N>(args...);
+    if constexpr (std::is_convertible<V, basic_string_view<Char>>::value) {
+      auto s = basic_string_view<Char>(arg);
+      return copy<Char>(s.begin(), s.end(), out);
+    } else {
+      return write<Char>(out, arg);
+    }
+  }
+};
+
+template <typename Char, typename T, int N>
+struct is_compiled_format<field<Char, T, N>> : std::true_type {};
+
+// A replacement field that refers to argument with name.
+template <typename Char> struct runtime_named_field {
+  using char_type = Char;
+  basic_string_view<Char> name;
+
+  template <typename OutputIt, typename T>
+  constexpr static auto try_format_argument(
+      OutputIt& out,
+      // [[maybe_unused]] due to unused-but-set-parameter warning in GCC 7,8,9
+      [[maybe_unused]] basic_string_view<Char> arg_name, const T& arg) -> bool {
+    if constexpr (is_named_arg<typename std::remove_cv<T>::type>::value) {
+      if (arg_name == arg.name) {
+        out = write<Char>(out, arg.value);
+        return true;
+      }
+    }
+    return false;
+  }
+
+  template <typename OutputIt, typename... T>
+  constexpr auto format(OutputIt out, const T&... args) const -> OutputIt {
+    bool found = (try_format_argument(out, name, args) || ...);
+    if (!found) {
+      FMT_THROW(format_error("argument with specified name is not found"));
+    }
+    return out;
+  }
+};
+
+template <typename Char>
+struct is_compiled_format<runtime_named_field<Char>> : std::true_type {};
+
+// A replacement field that refers to argument N and has format specifiers.
+template <typename Char, typename V, int N> struct spec_field {
+  using char_type = Char;
+  formatter<V, Char> fmt;
+
+  template <typename OutputIt, typename... T>
+  constexpr FMT_INLINE auto format(OutputIt out, const T&... args) const
+      -> OutputIt {
+    const auto& vargs =
+        fmt::make_format_args<basic_format_context<OutputIt, Char>>(args...);
+    basic_format_context<OutputIt, Char> ctx(out, vargs);
+    return fmt.format(get_arg_checked<V, N>(args...), ctx);
+  }
+};
+
+template <typename Char, typename T, int N>
+struct is_compiled_format<spec_field<Char, T, N>> : std::true_type {};
+
+template <typename L, typename R> struct concat {
+  L lhs;
+  R rhs;
+  using char_type = typename L::char_type;
+
+  template <typename OutputIt, typename... T>
+  constexpr auto format(OutputIt out, const T&... args) const -> OutputIt {
+    out = lhs.format(out, args...);
+    return rhs.format(out, args...);
+  }
+};
+
+template <typename L, typename R>
+struct is_compiled_format<concat<L, R>> : std::true_type {};
+
+template <typename L, typename R>
+constexpr auto make_concat(L lhs, R rhs) -> concat<L, R> {
+  return {lhs, rhs};
+}
+
+struct unknown_format {};
+
+template <typename Char>
+constexpr auto parse_text(basic_string_view<Char> str, size_t pos) -> size_t {
+  for (size_t size = str.size(); pos != size; ++pos) {
+    if (str[pos] == '{' || str[pos] == '}') break;
+  }
+  return pos;
+}
+
+template <typename Args, size_t POS, int ID, typename S>
+constexpr auto compile_format_string(S fmt);
+
+template <typename Args, size_t POS, int ID, typename T, typename S>
+constexpr auto parse_tail(T head, S fmt) {
+  if constexpr (POS != basic_string_view<typename S::char_type>(fmt).size()) {
+    constexpr auto tail = compile_format_string<Args, POS, ID>(fmt);
+    if constexpr (std::is_same<remove_cvref_t<decltype(tail)>,
+                               unknown_format>())
+      return tail;
+    else
+      return make_concat(head, tail);
+  } else {
+    return head;
+  }
+}
+
+template <typename T, typename Char> struct parse_specs_result {
+  formatter<T, Char> fmt;
+  size_t end;
+  int next_arg_id;
+};
+
+enum { manual_indexing_id = -1 };
+
+template <typename T, typename Char>
+constexpr auto parse_specs(basic_string_view<Char> str, size_t pos,
+                           int next_arg_id) -> parse_specs_result<T, Char> {
+  str.remove_prefix(pos);
+  auto ctx =
+      compile_parse_context<Char>(str, max_value<int>(), nullptr, next_arg_id);
+  auto f = formatter<T, Char>();
+  auto end = f.parse(ctx);
+  return {f, pos + fmt::detail::to_unsigned(end - str.data()),
+          next_arg_id == 0 ? manual_indexing_id : ctx.next_arg_id()};
+}
+
+template <typename Char> struct arg_id_handler {
+  arg_id_kind kind;
+  arg_ref<Char> arg_id;
+
+  constexpr auto on_auto() -> int {
+    FMT_ASSERT(false, "handler cannot be used with automatic indexing");
+    return 0;
+  }
+  constexpr auto on_index(int id) -> int {
+    kind = arg_id_kind::index;
+    arg_id = arg_ref<Char>(id);
+    return 0;
+  }
+  constexpr auto on_name(basic_string_view<Char> id) -> int {
+    kind = arg_id_kind::name;
+    arg_id = arg_ref<Char>(id);
+    return 0;
+  }
+};
+
+template <typename Char> struct parse_arg_id_result {
+  arg_id_kind kind;
+  arg_ref<Char> arg_id;
+  const Char* arg_id_end;
+};
+
+template <int ID, typename Char>
+constexpr auto parse_arg_id(const Char* begin, const Char* end) {
+  auto handler = arg_id_handler<Char>{arg_id_kind::none, arg_ref<Char>{}};
+  auto arg_id_end = parse_arg_id(begin, end, handler);
+  return parse_arg_id_result<Char>{handler.kind, handler.arg_id, arg_id_end};
+}
+
+template <typename T, typename Enable = void> struct field_type {
+  using type = remove_cvref_t<T>;
+};
+
+template <typename T>
+struct field_type<T, enable_if_t<detail::is_named_arg<T>::value>> {
+  using type = remove_cvref_t<decltype(T::value)>;
+};
+
+template <typename T, typename Args, size_t END_POS, int ARG_INDEX, int NEXT_ID,
+          typename S>
+constexpr auto parse_replacement_field_then_tail(S fmt) {
+  using char_type = typename S::char_type;
+  constexpr auto str = basic_string_view<char_type>(fmt);
+  constexpr char_type c = END_POS != str.size() ? str[END_POS] : char_type();
+  if constexpr (c == '}') {
+    return parse_tail<Args, END_POS + 1, NEXT_ID>(
+        field<char_type, typename field_type<T>::type, ARG_INDEX>(), fmt);
+  } else if constexpr (c != ':') {
+    FMT_THROW(format_error("expected ':'"));
+  } else {
+    constexpr auto result = parse_specs<typename field_type<T>::type>(
+        str, END_POS + 1, NEXT_ID == manual_indexing_id ? 0 : NEXT_ID);
+    if constexpr (result.end >= str.size() || str[result.end] != '}') {
+      FMT_THROW(format_error("expected '}'"));
+      return 0;
+    } else {
+      return parse_tail<Args, result.end + 1, result.next_arg_id>(
+          spec_field<char_type, typename field_type<T>::type, ARG_INDEX>{
+              result.fmt},
+          fmt);
+    }
+  }
+}
+
+// Compiles a non-empty format string and returns the compiled representation
+// or unknown_format() on unrecognized input.
+template <typename Args, size_t POS, int ID, typename S>
+constexpr auto compile_format_string(S fmt) {
+  using char_type = typename S::char_type;
+  constexpr auto str = basic_string_view<char_type>(fmt);
+  if constexpr (str[POS] == '{') {
+    if constexpr (POS + 1 == str.size())
+      FMT_THROW(format_error("unmatched '{' in format string"));
+    if constexpr (str[POS + 1] == '{') {
+      return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), fmt);
+    } else if constexpr (str[POS + 1] == '}' || str[POS + 1] == ':') {
+      static_assert(ID != manual_indexing_id,
+                    "cannot switch from manual to automatic argument indexing");
+      constexpr auto next_id =
+          ID != manual_indexing_id ? ID + 1 : manual_indexing_id;
+      return parse_replacement_field_then_tail<get_type<ID, Args>, Args,
+                                               POS + 1, ID, next_id>(fmt);
+    } else {
+      constexpr auto arg_id_result =
+          parse_arg_id<ID>(str.data() + POS + 1, str.data() + str.size());
+      constexpr auto arg_id_end_pos = arg_id_result.arg_id_end - str.data();
+      constexpr char_type c =
+          arg_id_end_pos != str.size() ? str[arg_id_end_pos] : char_type();
+      static_assert(c == '}' || c == ':', "missing '}' in format string");
+      if constexpr (arg_id_result.kind == arg_id_kind::index) {
+        static_assert(
+            ID == manual_indexing_id || ID == 0,
+            "cannot switch from automatic to manual argument indexing");
+        constexpr auto arg_index = arg_id_result.arg_id.index;
+        return parse_replacement_field_then_tail<get_type<arg_index, Args>,
+                                                 Args, arg_id_end_pos,
+                                                 arg_index, manual_indexing_id>(
+            fmt);
+      } else if constexpr (arg_id_result.kind == arg_id_kind::name) {
+        constexpr auto arg_index =
+            get_arg_index_by_name(arg_id_result.arg_id.name, Args{});
+        if constexpr (arg_index >= 0) {
+          constexpr auto next_id =
+              ID != manual_indexing_id ? ID + 1 : manual_indexing_id;
+          return parse_replacement_field_then_tail<
+              decltype(get_type<arg_index, Args>::value), Args, arg_id_end_pos,
+              arg_index, next_id>(fmt);
+        } else if constexpr (c == '}') {
+          return parse_tail<Args, arg_id_end_pos + 1, ID>(
+              runtime_named_field<char_type>{arg_id_result.arg_id.name}, fmt);
+        } else if constexpr (c == ':') {
+          return unknown_format();  // no type info for specs parsing
+        }
+      }
+    }
+  } else if constexpr (str[POS] == '}') {
+    if constexpr (POS + 1 == str.size())
+      FMT_THROW(format_error("unmatched '}' in format string"));
+    return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), fmt);
+  } else {
+    constexpr auto end = parse_text(str, POS + 1);
+    if constexpr (end - POS > 1) {
+      return parse_tail<Args, end, ID>(make_text(str, POS, end - POS), fmt);
+    } else {
+      return parse_tail<Args, end, ID>(code_unit<char_type>{str[POS]}, fmt);
+    }
+  }
+}
+
+template <typename... Args, typename S,
+          FMT_ENABLE_IF(is_compiled_string<S>::value)>
+constexpr auto compile(S fmt) {
+  constexpr auto str = basic_string_view<typename S::char_type>(fmt);
+  if constexpr (str.size() == 0) {
+    return detail::make_text(str, 0, 0);
+  } else {
+    constexpr auto result =
+        detail::compile_format_string<detail::type_list<Args...>, 0, 0>(fmt);
+    return result;
+  }
+}
+#endif  // defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
+}  // namespace detail
+
+FMT_BEGIN_EXPORT
+
+#if defined(__cpp_if_constexpr) && defined(__cpp_return_type_deduction)
+
+template <typename CompiledFormat, typename... T,
+          typename Char = typename CompiledFormat::char_type,
+          FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
+FMT_INLINE FMT_CONSTEXPR_STRING auto format(const CompiledFormat& cf,
+                                            const T&... args)
+    -> std::basic_string<Char> {
+  auto s = std::basic_string<Char>();
+  cf.format(std::back_inserter(s), args...);
+  return s;
+}
+
+template <typename OutputIt, typename CompiledFormat, typename... T,
+          FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
+constexpr FMT_INLINE auto format_to(OutputIt out, const CompiledFormat& cf,
+                                    const T&... args) -> OutputIt {
+  return cf.format(out, args...);
+}
+
+template <typename S, typename... T,
+          FMT_ENABLE_IF(is_compiled_string<S>::value)>
+FMT_INLINE FMT_CONSTEXPR_STRING auto format(const S&, T&&... args)
+    -> std::basic_string<typename S::char_type> {
+  if constexpr (std::is_same<typename S::char_type, char>::value) {
+    constexpr auto str = basic_string_view<typename S::char_type>(S());
+    if constexpr (str.size() == 2 && str[0] == '{' && str[1] == '}') {
+      const auto& first = detail::first(args...);
+      if constexpr (detail::is_named_arg<
+                        remove_cvref_t<decltype(first)>>::value) {
+        return fmt::to_string(first.value);
+      } else {
+        return fmt::to_string(first);
+      }
+    }
+  }
+  constexpr auto compiled = detail::compile<T...>(S());
+  if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
+                             detail::unknown_format>()) {
+    return fmt::format(
+        static_cast<basic_string_view<typename S::char_type>>(S()),
+        std::forward<T>(args)...);
+  } else {
+    return fmt::format(compiled, std::forward<T>(args)...);
+  }
+}
+
+template <typename OutputIt, typename S, typename... T,
+          FMT_ENABLE_IF(is_compiled_string<S>::value)>
+FMT_CONSTEXPR auto format_to(OutputIt out, const S&, T&&... args) -> OutputIt {
+  constexpr auto compiled = detail::compile<T...>(S());
+  if constexpr (std::is_same<remove_cvref_t<decltype(compiled)>,
+                             detail::unknown_format>()) {
+    return fmt::format_to(
+        out, static_cast<basic_string_view<typename S::char_type>>(S()),
+        std::forward<T>(args)...);
+  } else {
+    return fmt::format_to(out, compiled, std::forward<T>(args)...);
+  }
+}
+#endif
+
+template <typename OutputIt, typename S, typename... T,
+          FMT_ENABLE_IF(is_compiled_string<S>::value)>
+auto format_to_n(OutputIt out, size_t n, const S& fmt, T&&... args)
+    -> format_to_n_result<OutputIt> {
+  using traits = detail::fixed_buffer_traits;
+  auto buf = detail::iterator_buffer<OutputIt, char, traits>(out, n);
+  fmt::format_to(std::back_inserter(buf), fmt, std::forward<T>(args)...);
+  return {buf.out(), buf.count()};
+}
+
+template <typename S, typename... T,
+          FMT_ENABLE_IF(is_compiled_string<S>::value)>
+FMT_CONSTEXPR20 auto formatted_size(const S& fmt, T&&... args) -> size_t {
+  auto buf = detail::counting_buffer<>();
+  fmt::format_to(appender(buf), fmt, std::forward<T>(args)...);
+  return buf.count();
+}
+
+template <typename S, typename... T,
+          FMT_ENABLE_IF(is_compiled_string<S>::value)>
+void print(std::FILE* f, const S& fmt, T&&... args) {
+  auto buf = memory_buffer();
+  fmt::format_to(appender(buf), fmt, std::forward<T>(args)...);
+  detail::print(f, {buf.data(), buf.size()});
+}
+
+template <typename S, typename... T,
+          FMT_ENABLE_IF(is_compiled_string<S>::value)>
+void print(const S& fmt, T&&... args) {
+  print(stdout, fmt, std::forward<T>(args)...);
+}
+
+template <size_t N> class static_format_result {
+ private:
+  char data[N];
+
+ public:
+  template <typename S, typename... T,
+            FMT_ENABLE_IF(is_compiled_string<S>::value)>
+  explicit FMT_CONSTEXPR static_format_result(const S& fmt, T&&... args) {
+    *fmt::format_to(data, fmt, std::forward<T>(args)...) = '\0';
+  }
+
+  auto str() const -> fmt::string_view { return {data, N - 1}; }
+  auto c_str() const -> const char* { return data; }
+};
+
+/**
+ * Formats arguments according to the format string `fmt_str` and produces
+ * a string of the exact required size at compile time. Both the format string
+ * and the arguments must be compile-time expressions.
+ *
+ * The resulting string can be accessed as a C string via `c_str()` or as
+ * a `fmt::string_view` via `str()`.
+ *
+ * **Example**:
+ *
+ *     // Produces the static string "42" at compile time.
+ *     static constexpr auto result = FMT_STATIC_FORMAT("{}", 42);
+ *     const char* s = result.c_str();
+ */
+#define FMT_STATIC_FORMAT(fmt_str, ...)                            \
+  fmt::static_format_result<                                       \
+      fmt::formatted_size(FMT_COMPILE(fmt_str), __VA_ARGS__) + 1>( \
+      FMT_COMPILE(fmt_str), __VA_ARGS__)
+
+FMT_END_EXPORT
+FMT_END_NAMESPACE
+
+#endif  // FMT_COMPILE_H_

+ 5 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/core.h

@@ -0,0 +1,5 @@
+// This file is only provided for compatibility and may be removed in future
+// versions. Use fmt/base.h if you don't need fmt::format and fmt/format.h
+// otherwise.
+
+#include "format.h"

+ 1953 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/format-inl.h

@@ -0,0 +1,1953 @@
+// Formatting library for C++ - implementation
+//
+// Copyright (c) 2012 - 2016, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_FORMAT_INL_H_
+#define FMT_FORMAT_INL_H_
+
+#ifndef FMT_MODULE
+#  include <algorithm>
+#  include <cerrno>  // errno
+#  include <climits>
+#  include <cmath>
+#  include <exception>
+#endif
+
+#if defined(_WIN32) && !defined(FMT_USE_WRITE_CONSOLE)
+#  include <io.h>  // _isatty
+#endif
+
+#include "format.h"
+
+#if FMT_USE_LOCALE && !defined(FMT_MODULE)
+#  include <locale>
+#endif
+
+#ifndef FMT_FUNC
+#  define FMT_FUNC
+#endif
+
+FMT_BEGIN_NAMESPACE
+
+#ifndef FMT_CUSTOM_ASSERT_FAIL
+FMT_FUNC void assert_fail(const char* file, int line, const char* message) {
+  // Use unchecked std::fprintf to avoid triggering another assertion when
+  // writing to stderr fails.
+  fprintf(stderr, "%s:%d: assertion failed: %s", file, line, message);
+  abort();
+}
+#endif
+
+#if FMT_USE_LOCALE
+namespace detail {
+using std::locale;
+using std::numpunct;
+using std::use_facet;
+}  // namespace detail
+
+template <typename Locale, enable_if_t<(sizeof(Locale::collate) != 0), int>>
+locale_ref::locale_ref(const Locale& loc) : locale_(&loc) {
+  static_assert(std::is_same<Locale, std::locale>::value, "");
+}
+#else
+namespace detail {
+struct locale {};
+template <typename Char> struct numpunct {
+  auto grouping() const -> std::string { return "\03"; }
+  auto thousands_sep() const -> Char { return ','; }
+  auto decimal_point() const -> Char { return '.'; }
+};
+template <typename Facet> Facet use_facet(locale) { return {}; }
+}  // namespace detail
+#endif  // FMT_USE_LOCALE
+
+template <typename Locale> auto locale_ref::get() const -> Locale {
+  using namespace detail;
+  static_assert(std::is_same<Locale, locale>::value, "");
+#if FMT_USE_LOCALE
+  if (locale_) return *static_cast<const locale*>(locale_);
+#endif
+  return locale();
+}
+
+namespace detail {
+
+FMT_FUNC void format_error_code(detail::buffer<char>& out, int error_code,
+                                string_view message) noexcept {
+  // Report error code making sure that the output fits into
+  // inline_buffer_size to avoid dynamic memory allocation and potential
+  // bad_alloc.
+  out.try_resize(0);
+  static const char SEP[] = ": ";
+  static const char ERROR_STR[] = "error ";
+  // Subtract 2 to account for terminating null characters in SEP and ERROR_STR.
+  size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2;
+  auto abs_value = static_cast<uint32_or_64_or_128_t<int>>(error_code);
+  if (detail::is_negative(error_code)) {
+    abs_value = 0 - abs_value;
+    ++error_code_size;
+  }
+  error_code_size += detail::to_unsigned(detail::count_digits(abs_value));
+  auto it = appender(out);
+  if (message.size() <= inline_buffer_size - error_code_size)
+    fmt::format_to(it, FMT_STRING("{}{}"), message, SEP);
+  fmt::format_to(it, FMT_STRING("{}{}"), ERROR_STR, error_code);
+  FMT_ASSERT(out.size() <= inline_buffer_size, "");
+}
+
+FMT_FUNC void do_report_error(format_func func, int error_code,
+                              const char* message) noexcept {
+  memory_buffer full_message;
+  func(full_message, error_code, message);
+  // Don't use fwrite_all because the latter may throw.
+  if (std::fwrite(full_message.data(), full_message.size(), 1, stderr) > 0)
+    std::fputc('\n', stderr);
+}
+
+// A wrapper around fwrite that throws on error.
+inline void fwrite_all(const void* ptr, size_t count, FILE* stream) {
+  size_t written = std::fwrite(ptr, 1, count, stream);
+  if (written < count)
+    FMT_THROW(system_error(errno, FMT_STRING("cannot write to file")));
+}
+
+template <typename Char>
+FMT_FUNC auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result<Char> {
+  auto&& facet = use_facet<numpunct<Char>>(loc.get<locale>());
+  auto grouping = facet.grouping();
+  auto thousands_sep = grouping.empty() ? Char() : facet.thousands_sep();
+  return {std::move(grouping), thousands_sep};
+}
+template <typename Char>
+FMT_FUNC auto decimal_point_impl(locale_ref loc) -> Char {
+  return use_facet<numpunct<Char>>(loc.get<locale>()).decimal_point();
+}
+
+#if FMT_USE_LOCALE
+FMT_FUNC auto write_loc(appender out, loc_value value,
+                        const format_specs& specs, locale_ref loc) -> bool {
+  auto locale = loc.get<std::locale>();
+  // We cannot use the num_put<char> facet because it may produce output in
+  // a wrong encoding.
+  using facet = format_facet<std::locale>;
+  if (std::has_facet<facet>(locale))
+    return use_facet<facet>(locale).put(out, value, specs);
+  return facet(locale).put(out, value, specs);
+}
+#endif
+}  // namespace detail
+
+FMT_FUNC void report_error(const char* message) {
+#if FMT_MSC_VERSION || defined(__NVCC__)
+  // Silence unreachable code warnings in MSVC and NVCC because these
+  // are nearly impossible to fix in a generic code.
+  volatile bool b = true;
+  if (!b) return;
+#endif
+  FMT_THROW(format_error(message));
+}
+
+template <typename Locale> typename Locale::id format_facet<Locale>::id;
+
+template <typename Locale> format_facet<Locale>::format_facet(Locale& loc) {
+  auto& np = detail::use_facet<detail::numpunct<char>>(loc);
+  grouping_ = np.grouping();
+  if (!grouping_.empty()) separator_ = std::string(1, np.thousands_sep());
+}
+
+#if FMT_USE_LOCALE
+template <>
+FMT_API FMT_FUNC auto format_facet<std::locale>::do_put(
+    appender out, loc_value val, const format_specs& specs) const -> bool {
+  return val.visit(
+      detail::loc_writer<>{out, specs, separator_, grouping_, decimal_point_});
+}
+#endif
+
+FMT_FUNC auto vsystem_error(int error_code, string_view fmt, format_args args)
+    -> std::system_error {
+  auto ec = std::error_code(error_code, std::generic_category());
+  return std::system_error(ec, vformat(fmt, args));
+}
+
+namespace detail {
+
+template <typename F>
+inline auto operator==(basic_fp<F> x, basic_fp<F> y) -> bool {
+  return x.f == y.f && x.e == y.e;
+}
+
+// Compilers should be able to optimize this into the ror instruction.
+FMT_INLINE auto rotr(uint32_t n, uint32_t r) noexcept -> uint32_t {
+  r &= 31;
+  return (n >> r) | (n << (32 - r));
+}
+FMT_INLINE auto rotr(uint64_t n, uint32_t r) noexcept -> uint64_t {
+  r &= 63;
+  return (n >> r) | (n << (64 - r));
+}
+
+// Implementation of Dragonbox algorithm: https://github.com/jk-jeon/dragonbox.
+namespace dragonbox {
+// Computes upper 64 bits of multiplication of a 32-bit unsigned integer and a
+// 64-bit unsigned integer.
+inline auto umul96_upper64(uint32_t x, uint64_t y) noexcept -> uint64_t {
+  return umul128_upper64(static_cast<uint64_t>(x) << 32, y);
+}
+
+// Computes lower 128 bits of multiplication of a 64-bit unsigned integer and a
+// 128-bit unsigned integer.
+inline auto umul192_lower128(uint64_t x, uint128_fallback y) noexcept
+    -> uint128_fallback {
+  uint64_t high = x * y.high();
+  uint128_fallback high_low = umul128(x, y.low());
+  return {high + high_low.high(), high_low.low()};
+}
+
+// Computes lower 64 bits of multiplication of a 32-bit unsigned integer and a
+// 64-bit unsigned integer.
+inline auto umul96_lower64(uint32_t x, uint64_t y) noexcept -> uint64_t {
+  return x * y;
+}
+
+// Various fast log computations.
+inline auto floor_log10_pow2_minus_log10_4_over_3(int e) noexcept -> int {
+  FMT_ASSERT(e <= 2936 && e >= -2985, "too large exponent");
+  return (e * 631305 - 261663) >> 21;
+}
+
+FMT_INLINE_VARIABLE constexpr struct div_small_pow10_infos_struct {
+  uint32_t divisor;
+  int shift_amount;
+} div_small_pow10_infos[] = {{10, 16}, {100, 16}};
+
+// Replaces n by floor(n / pow(10, N)) returning true if and only if n is
+// divisible by pow(10, N).
+// Precondition: n <= pow(10, N + 1).
+template <int N>
+auto check_divisibility_and_divide_by_pow10(uint32_t& n) noexcept -> bool {
+  // The numbers below are chosen such that:
+  //   1. floor(n/d) = floor(nm / 2^k) where d=10 or d=100,
+  //   2. nm mod 2^k < m if and only if n is divisible by d,
+  // where m is magic_number, k is shift_amount
+  // and d is divisor.
+  //
+  // Item 1 is a common technique of replacing division by a constant with
+  // multiplication, see e.g. "Division by Invariant Integers Using
+  // Multiplication" by Granlund and Montgomery (1994). magic_number (m) is set
+  // to ceil(2^k/d) for large enough k.
+  // The idea for item 2 originates from Schubfach.
+  constexpr auto info = div_small_pow10_infos[N - 1];
+  FMT_ASSERT(n <= info.divisor * 10, "n is too large");
+  constexpr uint32_t magic_number =
+      (1u << info.shift_amount) / info.divisor + 1;
+  n *= magic_number;
+  const uint32_t comparison_mask = (1u << info.shift_amount) - 1;
+  bool result = (n & comparison_mask) < magic_number;
+  n >>= info.shift_amount;
+  return result;
+}
+
+// Computes floor(n / pow(10, N)) for small n and N.
+// Precondition: n <= pow(10, N + 1).
+template <int N> auto small_division_by_pow10(uint32_t n) noexcept -> uint32_t {
+  constexpr auto info = div_small_pow10_infos[N - 1];
+  FMT_ASSERT(n <= info.divisor * 10, "n is too large");
+  constexpr uint32_t magic_number =
+      (1u << info.shift_amount) / info.divisor + 1;
+  return (n * magic_number) >> info.shift_amount;
+}
+
+// Computes floor(n / 10^(kappa + 1)) (float)
+inline auto divide_by_10_to_kappa_plus_1(uint32_t n) noexcept -> uint32_t {
+  // 1374389535 = ceil(2^37/100)
+  return static_cast<uint32_t>((static_cast<uint64_t>(n) * 1374389535) >> 37);
+}
+// Computes floor(n / 10^(kappa + 1)) (double)
+inline auto divide_by_10_to_kappa_plus_1(uint64_t n) noexcept -> uint64_t {
+  // 2361183241434822607 = ceil(2^(64+7)/1000)
+  return umul128_upper64(n, 2361183241434822607ull) >> 7;
+}
+
+// Various subroutines using pow10 cache
+template <typename T> struct cache_accessor;
+
+template <> struct cache_accessor<float> {
+  using carrier_uint = float_info<float>::carrier_uint;
+  using cache_entry_type = uint64_t;
+
+  static auto get_cached_power(int k) noexcept -> uint64_t {
+    FMT_ASSERT(k >= float_info<float>::min_k && k <= float_info<float>::max_k,
+               "k is out of range");
+    static constexpr uint64_t pow10_significands[] = {
+        0x81ceb32c4b43fcf5, 0xa2425ff75e14fc32, 0xcad2f7f5359a3b3f,
+        0xfd87b5f28300ca0e, 0x9e74d1b791e07e49, 0xc612062576589ddb,
+        0xf79687aed3eec552, 0x9abe14cd44753b53, 0xc16d9a0095928a28,
+        0xf1c90080baf72cb2, 0x971da05074da7bef, 0xbce5086492111aeb,
+        0xec1e4a7db69561a6, 0x9392ee8e921d5d08, 0xb877aa3236a4b44a,
+        0xe69594bec44de15c, 0x901d7cf73ab0acda, 0xb424dc35095cd810,
+        0xe12e13424bb40e14, 0x8cbccc096f5088cc, 0xafebff0bcb24aaff,
+        0xdbe6fecebdedd5bf, 0x89705f4136b4a598, 0xabcc77118461cefd,
+        0xd6bf94d5e57a42bd, 0x8637bd05af6c69b6, 0xa7c5ac471b478424,
+        0xd1b71758e219652c, 0x83126e978d4fdf3c, 0xa3d70a3d70a3d70b,
+        0xcccccccccccccccd, 0x8000000000000000, 0xa000000000000000,
+        0xc800000000000000, 0xfa00000000000000, 0x9c40000000000000,
+        0xc350000000000000, 0xf424000000000000, 0x9896800000000000,
+        0xbebc200000000000, 0xee6b280000000000, 0x9502f90000000000,
+        0xba43b74000000000, 0xe8d4a51000000000, 0x9184e72a00000000,
+        0xb5e620f480000000, 0xe35fa931a0000000, 0x8e1bc9bf04000000,
+        0xb1a2bc2ec5000000, 0xde0b6b3a76400000, 0x8ac7230489e80000,
+        0xad78ebc5ac620000, 0xd8d726b7177a8000, 0x878678326eac9000,
+        0xa968163f0a57b400, 0xd3c21bcecceda100, 0x84595161401484a0,
+        0xa56fa5b99019a5c8, 0xcecb8f27f4200f3a, 0x813f3978f8940985,
+        0xa18f07d736b90be6, 0xc9f2c9cd04674edf, 0xfc6f7c4045812297,
+        0x9dc5ada82b70b59e, 0xc5371912364ce306, 0xf684df56c3e01bc7,
+        0x9a130b963a6c115d, 0xc097ce7bc90715b4, 0xf0bdc21abb48db21,
+        0x96769950b50d88f5, 0xbc143fa4e250eb32, 0xeb194f8e1ae525fe,
+        0x92efd1b8d0cf37bf, 0xb7abc627050305ae, 0xe596b7b0c643c71a,
+        0x8f7e32ce7bea5c70, 0xb35dbf821ae4f38c, 0xe0352f62a19e306f};
+    return pow10_significands[k - float_info<float>::min_k];
+  }
+
+  struct compute_mul_result {
+    carrier_uint result;
+    bool is_integer;
+  };
+  struct compute_mul_parity_result {
+    bool parity;
+    bool is_integer;
+  };
+
+  static auto compute_mul(carrier_uint u,
+                          const cache_entry_type& cache) noexcept
+      -> compute_mul_result {
+    auto r = umul96_upper64(u, cache);
+    return {static_cast<carrier_uint>(r >> 32),
+            static_cast<carrier_uint>(r) == 0};
+  }
+
+  static auto compute_delta(const cache_entry_type& cache, int beta) noexcept
+      -> uint32_t {
+    return static_cast<uint32_t>(cache >> (64 - 1 - beta));
+  }
+
+  static auto compute_mul_parity(carrier_uint two_f,
+                                 const cache_entry_type& cache,
+                                 int beta) noexcept
+      -> compute_mul_parity_result {
+    FMT_ASSERT(beta >= 1, "");
+    FMT_ASSERT(beta < 64, "");
+
+    auto r = umul96_lower64(two_f, cache);
+    return {((r >> (64 - beta)) & 1) != 0,
+            static_cast<uint32_t>(r >> (32 - beta)) == 0};
+  }
+
+  static auto compute_left_endpoint_for_shorter_interval_case(
+      const cache_entry_type& cache, int beta) noexcept -> carrier_uint {
+    return static_cast<carrier_uint>(
+        (cache - (cache >> (num_significand_bits<float>() + 2))) >>
+        (64 - num_significand_bits<float>() - 1 - beta));
+  }
+
+  static auto compute_right_endpoint_for_shorter_interval_case(
+      const cache_entry_type& cache, int beta) noexcept -> carrier_uint {
+    return static_cast<carrier_uint>(
+        (cache + (cache >> (num_significand_bits<float>() + 1))) >>
+        (64 - num_significand_bits<float>() - 1 - beta));
+  }
+
+  static auto compute_round_up_for_shorter_interval_case(
+      const cache_entry_type& cache, int beta) noexcept -> carrier_uint {
+    return (static_cast<carrier_uint>(
+                cache >> (64 - num_significand_bits<float>() - 2 - beta)) +
+            1) /
+           2;
+  }
+};
+
+template <> struct cache_accessor<double> {
+  using carrier_uint = float_info<double>::carrier_uint;
+  using cache_entry_type = uint128_fallback;
+
+  static auto get_cached_power(int k) noexcept -> uint128_fallback {
+    FMT_ASSERT(k >= float_info<double>::min_k && k <= float_info<double>::max_k,
+               "k is out of range");
+
+    static constexpr uint128_fallback pow10_significands[] = {
+#if FMT_USE_FULL_CACHE_DRAGONBOX
+      {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b},
+      {0x9faacf3df73609b1, 0x77b191618c54e9ad},
+      {0xc795830d75038c1d, 0xd59df5b9ef6a2418},
+      {0xf97ae3d0d2446f25, 0x4b0573286b44ad1e},
+      {0x9becce62836ac577, 0x4ee367f9430aec33},
+      {0xc2e801fb244576d5, 0x229c41f793cda740},
+      {0xf3a20279ed56d48a, 0x6b43527578c11110},
+      {0x9845418c345644d6, 0x830a13896b78aaaa},
+      {0xbe5691ef416bd60c, 0x23cc986bc656d554},
+      {0xedec366b11c6cb8f, 0x2cbfbe86b7ec8aa9},
+      {0x94b3a202eb1c3f39, 0x7bf7d71432f3d6aa},
+      {0xb9e08a83a5e34f07, 0xdaf5ccd93fb0cc54},
+      {0xe858ad248f5c22c9, 0xd1b3400f8f9cff69},
+      {0x91376c36d99995be, 0x23100809b9c21fa2},
+      {0xb58547448ffffb2d, 0xabd40a0c2832a78b},
+      {0xe2e69915b3fff9f9, 0x16c90c8f323f516d},
+      {0x8dd01fad907ffc3b, 0xae3da7d97f6792e4},
+      {0xb1442798f49ffb4a, 0x99cd11cfdf41779d},
+      {0xdd95317f31c7fa1d, 0x40405643d711d584},
+      {0x8a7d3eef7f1cfc52, 0x482835ea666b2573},
+      {0xad1c8eab5ee43b66, 0xda3243650005eed0},
+      {0xd863b256369d4a40, 0x90bed43e40076a83},
+      {0x873e4f75e2224e68, 0x5a7744a6e804a292},
+      {0xa90de3535aaae202, 0x711515d0a205cb37},
+      {0xd3515c2831559a83, 0x0d5a5b44ca873e04},
+      {0x8412d9991ed58091, 0xe858790afe9486c3},
+      {0xa5178fff668ae0b6, 0x626e974dbe39a873},
+      {0xce5d73ff402d98e3, 0xfb0a3d212dc81290},
+      {0x80fa687f881c7f8e, 0x7ce66634bc9d0b9a},
+      {0xa139029f6a239f72, 0x1c1fffc1ebc44e81},
+      {0xc987434744ac874e, 0xa327ffb266b56221},
+      {0xfbe9141915d7a922, 0x4bf1ff9f0062baa9},
+      {0x9d71ac8fada6c9b5, 0x6f773fc3603db4aa},
+      {0xc4ce17b399107c22, 0xcb550fb4384d21d4},
+      {0xf6019da07f549b2b, 0x7e2a53a146606a49},
+      {0x99c102844f94e0fb, 0x2eda7444cbfc426e},
+      {0xc0314325637a1939, 0xfa911155fefb5309},
+      {0xf03d93eebc589f88, 0x793555ab7eba27cb},
+      {0x96267c7535b763b5, 0x4bc1558b2f3458df},
+      {0xbbb01b9283253ca2, 0x9eb1aaedfb016f17},
+      {0xea9c227723ee8bcb, 0x465e15a979c1cadd},
+      {0x92a1958a7675175f, 0x0bfacd89ec191eca},
+      {0xb749faed14125d36, 0xcef980ec671f667c},
+      {0xe51c79a85916f484, 0x82b7e12780e7401b},
+      {0x8f31cc0937ae58d2, 0xd1b2ecb8b0908811},
+      {0xb2fe3f0b8599ef07, 0x861fa7e6dcb4aa16},
+      {0xdfbdcece67006ac9, 0x67a791e093e1d49b},
+      {0x8bd6a141006042bd, 0xe0c8bb2c5c6d24e1},
+      {0xaecc49914078536d, 0x58fae9f773886e19},
+      {0xda7f5bf590966848, 0xaf39a475506a899f},
+      {0x888f99797a5e012d, 0x6d8406c952429604},
+      {0xaab37fd7d8f58178, 0xc8e5087ba6d33b84},
+      {0xd5605fcdcf32e1d6, 0xfb1e4a9a90880a65},
+      {0x855c3be0a17fcd26, 0x5cf2eea09a550680},
+      {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f},
+      {0xd0601d8efc57b08b, 0xf13b94daf124da27},
+      {0x823c12795db6ce57, 0x76c53d08d6b70859},
+      {0xa2cb1717b52481ed, 0x54768c4b0c64ca6f},
+      {0xcb7ddcdda26da268, 0xa9942f5dcf7dfd0a},
+      {0xfe5d54150b090b02, 0xd3f93b35435d7c4d},
+      {0x9efa548d26e5a6e1, 0xc47bc5014a1a6db0},
+      {0xc6b8e9b0709f109a, 0x359ab6419ca1091c},
+      {0xf867241c8cc6d4c0, 0xc30163d203c94b63},
+      {0x9b407691d7fc44f8, 0x79e0de63425dcf1e},
+      {0xc21094364dfb5636, 0x985915fc12f542e5},
+      {0xf294b943e17a2bc4, 0x3e6f5b7b17b2939e},
+      {0x979cf3ca6cec5b5a, 0xa705992ceecf9c43},
+      {0xbd8430bd08277231, 0x50c6ff782a838354},
+      {0xece53cec4a314ebd, 0xa4f8bf5635246429},
+      {0x940f4613ae5ed136, 0x871b7795e136be9a},
+      {0xb913179899f68584, 0x28e2557b59846e40},
+      {0xe757dd7ec07426e5, 0x331aeada2fe589d0},
+      {0x9096ea6f3848984f, 0x3ff0d2c85def7622},
+      {0xb4bca50b065abe63, 0x0fed077a756b53aa},
+      {0xe1ebce4dc7f16dfb, 0xd3e8495912c62895},
+      {0x8d3360f09cf6e4bd, 0x64712dd7abbbd95d},
+      {0xb080392cc4349dec, 0xbd8d794d96aacfb4},
+      {0xdca04777f541c567, 0xecf0d7a0fc5583a1},
+      {0x89e42caaf9491b60, 0xf41686c49db57245},
+      {0xac5d37d5b79b6239, 0x311c2875c522ced6},
+      {0xd77485cb25823ac7, 0x7d633293366b828c},
+      {0x86a8d39ef77164bc, 0xae5dff9c02033198},
+      {0xa8530886b54dbdeb, 0xd9f57f830283fdfd},
+      {0xd267caa862a12d66, 0xd072df63c324fd7c},
+      {0x8380dea93da4bc60, 0x4247cb9e59f71e6e},
+      {0xa46116538d0deb78, 0x52d9be85f074e609},
+      {0xcd795be870516656, 0x67902e276c921f8c},
+      {0x806bd9714632dff6, 0x00ba1cd8a3db53b7},
+      {0xa086cfcd97bf97f3, 0x80e8a40eccd228a5},
+      {0xc8a883c0fdaf7df0, 0x6122cd128006b2ce},
+      {0xfad2a4b13d1b5d6c, 0x796b805720085f82},
+      {0x9cc3a6eec6311a63, 0xcbe3303674053bb1},
+      {0xc3f490aa77bd60fc, 0xbedbfc4411068a9d},
+      {0xf4f1b4d515acb93b, 0xee92fb5515482d45},
+      {0x991711052d8bf3c5, 0x751bdd152d4d1c4b},
+      {0xbf5cd54678eef0b6, 0xd262d45a78a0635e},
+      {0xef340a98172aace4, 0x86fb897116c87c35},
+      {0x9580869f0e7aac0e, 0xd45d35e6ae3d4da1},
+      {0xbae0a846d2195712, 0x8974836059cca10a},
+      {0xe998d258869facd7, 0x2bd1a438703fc94c},
+      {0x91ff83775423cc06, 0x7b6306a34627ddd0},
+      {0xb67f6455292cbf08, 0x1a3bc84c17b1d543},
+      {0xe41f3d6a7377eeca, 0x20caba5f1d9e4a94},
+      {0x8e938662882af53e, 0x547eb47b7282ee9d},
+      {0xb23867fb2a35b28d, 0xe99e619a4f23aa44},
+      {0xdec681f9f4c31f31, 0x6405fa00e2ec94d5},
+      {0x8b3c113c38f9f37e, 0xde83bc408dd3dd05},
+      {0xae0b158b4738705e, 0x9624ab50b148d446},
+      {0xd98ddaee19068c76, 0x3badd624dd9b0958},
+      {0x87f8a8d4cfa417c9, 0xe54ca5d70a80e5d7},
+      {0xa9f6d30a038d1dbc, 0x5e9fcf4ccd211f4d},
+      {0xd47487cc8470652b, 0x7647c32000696720},
+      {0x84c8d4dfd2c63f3b, 0x29ecd9f40041e074},
+      {0xa5fb0a17c777cf09, 0xf468107100525891},
+      {0xcf79cc9db955c2cc, 0x7182148d4066eeb5},
+      {0x81ac1fe293d599bf, 0xc6f14cd848405531},
+      {0xa21727db38cb002f, 0xb8ada00e5a506a7d},
+      {0xca9cf1d206fdc03b, 0xa6d90811f0e4851d},
+      {0xfd442e4688bd304a, 0x908f4a166d1da664},
+      {0x9e4a9cec15763e2e, 0x9a598e4e043287ff},
+      {0xc5dd44271ad3cdba, 0x40eff1e1853f29fe},
+      {0xf7549530e188c128, 0xd12bee59e68ef47d},
+      {0x9a94dd3e8cf578b9, 0x82bb74f8301958cf},
+      {0xc13a148e3032d6e7, 0xe36a52363c1faf02},
+      {0xf18899b1bc3f8ca1, 0xdc44e6c3cb279ac2},
+      {0x96f5600f15a7b7e5, 0x29ab103a5ef8c0ba},
+      {0xbcb2b812db11a5de, 0x7415d448f6b6f0e8},
+      {0xebdf661791d60f56, 0x111b495b3464ad22},
+      {0x936b9fcebb25c995, 0xcab10dd900beec35},
+      {0xb84687c269ef3bfb, 0x3d5d514f40eea743},
+      {0xe65829b3046b0afa, 0x0cb4a5a3112a5113},
+      {0x8ff71a0fe2c2e6dc, 0x47f0e785eaba72ac},
+      {0xb3f4e093db73a093, 0x59ed216765690f57},
+      {0xe0f218b8d25088b8, 0x306869c13ec3532d},
+      {0x8c974f7383725573, 0x1e414218c73a13fc},
+      {0xafbd2350644eeacf, 0xe5d1929ef90898fb},
+      {0xdbac6c247d62a583, 0xdf45f746b74abf3a},
+      {0x894bc396ce5da772, 0x6b8bba8c328eb784},
+      {0xab9eb47c81f5114f, 0x066ea92f3f326565},
+      {0xd686619ba27255a2, 0xc80a537b0efefebe},
+      {0x8613fd0145877585, 0xbd06742ce95f5f37},
+      {0xa798fc4196e952e7, 0x2c48113823b73705},
+      {0xd17f3b51fca3a7a0, 0xf75a15862ca504c6},
+      {0x82ef85133de648c4, 0x9a984d73dbe722fc},
+      {0xa3ab66580d5fdaf5, 0xc13e60d0d2e0ebbb},
+      {0xcc963fee10b7d1b3, 0x318df905079926a9},
+      {0xffbbcfe994e5c61f, 0xfdf17746497f7053},
+      {0x9fd561f1fd0f9bd3, 0xfeb6ea8bedefa634},
+      {0xc7caba6e7c5382c8, 0xfe64a52ee96b8fc1},
+      {0xf9bd690a1b68637b, 0x3dfdce7aa3c673b1},
+      {0x9c1661a651213e2d, 0x06bea10ca65c084f},
+      {0xc31bfa0fe5698db8, 0x486e494fcff30a63},
+      {0xf3e2f893dec3f126, 0x5a89dba3c3efccfb},
+      {0x986ddb5c6b3a76b7, 0xf89629465a75e01d},
+      {0xbe89523386091465, 0xf6bbb397f1135824},
+      {0xee2ba6c0678b597f, 0x746aa07ded582e2d},
+      {0x94db483840b717ef, 0xa8c2a44eb4571cdd},
+      {0xba121a4650e4ddeb, 0x92f34d62616ce414},
+      {0xe896a0d7e51e1566, 0x77b020baf9c81d18},
+      {0x915e2486ef32cd60, 0x0ace1474dc1d122f},
+      {0xb5b5ada8aaff80b8, 0x0d819992132456bb},
+      {0xe3231912d5bf60e6, 0x10e1fff697ed6c6a},
+      {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2},
+      {0xb1736b96b6fd83b3, 0xbd308ff8a6b17cb3},
+      {0xddd0467c64bce4a0, 0xac7cb3f6d05ddbdf},
+      {0x8aa22c0dbef60ee4, 0x6bcdf07a423aa96c},
+      {0xad4ab7112eb3929d, 0x86c16c98d2c953c7},
+      {0xd89d64d57a607744, 0xe871c7bf077ba8b8},
+      {0x87625f056c7c4a8b, 0x11471cd764ad4973},
+      {0xa93af6c6c79b5d2d, 0xd598e40d3dd89bd0},
+      {0xd389b47879823479, 0x4aff1d108d4ec2c4},
+      {0x843610cb4bf160cb, 0xcedf722a585139bb},
+      {0xa54394fe1eedb8fe, 0xc2974eb4ee658829},
+      {0xce947a3da6a9273e, 0x733d226229feea33},
+      {0x811ccc668829b887, 0x0806357d5a3f5260},
+      {0xa163ff802a3426a8, 0xca07c2dcb0cf26f8},
+      {0xc9bcff6034c13052, 0xfc89b393dd02f0b6},
+      {0xfc2c3f3841f17c67, 0xbbac2078d443ace3},
+      {0x9d9ba7832936edc0, 0xd54b944b84aa4c0e},
+      {0xc5029163f384a931, 0x0a9e795e65d4df12},
+      {0xf64335bcf065d37d, 0x4d4617b5ff4a16d6},
+      {0x99ea0196163fa42e, 0x504bced1bf8e4e46},
+      {0xc06481fb9bcf8d39, 0xe45ec2862f71e1d7},
+      {0xf07da27a82c37088, 0x5d767327bb4e5a4d},
+      {0x964e858c91ba2655, 0x3a6a07f8d510f870},
+      {0xbbe226efb628afea, 0x890489f70a55368c},
+      {0xeadab0aba3b2dbe5, 0x2b45ac74ccea842f},
+      {0x92c8ae6b464fc96f, 0x3b0b8bc90012929e},
+      {0xb77ada0617e3bbcb, 0x09ce6ebb40173745},
+      {0xe55990879ddcaabd, 0xcc420a6a101d0516},
+      {0x8f57fa54c2a9eab6, 0x9fa946824a12232e},
+      {0xb32df8e9f3546564, 0x47939822dc96abfa},
+      {0xdff9772470297ebd, 0x59787e2b93bc56f8},
+      {0x8bfbea76c619ef36, 0x57eb4edb3c55b65b},
+      {0xaefae51477a06b03, 0xede622920b6b23f2},
+      {0xdab99e59958885c4, 0xe95fab368e45ecee},
+      {0x88b402f7fd75539b, 0x11dbcb0218ebb415},
+      {0xaae103b5fcd2a881, 0xd652bdc29f26a11a},
+      {0xd59944a37c0752a2, 0x4be76d3346f04960},
+      {0x857fcae62d8493a5, 0x6f70a4400c562ddc},
+      {0xa6dfbd9fb8e5b88e, 0xcb4ccd500f6bb953},
+      {0xd097ad07a71f26b2, 0x7e2000a41346a7a8},
+      {0x825ecc24c873782f, 0x8ed400668c0c28c9},
+      {0xa2f67f2dfa90563b, 0x728900802f0f32fb},
+      {0xcbb41ef979346bca, 0x4f2b40a03ad2ffba},
+      {0xfea126b7d78186bc, 0xe2f610c84987bfa9},
+      {0x9f24b832e6b0f436, 0x0dd9ca7d2df4d7ca},
+      {0xc6ede63fa05d3143, 0x91503d1c79720dbc},
+      {0xf8a95fcf88747d94, 0x75a44c6397ce912b},
+      {0x9b69dbe1b548ce7c, 0xc986afbe3ee11abb},
+      {0xc24452da229b021b, 0xfbe85badce996169},
+      {0xf2d56790ab41c2a2, 0xfae27299423fb9c4},
+      {0x97c560ba6b0919a5, 0xdccd879fc967d41b},
+      {0xbdb6b8e905cb600f, 0x5400e987bbc1c921},
+      {0xed246723473e3813, 0x290123e9aab23b69},
+      {0x9436c0760c86e30b, 0xf9a0b6720aaf6522},
+      {0xb94470938fa89bce, 0xf808e40e8d5b3e6a},
+      {0xe7958cb87392c2c2, 0xb60b1d1230b20e05},
+      {0x90bd77f3483bb9b9, 0xb1c6f22b5e6f48c3},
+      {0xb4ecd5f01a4aa828, 0x1e38aeb6360b1af4},
+      {0xe2280b6c20dd5232, 0x25c6da63c38de1b1},
+      {0x8d590723948a535f, 0x579c487e5a38ad0f},
+      {0xb0af48ec79ace837, 0x2d835a9df0c6d852},
+      {0xdcdb1b2798182244, 0xf8e431456cf88e66},
+      {0x8a08f0f8bf0f156b, 0x1b8e9ecb641b5900},
+      {0xac8b2d36eed2dac5, 0xe272467e3d222f40},
+      {0xd7adf884aa879177, 0x5b0ed81dcc6abb10},
+      {0x86ccbb52ea94baea, 0x98e947129fc2b4ea},
+      {0xa87fea27a539e9a5, 0x3f2398d747b36225},
+      {0xd29fe4b18e88640e, 0x8eec7f0d19a03aae},
+      {0x83a3eeeef9153e89, 0x1953cf68300424ad},
+      {0xa48ceaaab75a8e2b, 0x5fa8c3423c052dd8},
+      {0xcdb02555653131b6, 0x3792f412cb06794e},
+      {0x808e17555f3ebf11, 0xe2bbd88bbee40bd1},
+      {0xa0b19d2ab70e6ed6, 0x5b6aceaeae9d0ec5},
+      {0xc8de047564d20a8b, 0xf245825a5a445276},
+      {0xfb158592be068d2e, 0xeed6e2f0f0d56713},
+      {0x9ced737bb6c4183d, 0x55464dd69685606c},
+      {0xc428d05aa4751e4c, 0xaa97e14c3c26b887},
+      {0xf53304714d9265df, 0xd53dd99f4b3066a9},
+      {0x993fe2c6d07b7fab, 0xe546a8038efe402a},
+      {0xbf8fdb78849a5f96, 0xde98520472bdd034},
+      {0xef73d256a5c0f77c, 0x963e66858f6d4441},
+      {0x95a8637627989aad, 0xdde7001379a44aa9},
+      {0xbb127c53b17ec159, 0x5560c018580d5d53},
+      {0xe9d71b689dde71af, 0xaab8f01e6e10b4a7},
+      {0x9226712162ab070d, 0xcab3961304ca70e9},
+      {0xb6b00d69bb55c8d1, 0x3d607b97c5fd0d23},
+      {0xe45c10c42a2b3b05, 0x8cb89a7db77c506b},
+      {0x8eb98a7a9a5b04e3, 0x77f3608e92adb243},
+      {0xb267ed1940f1c61c, 0x55f038b237591ed4},
+      {0xdf01e85f912e37a3, 0x6b6c46dec52f6689},
+      {0x8b61313bbabce2c6, 0x2323ac4b3b3da016},
+      {0xae397d8aa96c1b77, 0xabec975e0a0d081b},
+      {0xd9c7dced53c72255, 0x96e7bd358c904a22},
+      {0x881cea14545c7575, 0x7e50d64177da2e55},
+      {0xaa242499697392d2, 0xdde50bd1d5d0b9ea},
+      {0xd4ad2dbfc3d07787, 0x955e4ec64b44e865},
+      {0x84ec3c97da624ab4, 0xbd5af13bef0b113f},
+      {0xa6274bbdd0fadd61, 0xecb1ad8aeacdd58f},
+      {0xcfb11ead453994ba, 0x67de18eda5814af3},
+      {0x81ceb32c4b43fcf4, 0x80eacf948770ced8},
+      {0xa2425ff75e14fc31, 0xa1258379a94d028e},
+      {0xcad2f7f5359a3b3e, 0x096ee45813a04331},
+      {0xfd87b5f28300ca0d, 0x8bca9d6e188853fd},
+      {0x9e74d1b791e07e48, 0x775ea264cf55347e},
+      {0xc612062576589dda, 0x95364afe032a819e},
+      {0xf79687aed3eec551, 0x3a83ddbd83f52205},
+      {0x9abe14cd44753b52, 0xc4926a9672793543},
+      {0xc16d9a0095928a27, 0x75b7053c0f178294},
+      {0xf1c90080baf72cb1, 0x5324c68b12dd6339},
+      {0x971da05074da7bee, 0xd3f6fc16ebca5e04},
+      {0xbce5086492111aea, 0x88f4bb1ca6bcf585},
+      {0xec1e4a7db69561a5, 0x2b31e9e3d06c32e6},
+      {0x9392ee8e921d5d07, 0x3aff322e62439fd0},
+      {0xb877aa3236a4b449, 0x09befeb9fad487c3},
+      {0xe69594bec44de15b, 0x4c2ebe687989a9b4},
+      {0x901d7cf73ab0acd9, 0x0f9d37014bf60a11},
+      {0xb424dc35095cd80f, 0x538484c19ef38c95},
+      {0xe12e13424bb40e13, 0x2865a5f206b06fba},
+      {0x8cbccc096f5088cb, 0xf93f87b7442e45d4},
+      {0xafebff0bcb24aafe, 0xf78f69a51539d749},
+      {0xdbe6fecebdedd5be, 0xb573440e5a884d1c},
+      {0x89705f4136b4a597, 0x31680a88f8953031},
+      {0xabcc77118461cefc, 0xfdc20d2b36ba7c3e},
+      {0xd6bf94d5e57a42bc, 0x3d32907604691b4d},
+      {0x8637bd05af6c69b5, 0xa63f9a49c2c1b110},
+      {0xa7c5ac471b478423, 0x0fcf80dc33721d54},
+      {0xd1b71758e219652b, 0xd3c36113404ea4a9},
+      {0x83126e978d4fdf3b, 0x645a1cac083126ea},
+      {0xa3d70a3d70a3d70a, 0x3d70a3d70a3d70a4},
+      {0xcccccccccccccccc, 0xcccccccccccccccd},
+      {0x8000000000000000, 0x0000000000000000},
+      {0xa000000000000000, 0x0000000000000000},
+      {0xc800000000000000, 0x0000000000000000},
+      {0xfa00000000000000, 0x0000000000000000},
+      {0x9c40000000000000, 0x0000000000000000},
+      {0xc350000000000000, 0x0000000000000000},
+      {0xf424000000000000, 0x0000000000000000},
+      {0x9896800000000000, 0x0000000000000000},
+      {0xbebc200000000000, 0x0000000000000000},
+      {0xee6b280000000000, 0x0000000000000000},
+      {0x9502f90000000000, 0x0000000000000000},
+      {0xba43b74000000000, 0x0000000000000000},
+      {0xe8d4a51000000000, 0x0000000000000000},
+      {0x9184e72a00000000, 0x0000000000000000},
+      {0xb5e620f480000000, 0x0000000000000000},
+      {0xe35fa931a0000000, 0x0000000000000000},
+      {0x8e1bc9bf04000000, 0x0000000000000000},
+      {0xb1a2bc2ec5000000, 0x0000000000000000},
+      {0xde0b6b3a76400000, 0x0000000000000000},
+      {0x8ac7230489e80000, 0x0000000000000000},
+      {0xad78ebc5ac620000, 0x0000000000000000},
+      {0xd8d726b7177a8000, 0x0000000000000000},
+      {0x878678326eac9000, 0x0000000000000000},
+      {0xa968163f0a57b400, 0x0000000000000000},
+      {0xd3c21bcecceda100, 0x0000000000000000},
+      {0x84595161401484a0, 0x0000000000000000},
+      {0xa56fa5b99019a5c8, 0x0000000000000000},
+      {0xcecb8f27f4200f3a, 0x0000000000000000},
+      {0x813f3978f8940984, 0x4000000000000000},
+      {0xa18f07d736b90be5, 0x5000000000000000},
+      {0xc9f2c9cd04674ede, 0xa400000000000000},
+      {0xfc6f7c4045812296, 0x4d00000000000000},
+      {0x9dc5ada82b70b59d, 0xf020000000000000},
+      {0xc5371912364ce305, 0x6c28000000000000},
+      {0xf684df56c3e01bc6, 0xc732000000000000},
+      {0x9a130b963a6c115c, 0x3c7f400000000000},
+      {0xc097ce7bc90715b3, 0x4b9f100000000000},
+      {0xf0bdc21abb48db20, 0x1e86d40000000000},
+      {0x96769950b50d88f4, 0x1314448000000000},
+      {0xbc143fa4e250eb31, 0x17d955a000000000},
+      {0xeb194f8e1ae525fd, 0x5dcfab0800000000},
+      {0x92efd1b8d0cf37be, 0x5aa1cae500000000},
+      {0xb7abc627050305ad, 0xf14a3d9e40000000},
+      {0xe596b7b0c643c719, 0x6d9ccd05d0000000},
+      {0x8f7e32ce7bea5c6f, 0xe4820023a2000000},
+      {0xb35dbf821ae4f38b, 0xdda2802c8a800000},
+      {0xe0352f62a19e306e, 0xd50b2037ad200000},
+      {0x8c213d9da502de45, 0x4526f422cc340000},
+      {0xaf298d050e4395d6, 0x9670b12b7f410000},
+      {0xdaf3f04651d47b4c, 0x3c0cdd765f114000},
+      {0x88d8762bf324cd0f, 0xa5880a69fb6ac800},
+      {0xab0e93b6efee0053, 0x8eea0d047a457a00},
+      {0xd5d238a4abe98068, 0x72a4904598d6d880},
+      {0x85a36366eb71f041, 0x47a6da2b7f864750},
+      {0xa70c3c40a64e6c51, 0x999090b65f67d924},
+      {0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d},
+      {0x82818f1281ed449f, 0xbff8f10e7a8921a5},
+      {0xa321f2d7226895c7, 0xaff72d52192b6a0e},
+      {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764491},
+      {0xfee50b7025c36a08, 0x02f236d04753d5b5},
+      {0x9f4f2726179a2245, 0x01d762422c946591},
+      {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef6},
+      {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb3},
+      {0x9b934c3b330c8577, 0x63cc55f49f88eb30},
+      {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fc},
+      {0xf316271c7fc3908a, 0x8bef464e3945ef7b},
+      {0x97edd871cfda3a56, 0x97758bf0e3cbb5ad},
+      {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea318},
+      {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bde},
+      {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6b},
+      {0xb975d6b6ee39e436, 0xb3e2fd538e122b45},
+      {0xe7d34c64a9c85d44, 0x60dbbca87196b617},
+      {0x90e40fbeea1d3a4a, 0xbc8955e946fe31ce},
+      {0xb51d13aea4a488dd, 0x6babab6398bdbe42},
+      {0xe264589a4dcdab14, 0xc696963c7eed2dd2},
+      {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca3},
+      {0xb0de65388cc8ada8, 0x3b25a55f43294bcc},
+      {0xdd15fe86affad912, 0x49ef0eb713f39ebf},
+      {0x8a2dbf142dfcc7ab, 0x6e3569326c784338},
+      {0xacb92ed9397bf996, 0x49c2c37f07965405},
+      {0xd7e77a8f87daf7fb, 0xdc33745ec97be907},
+      {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a4},
+      {0xa8acd7c0222311bc, 0xc40832ea0d68ce0d},
+      {0xd2d80db02aabd62b, 0xf50a3fa490c30191},
+      {0x83c7088e1aab65db, 0x792667c6da79e0fb},
+      {0xa4b8cab1a1563f52, 0x577001b891185939},
+      {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87},
+      {0x80b05e5ac60b6178, 0x544f8158315b05b5},
+      {0xa0dc75f1778e39d6, 0x696361ae3db1c722},
+      {0xc913936dd571c84c, 0x03bc3a19cd1e38ea},
+      {0xfb5878494ace3a5f, 0x04ab48a04065c724},
+      {0x9d174b2dcec0e47b, 0x62eb0d64283f9c77},
+      {0xc45d1df942711d9a, 0x3ba5d0bd324f8395},
+      {0xf5746577930d6500, 0xca8f44ec7ee3647a},
+      {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecc},
+      {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67f},
+      {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101f},
+      {0x95d04aee3b80ece5, 0xbba1f1d158724a13},
+      {0xbb445da9ca61281f, 0x2a8a6e45ae8edc98},
+      {0xea1575143cf97226, 0xf52d09d71a3293be},
+      {0x924d692ca61be758, 0x593c2626705f9c57},
+      {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836d},
+      {0xe498f455c38b997a, 0x0b6dfb9c0f956448},
+      {0x8edf98b59a373fec, 0x4724bd4189bd5ead},
+      {0xb2977ee300c50fe7, 0x58edec91ec2cb658},
+      {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ee},
+      {0x8b865b215899f46c, 0xbd79e0d20082ee75},
+      {0xae67f1e9aec07187, 0xecd8590680a3aa12},
+      {0xda01ee641a708de9, 0xe80e6f4820cc9496},
+      {0x884134fe908658b2, 0x3109058d147fdcde},
+      {0xaa51823e34a7eede, 0xbd4b46f0599fd416},
+      {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91b},
+      {0x850fadc09923329e, 0x03e2cf6bc604ddb1},
+      {0xa6539930bf6bff45, 0x84db8346b786151d},
+      {0xcfe87f7cef46ff16, 0xe612641865679a64},
+      {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07f},
+      {0xa26da3999aef7749, 0xe3be5e330f38f09e},
+      {0xcb090c8001ab551c, 0x5cadf5bfd3072cc6},
+      {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f7},
+      {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afb},
+      {0xc646d63501a1511d, 0xb281e1fd541501b9},
+      {0xf7d88bc24209a565, 0x1f225a7ca91a4227},
+      {0x9ae757596946075f, 0x3375788de9b06959},
+      {0xc1a12d2fc3978937, 0x0052d6b1641c83af},
+      {0xf209787bb47d6b84, 0xc0678c5dbd23a49b},
+      {0x9745eb4d50ce6332, 0xf840b7ba963646e1},
+      {0xbd176620a501fbff, 0xb650e5a93bc3d899},
+      {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebf},
+      {0x93ba47c980e98cdf, 0xc66f336c36b10138},
+      {0xb8a8d9bbe123f017, 0xb80b0047445d4185},
+      {0xe6d3102ad96cec1d, 0xa60dc059157491e6},
+      {0x9043ea1ac7e41392, 0x87c89837ad68db30},
+      {0xb454e4a179dd1877, 0x29babe4598c311fc},
+      {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67b},
+      {0x8ce2529e2734bb1d, 0x1899e4a65f58660d},
+      {0xb01ae745b101e9e4, 0x5ec05dcff72e7f90},
+      {0xdc21a1171d42645d, 0x76707543f4fa1f74},
+      {0x899504ae72497eba, 0x6a06494a791c53a9},
+      {0xabfa45da0edbde69, 0x0487db9d17636893},
+      {0xd6f8d7509292d603, 0x45a9d2845d3c42b7},
+      {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3},
+      {0xa7f26836f282b732, 0x8e6cac7768d7141f},
+      {0xd1ef0244af2364ff, 0x3207d795430cd927},
+      {0x8335616aed761f1f, 0x7f44e6bd49e807b9},
+      {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a7},
+      {0xcd036837130890a1, 0x36dba887c37a8c10},
+      {0x802221226be55a64, 0xc2494954da2c978a},
+      {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6d},
+      {0xc83553c5c8965d3d, 0x6f92829494e5acc8},
+      {0xfa42a8b73abbf48c, 0xcb772339ba1f17fa},
+      {0x9c69a97284b578d7, 0xff2a760414536efc},
+      {0xc38413cf25e2d70d, 0xfef5138519684abb},
+      {0xf46518c2ef5b8cd1, 0x7eb258665fc25d6a},
+      {0x98bf2f79d5993802, 0xef2f773ffbd97a62},
+      {0xbeeefb584aff8603, 0xaafb550ffacfd8fb},
+      {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf39},
+      {0x952ab45cfa97a0b2, 0xdd945a747bf26184},
+      {0xba756174393d88df, 0x94f971119aeef9e5},
+      {0xe912b9d1478ceb17, 0x7a37cd5601aab85e},
+      {0x91abb422ccb812ee, 0xac62e055c10ab33b},
+      {0xb616a12b7fe617aa, 0x577b986b314d600a},
+      {0xe39c49765fdf9d94, 0xed5a7e85fda0b80c},
+      {0x8e41ade9fbebc27d, 0x14588f13be847308},
+      {0xb1d219647ae6b31c, 0x596eb2d8ae258fc9},
+      {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bc},
+      {0x8aec23d680043bee, 0x25de7bb9480d5855},
+      {0xada72ccc20054ae9, 0xaf561aa79a10ae6b},
+      {0xd910f7ff28069da4, 0x1b2ba1518094da05},
+      {0x87aa9aff79042286, 0x90fb44d2f05d0843},
+      {0xa99541bf57452b28, 0x353a1607ac744a54},
+      {0xd3fa922f2d1675f2, 0x42889b8997915ce9},
+      {0x847c9b5d7c2e09b7, 0x69956135febada12},
+      {0xa59bc234db398c25, 0x43fab9837e699096},
+      {0xcf02b2c21207ef2e, 0x94f967e45e03f4bc},
+      {0x8161afb94b44f57d, 0x1d1be0eebac278f6},
+      {0xa1ba1ba79e1632dc, 0x6462d92a69731733},
+      {0xca28a291859bbf93, 0x7d7b8f7503cfdcff},
+      {0xfcb2cb35e702af78, 0x5cda735244c3d43f},
+      {0x9defbf01b061adab, 0x3a0888136afa64a8},
+      {0xc56baec21c7a1916, 0x088aaa1845b8fdd1},
+      {0xf6c69a72a3989f5b, 0x8aad549e57273d46},
+      {0x9a3c2087a63f6399, 0x36ac54e2f678864c},
+      {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7de},
+      {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d6},
+      {0x969eb7c47859e743, 0x9f644ae5a4b1b326},
+      {0xbc4665b596706114, 0x873d5d9f0dde1fef},
+      {0xeb57ff22fc0c7959, 0xa90cb506d155a7eb},
+      {0x9316ff75dd87cbd8, 0x09a7f12442d588f3},
+      {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb30},
+      {0xe5d3ef282a242e81, 0x8f1668c8a86da5fb},
+      {0x8fa475791a569d10, 0xf96e017d694487bd},
+      {0xb38d92d760ec4455, 0x37c981dcc395a9ad},
+      {0xe070f78d3927556a, 0x85bbe253f47b1418},
+      {0x8c469ab843b89562, 0x93956d7478ccec8f},
+      {0xaf58416654a6babb, 0x387ac8d1970027b3},
+      {0xdb2e51bfe9d0696a, 0x06997b05fcc0319f},
+      {0x88fcf317f22241e2, 0x441fece3bdf81f04},
+      {0xab3c2fddeeaad25a, 0xd527e81cad7626c4},
+      {0xd60b3bd56a5586f1, 0x8a71e223d8d3b075},
+      {0x85c7056562757456, 0xf6872d5667844e4a},
+      {0xa738c6bebb12d16c, 0xb428f8ac016561dc},
+      {0xd106f86e69d785c7, 0xe13336d701beba53},
+      {0x82a45b450226b39c, 0xecc0024661173474},
+      {0xa34d721642b06084, 0x27f002d7f95d0191},
+      {0xcc20ce9bd35c78a5, 0x31ec038df7b441f5},
+      {0xff290242c83396ce, 0x7e67047175a15272},
+      {0x9f79a169bd203e41, 0x0f0062c6e984d387},
+      {0xc75809c42c684dd1, 0x52c07b78a3e60869},
+      {0xf92e0c3537826145, 0xa7709a56ccdf8a83},
+      {0x9bbcc7a142b17ccb, 0x88a66076400bb692},
+      {0xc2abf989935ddbfe, 0x6acff893d00ea436},
+      {0xf356f7ebf83552fe, 0x0583f6b8c4124d44},
+      {0x98165af37b2153de, 0xc3727a337a8b704b},
+      {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5d},
+      {0xeda2ee1c7064130c, 0x1162def06f79df74},
+      {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba9},
+      {0xb9a74a0637ce2ee1, 0x6d953e2bd7173693},
+      {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0438},
+      {0x910ab1d4db9914a0, 0x1d9c9892400a22a3},
+      {0xb54d5e4a127f59c8, 0x2503beb6d00cab4c},
+      {0xe2a0b5dc971f303a, 0x2e44ae64840fd61e},
+      {0x8da471a9de737e24, 0x5ceaecfed289e5d3},
+      {0xb10d8e1456105dad, 0x7425a83e872c5f48},
+      {0xdd50f1996b947518, 0xd12f124e28f7771a},
+      {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa70},
+      {0xace73cbfdc0bfb7b, 0x636cc64d1001550c},
+      {0xd8210befd30efa5a, 0x3c47f7e05401aa4f},
+      {0x8714a775e3e95c78, 0x65acfaec34810a72},
+      {0xa8d9d1535ce3b396, 0x7f1839a741a14d0e},
+      {0xd31045a8341ca07c, 0x1ede48111209a051},
+      {0x83ea2b892091e44d, 0x934aed0aab460433},
+      {0xa4e4b66b68b65d60, 0xf81da84d56178540},
+      {0xce1de40642e3f4b9, 0x36251260ab9d668f},
+      {0x80d2ae83e9ce78f3, 0xc1d72b7c6b42601a},
+      {0xa1075a24e4421730, 0xb24cf65b8612f820},
+      {0xc94930ae1d529cfc, 0xdee033f26797b628},
+      {0xfb9b7cd9a4a7443c, 0x169840ef017da3b2},
+      {0x9d412e0806e88aa5, 0x8e1f289560ee864f},
+      {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e3},
+      {0xf5b5d7ec8acb58a2, 0xae10af696774b1dc},
+      {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef2a},
+      {0xbff610b0cc6edd3f, 0x17fd090a58d32af4},
+      {0xeff394dcff8a948e, 0xddfc4b4cef07f5b1},
+      {0x95f83d0a1fb69cd9, 0x4abdaf101564f98f},
+      {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f2},
+      {0xea53df5fd18d5513, 0x84c86189216dc5ee},
+      {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb5},
+      {0xb7118682dbb66a77, 0x3fbc8c33221dc2a2},
+      {0xe4d5e82392a40515, 0x0fabaf3feaa5334b},
+      {0x8f05b1163ba6832d, 0x29cb4d87f2a7400f},
+      {0xb2c71d5bca9023f8, 0x743e20e9ef511013},
+      {0xdf78e4b2bd342cf6, 0x914da9246b255417},
+      {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548f},
+      {0xae9672aba3d0c320, 0xa184ac2473b529b2},
+      {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741f},
+      {0x8865899617fb1871, 0x7e2fa67c7a658893},
+      {0xaa7eebfb9df9de8d, 0xddbb901b98feeab8},
+      {0xd51ea6fa85785631, 0x552a74227f3ea566},
+      {0x8533285c936b35de, 0xd53a88958f872760},
+      {0xa67ff273b8460356, 0x8a892abaf368f138},
+      {0xd01fef10a657842c, 0x2d2b7569b0432d86},
+      {0x8213f56a67f6b29b, 0x9c3b29620e29fc74},
+      {0xa298f2c501f45f42, 0x8349f3ba91b47b90},
+      {0xcb3f2f7642717713, 0x241c70a936219a74},
+      {0xfe0efb53d30dd4d7, 0xed238cd383aa0111},
+      {0x9ec95d1463e8a506, 0xf4363804324a40ab},
+      {0xc67bb4597ce2ce48, 0xb143c6053edcd0d6},
+      {0xf81aa16fdc1b81da, 0xdd94b7868e94050b},
+      {0x9b10a4e5e9913128, 0xca7cf2b4191c8327},
+      {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f1},
+      {0xf24a01a73cf2dccf, 0xbc633b39673c8ced},
+      {0x976e41088617ca01, 0xd5be0503e085d814},
+      {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e19},
+      {0xec9c459d51852ba2, 0xddf8e7d60ed1219f},
+      {0x93e1ab8252f33b45, 0xcabb90e5c942b504},
+      {0xb8da1662e7b00a17, 0x3d6a751f3b936244},
+      {0xe7109bfba19c0c9d, 0x0cc512670a783ad5},
+      {0x906a617d450187e2, 0x27fb2b80668b24c6},
+      {0xb484f9dc9641e9da, 0xb1f9f660802dedf7},
+      {0xe1a63853bbd26451, 0x5e7873f8a0396974},
+      {0x8d07e33455637eb2, 0xdb0b487b6423e1e9},
+      {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda63},
+      {0xdc5c5301c56b75f7, 0x7641a140cc7810fc},
+      {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9e},
+      {0xac2820d9623bf429, 0x546345fa9fbdcd45},
+      {0xd732290fbacaf133, 0xa97c177947ad4096},
+      {0x867f59a9d4bed6c0, 0x49ed8eabcccc485e},
+      {0xa81f301449ee8c70, 0x5c68f256bfff5a75},
+      {0xd226fc195c6a2f8c, 0x73832eec6fff3112},
+      {0x83585d8fd9c25db7, 0xc831fd53c5ff7eac},
+      {0xa42e74f3d032f525, 0xba3e7ca8b77f5e56},
+      {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35ec},
+      {0x80444b5e7aa7cf85, 0x7980d163cf5b81b4},
+      {0xa0555e361951c366, 0xd7e105bcc3326220},
+      {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa8},
+      {0xfa856334878fc150, 0xb14f98f6f0feb952},
+      {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d4},
+      {0xc3b8358109e84f07, 0x0a862f80ec4700c9},
+      {0xf4a642e14c6262c8, 0xcd27bb612758c0fb},
+      {0x98e7e9cccfbd7dbd, 0x8038d51cb897789d},
+      {0xbf21e44003acdd2c, 0xe0470a63e6bd56c4},
+      {0xeeea5d5004981478, 0x1858ccfce06cac75},
+      {0x95527a5202df0ccb, 0x0f37801e0c43ebc9},
+      {0xbaa718e68396cffd, 0xd30560258f54e6bb},
+      {0xe950df20247c83fd, 0x47c6b82ef32a206a},
+      {0x91d28b7416cdd27e, 0x4cdc331d57fa5442},
+      {0xb6472e511c81471d, 0xe0133fe4adf8e953},
+      {0xe3d8f9e563a198e5, 0x58180fddd97723a7},
+      {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7649},
+      {0xb201833b35d63f73, 0x2cd2cc6551e513db},
+      {0xde81e40a034bcf4f, 0xf8077f7ea65e58d2},
+      {0x8b112e86420f6191, 0xfb04afaf27faf783},
+      {0xadd57a27d29339f6, 0x79c5db9af1f9b564},
+      {0xd94ad8b1c7380874, 0x18375281ae7822bd},
+      {0x87cec76f1c830548, 0x8f2293910d0b15b6},
+      {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb23},
+      {0xd433179d9c8cb841, 0x5fa60692a46151ec},
+      {0x849feec281d7f328, 0xdbc7c41ba6bcd334},
+      {0xa5c7ea73224deff3, 0x12b9b522906c0801},
+      {0xcf39e50feae16bef, 0xd768226b34870a01},
+      {0x81842f29f2cce375, 0xe6a1158300d46641},
+      {0xa1e53af46f801c53, 0x60495ae3c1097fd1},
+      {0xca5e89b18b602368, 0x385bb19cb14bdfc5},
+      {0xfcf62c1dee382c42, 0x46729e03dd9ed7b6},
+      {0x9e19db92b4e31ba9, 0x6c07a2c26a8346d2},
+      {0xc5a05277621be293, 0xc7098b7305241886},
+      {0xf70867153aa2db38, 0xb8cbee4fc66d1ea8},
+      {0x9a65406d44a5c903, 0x737f74f1dc043329},
+      {0xc0fe908895cf3b44, 0x505f522e53053ff3},
+      {0xf13e34aabb430a15, 0x647726b9e7c68ff0},
+      {0x96c6e0eab509e64d, 0x5eca783430dc19f6},
+      {0xbc789925624c5fe0, 0xb67d16413d132073},
+      {0xeb96bf6ebadf77d8, 0xe41c5bd18c57e890},
+      {0x933e37a534cbaae7, 0x8e91b962f7b6f15a},
+      {0xb80dc58e81fe95a1, 0x723627bbb5a4adb1},
+      {0xe61136f2227e3b09, 0xcec3b1aaa30dd91d},
+      {0x8fcac257558ee4e6, 0x213a4f0aa5e8a7b2},
+      {0xb3bd72ed2af29e1f, 0xa988e2cd4f62d19e},
+      {0xe0accfa875af45a7, 0x93eb1b80a33b8606},
+      {0x8c6c01c9498d8b88, 0xbc72f130660533c4},
+      {0xaf87023b9bf0ee6a, 0xeb8fad7c7f8680b5},
+      {0xdb68c2ca82ed2a05, 0xa67398db9f6820e2},
+#else
+      {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b},
+      {0xce5d73ff402d98e3, 0xfb0a3d212dc81290},
+      {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f},
+      {0x86a8d39ef77164bc, 0xae5dff9c02033198},
+      {0xd98ddaee19068c76, 0x3badd624dd9b0958},
+      {0xafbd2350644eeacf, 0xe5d1929ef90898fb},
+      {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2},
+      {0xe55990879ddcaabd, 0xcc420a6a101d0516},
+      {0xb94470938fa89bce, 0xf808e40e8d5b3e6a},
+      {0x95a8637627989aad, 0xdde7001379a44aa9},
+      {0xf1c90080baf72cb1, 0x5324c68b12dd6339},
+      {0xc350000000000000, 0x0000000000000000},
+      {0x9dc5ada82b70b59d, 0xf020000000000000},
+      {0xfee50b7025c36a08, 0x02f236d04753d5b5},
+      {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87},
+      {0xa6539930bf6bff45, 0x84db8346b786151d},
+      {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3},
+      {0xd910f7ff28069da4, 0x1b2ba1518094da05},
+      {0xaf58416654a6babb, 0x387ac8d1970027b3},
+      {0x8da471a9de737e24, 0x5ceaecfed289e5d3},
+      {0xe4d5e82392a40515, 0x0fabaf3feaa5334b},
+      {0xb8da1662e7b00a17, 0x3d6a751f3b936244},
+      {0x95527a5202df0ccb, 0x0f37801e0c43ebc9},
+      {0xf13e34aabb430a15, 0x647726b9e7c68ff0}
+#endif
+    };
+
+#if FMT_USE_FULL_CACHE_DRAGONBOX
+    return pow10_significands[k - float_info<double>::min_k];
+#else
+    static constexpr uint64_t powers_of_5_64[] = {
+        0x0000000000000001, 0x0000000000000005, 0x0000000000000019,
+        0x000000000000007d, 0x0000000000000271, 0x0000000000000c35,
+        0x0000000000003d09, 0x000000000001312d, 0x000000000005f5e1,
+        0x00000000001dcd65, 0x00000000009502f9, 0x0000000002e90edd,
+        0x000000000e8d4a51, 0x0000000048c27395, 0x000000016bcc41e9,
+        0x000000071afd498d, 0x0000002386f26fc1, 0x000000b1a2bc2ec5,
+        0x000003782dace9d9, 0x00001158e460913d, 0x000056bc75e2d631,
+        0x0001b1ae4d6e2ef5, 0x000878678326eac9, 0x002a5a058fc295ed,
+        0x00d3c21bcecceda1, 0x0422ca8b0a00a425, 0x14adf4b7320334b9};
+
+    static const int compression_ratio = 27;
+
+    // Compute base index.
+    int cache_index = (k - float_info<double>::min_k) / compression_ratio;
+    int kb = cache_index * compression_ratio + float_info<double>::min_k;
+    int offset = k - kb;
+
+    // Get base cache.
+    uint128_fallback base_cache = pow10_significands[cache_index];
+    if (offset == 0) return base_cache;
+
+    // Compute the required amount of bit-shift.
+    int alpha = floor_log2_pow10(kb + offset) - floor_log2_pow10(kb) - offset;
+    FMT_ASSERT(alpha > 0 && alpha < 64, "shifting error detected");
+
+    // Try to recover the real cache.
+    uint64_t pow5 = powers_of_5_64[offset];
+    uint128_fallback recovered_cache = umul128(base_cache.high(), pow5);
+    uint128_fallback middle_low = umul128(base_cache.low(), pow5);
+
+    recovered_cache += middle_low.high();
+
+    uint64_t high_to_middle = recovered_cache.high() << (64 - alpha);
+    uint64_t middle_to_low = recovered_cache.low() << (64 - alpha);
+
+    recovered_cache =
+        uint128_fallback{(recovered_cache.low() >> alpha) | high_to_middle,
+                         ((middle_low.low() >> alpha) | middle_to_low)};
+    FMT_ASSERT(recovered_cache.low() + 1 != 0, "");
+    return {recovered_cache.high(), recovered_cache.low() + 1};
+#endif
+  }
+
+  struct compute_mul_result {
+    carrier_uint result;
+    bool is_integer;
+  };
+  struct compute_mul_parity_result {
+    bool parity;
+    bool is_integer;
+  };
+
+  static auto compute_mul(carrier_uint u,
+                          const cache_entry_type& cache) noexcept
+      -> compute_mul_result {
+    auto r = umul192_upper128(u, cache);
+    return {r.high(), r.low() == 0};
+  }
+
+  static auto compute_delta(const cache_entry_type& cache, int beta) noexcept
+      -> uint32_t {
+    return static_cast<uint32_t>(cache.high() >> (64 - 1 - beta));
+  }
+
+  static auto compute_mul_parity(carrier_uint two_f,
+                                 const cache_entry_type& cache,
+                                 int beta) noexcept
+      -> compute_mul_parity_result {
+    FMT_ASSERT(beta >= 1, "");
+    FMT_ASSERT(beta < 64, "");
+
+    auto r = umul192_lower128(two_f, cache);
+    return {((r.high() >> (64 - beta)) & 1) != 0,
+            ((r.high() << beta) | (r.low() >> (64 - beta))) == 0};
+  }
+
+  static auto compute_left_endpoint_for_shorter_interval_case(
+      const cache_entry_type& cache, int beta) noexcept -> carrier_uint {
+    return (cache.high() -
+            (cache.high() >> (num_significand_bits<double>() + 2))) >>
+           (64 - num_significand_bits<double>() - 1 - beta);
+  }
+
+  static auto compute_right_endpoint_for_shorter_interval_case(
+      const cache_entry_type& cache, int beta) noexcept -> carrier_uint {
+    return (cache.high() +
+            (cache.high() >> (num_significand_bits<double>() + 1))) >>
+           (64 - num_significand_bits<double>() - 1 - beta);
+  }
+
+  static auto compute_round_up_for_shorter_interval_case(
+      const cache_entry_type& cache, int beta) noexcept -> carrier_uint {
+    return ((cache.high() >> (64 - num_significand_bits<double>() - 2 - beta)) +
+            1) /
+           2;
+  }
+};
+
+FMT_FUNC auto get_cached_power(int k) noexcept -> uint128_fallback {
+  return cache_accessor<double>::get_cached_power(k);
+}
+
+// Various integer checks
+template <typename T>
+auto is_left_endpoint_integer_shorter_interval(int exponent) noexcept -> bool {
+  const int case_shorter_interval_left_endpoint_lower_threshold = 2;
+  const int case_shorter_interval_left_endpoint_upper_threshold = 3;
+  return exponent >= case_shorter_interval_left_endpoint_lower_threshold &&
+         exponent <= case_shorter_interval_left_endpoint_upper_threshold;
+}
+
+// Remove trailing zeros from n and return the number of zeros removed (float).
+FMT_INLINE auto remove_trailing_zeros(uint32_t& n, int s = 0) noexcept -> int {
+  FMT_ASSERT(n != 0, "");
+  // Modular inverse of 5 (mod 2^32): (mod_inv_5 * 5) mod 2^32 = 1.
+  constexpr uint32_t mod_inv_5 = 0xcccccccd;
+  constexpr uint32_t mod_inv_25 = 0xc28f5c29;  // = mod_inv_5 * mod_inv_5
+
+  while (true) {
+    auto q = rotr(n * mod_inv_25, 2);
+    if (q > max_value<uint32_t>() / 100) break;
+    n = q;
+    s += 2;
+  }
+  auto q = rotr(n * mod_inv_5, 1);
+  if (q <= max_value<uint32_t>() / 10) {
+    n = q;
+    s |= 1;
+  }
+  return s;
+}
+
+// Removes trailing zeros and returns the number of zeros removed (double).
+FMT_INLINE auto remove_trailing_zeros(uint64_t& n) noexcept -> int {
+  FMT_ASSERT(n != 0, "");
+
+  // Is n is divisible by 10^8?
+  constexpr uint32_t ten_pow_8 = 100000000u;
+  if ((n % ten_pow_8) == 0) {
+    // If yes, work with the quotient...
+    auto n32 = static_cast<uint32_t>(n / ten_pow_8);
+    // ... and use the 32 bit variant of the function
+    int num_zeros = remove_trailing_zeros(n32, 8);
+    n = n32;
+    return num_zeros;
+  }
+
+  // If n is not divisible by 10^8, work with n itself.
+  constexpr uint64_t mod_inv_5 = 0xcccccccccccccccd;
+  constexpr uint64_t mod_inv_25 = 0x8f5c28f5c28f5c29;  // mod_inv_5 * mod_inv_5
+
+  int s = 0;
+  while (true) {
+    auto q = rotr(n * mod_inv_25, 2);
+    if (q > max_value<uint64_t>() / 100) break;
+    n = q;
+    s += 2;
+  }
+  auto q = rotr(n * mod_inv_5, 1);
+  if (q <= max_value<uint64_t>() / 10) {
+    n = q;
+    s |= 1;
+  }
+
+  return s;
+}
+
+// The main algorithm for shorter interval case
+template <typename T>
+FMT_INLINE auto shorter_interval_case(int exponent) noexcept -> decimal_fp<T> {
+  decimal_fp<T> ret_value;
+  // Compute k and beta
+  const int minus_k = floor_log10_pow2_minus_log10_4_over_3(exponent);
+  const int beta = exponent + floor_log2_pow10(-minus_k);
+
+  // Compute xi and zi
+  using cache_entry_type = typename cache_accessor<T>::cache_entry_type;
+  const cache_entry_type cache = cache_accessor<T>::get_cached_power(-minus_k);
+
+  auto xi = cache_accessor<T>::compute_left_endpoint_for_shorter_interval_case(
+      cache, beta);
+  auto zi = cache_accessor<T>::compute_right_endpoint_for_shorter_interval_case(
+      cache, beta);
+
+  // If the left endpoint is not an integer, increase it
+  if (!is_left_endpoint_integer_shorter_interval<T>(exponent)) ++xi;
+
+  // Try bigger divisor
+  ret_value.significand = zi / 10;
+
+  // If succeed, remove trailing zeros if necessary and return
+  if (ret_value.significand * 10 >= xi) {
+    ret_value.exponent = minus_k + 1;
+    ret_value.exponent += remove_trailing_zeros(ret_value.significand);
+    return ret_value;
+  }
+
+  // Otherwise, compute the round-up of y
+  ret_value.significand =
+      cache_accessor<T>::compute_round_up_for_shorter_interval_case(cache,
+                                                                    beta);
+  ret_value.exponent = minus_k;
+
+  // When tie occurs, choose one of them according to the rule
+  if (exponent >= float_info<T>::shorter_interval_tie_lower_threshold &&
+      exponent <= float_info<T>::shorter_interval_tie_upper_threshold) {
+    ret_value.significand = ret_value.significand % 2 == 0
+                                ? ret_value.significand
+                                : ret_value.significand - 1;
+  } else if (ret_value.significand < xi) {
+    ++ret_value.significand;
+  }
+  return ret_value;
+}
+
+template <typename T> auto to_decimal(T x) noexcept -> decimal_fp<T> {
+  // Step 1: integer promotion & Schubfach multiplier calculation.
+
+  using carrier_uint = typename float_info<T>::carrier_uint;
+  using cache_entry_type = typename cache_accessor<T>::cache_entry_type;
+  auto br = bit_cast<carrier_uint>(x);
+
+  // Extract significand bits and exponent bits.
+  const carrier_uint significand_mask =
+      (static_cast<carrier_uint>(1) << num_significand_bits<T>()) - 1;
+  carrier_uint significand = (br & significand_mask);
+  int exponent =
+      static_cast<int>((br & exponent_mask<T>()) >> num_significand_bits<T>());
+
+  if (exponent != 0) {  // Check if normal.
+    exponent -= exponent_bias<T>() + num_significand_bits<T>();
+
+    // Shorter interval case; proceed like Schubfach.
+    // In fact, when exponent == 1 and significand == 0, the interval is
+    // regular. However, it can be shown that the end-results are anyway same.
+    if (significand == 0) return shorter_interval_case<T>(exponent);
+
+    significand |= (static_cast<carrier_uint>(1) << num_significand_bits<T>());
+  } else {
+    // Subnormal case; the interval is always regular.
+    if (significand == 0) return {0, 0};
+    exponent =
+        std::numeric_limits<T>::min_exponent - num_significand_bits<T>() - 1;
+  }
+
+  const bool include_left_endpoint = (significand % 2 == 0);
+  const bool include_right_endpoint = include_left_endpoint;
+
+  // Compute k and beta.
+  const int minus_k = floor_log10_pow2(exponent) - float_info<T>::kappa;
+  const cache_entry_type cache = cache_accessor<T>::get_cached_power(-minus_k);
+  const int beta = exponent + floor_log2_pow10(-minus_k);
+
+  // Compute zi and deltai.
+  // 10^kappa <= deltai < 10^(kappa + 1)
+  const uint32_t deltai = cache_accessor<T>::compute_delta(cache, beta);
+  const carrier_uint two_fc = significand << 1;
+
+  // For the case of binary32, the result of integer check is not correct for
+  // 29711844 * 2^-82
+  // = 6.1442653300000000008655037797566933477355632930994033813476... * 10^-18
+  // and 29711844 * 2^-81
+  // = 1.2288530660000000001731007559513386695471126586198806762695... * 10^-17,
+  // and they are the unique counterexamples. However, since 29711844 is even,
+  // this does not cause any problem for the endpoints calculations; it can only
+  // cause a problem when we need to perform integer check for the center.
+  // Fortunately, with these inputs, that branch is never executed, so we are
+  // fine.
+  const typename cache_accessor<T>::compute_mul_result z_mul =
+      cache_accessor<T>::compute_mul((two_fc | 1) << beta, cache);
+
+  // Step 2: Try larger divisor; remove trailing zeros if necessary.
+
+  // Using an upper bound on zi, we might be able to optimize the division
+  // better than the compiler; we are computing zi / big_divisor here.
+  decimal_fp<T> ret_value;
+  ret_value.significand = divide_by_10_to_kappa_plus_1(z_mul.result);
+  uint32_t r = static_cast<uint32_t>(z_mul.result - float_info<T>::big_divisor *
+                                                        ret_value.significand);
+
+  if (r < deltai) {
+    // Exclude the right endpoint if necessary.
+    if (r == 0 && (z_mul.is_integer & !include_right_endpoint)) {
+      --ret_value.significand;
+      r = float_info<T>::big_divisor;
+      goto small_divisor_case_label;
+    }
+  } else if (r > deltai) {
+    goto small_divisor_case_label;
+  } else {
+    // r == deltai; compare fractional parts.
+    const typename cache_accessor<T>::compute_mul_parity_result x_mul =
+        cache_accessor<T>::compute_mul_parity(two_fc - 1, cache, beta);
+
+    if (!(x_mul.parity | (x_mul.is_integer & include_left_endpoint)))
+      goto small_divisor_case_label;
+  }
+  ret_value.exponent = minus_k + float_info<T>::kappa + 1;
+
+  // We may need to remove trailing zeros.
+  ret_value.exponent += remove_trailing_zeros(ret_value.significand);
+  return ret_value;
+
+  // Step 3: Find the significand with the smaller divisor.
+
+small_divisor_case_label:
+  ret_value.significand *= 10;
+  ret_value.exponent = minus_k + float_info<T>::kappa;
+
+  uint32_t dist = r - (deltai / 2) + (float_info<T>::small_divisor / 2);
+  const bool approx_y_parity =
+      ((dist ^ (float_info<T>::small_divisor / 2)) & 1) != 0;
+
+  // Is dist divisible by 10^kappa?
+  const bool divisible_by_small_divisor =
+      check_divisibility_and_divide_by_pow10<float_info<T>::kappa>(dist);
+
+  // Add dist / 10^kappa to the significand.
+  ret_value.significand += dist;
+
+  if (!divisible_by_small_divisor) return ret_value;
+
+  // Check z^(f) >= epsilon^(f).
+  // We have either yi == zi - epsiloni or yi == (zi - epsiloni) - 1,
+  // where yi == zi - epsiloni if and only if z^(f) >= epsilon^(f).
+  // Since there are only 2 possibilities, we only need to care about the
+  // parity. Also, zi and r should have the same parity since the divisor
+  // is an even number.
+  const auto y_mul = cache_accessor<T>::compute_mul_parity(two_fc, cache, beta);
+
+  // If z^(f) >= epsilon^(f), we might have a tie when z^(f) == epsilon^(f),
+  // or equivalently, when y is an integer.
+  if (y_mul.parity != approx_y_parity)
+    --ret_value.significand;
+  else if (y_mul.is_integer & (ret_value.significand % 2 != 0))
+    --ret_value.significand;
+  return ret_value;
+}
+}  // namespace dragonbox
+}  // namespace detail
+
+template <> struct formatter<detail::bigint> {
+  FMT_CONSTEXPR auto parse(format_parse_context& ctx)
+      -> format_parse_context::iterator {
+    return ctx.begin();
+  }
+
+  auto format(const detail::bigint& n, format_context& ctx) const
+      -> format_context::iterator {
+    auto out = ctx.out();
+    bool first = true;
+    for (auto i = n.bigits_.size(); i > 0; --i) {
+      auto value = n.bigits_[i - 1u];
+      if (first) {
+        out = fmt::format_to(out, FMT_STRING("{:x}"), value);
+        first = false;
+        continue;
+      }
+      out = fmt::format_to(out, FMT_STRING("{:08x}"), value);
+    }
+    if (n.exp_ > 0)
+      out = fmt::format_to(out, FMT_STRING("p{}"),
+                           n.exp_ * detail::bigint::bigit_bits);
+    return out;
+  }
+};
+
+FMT_FUNC detail::utf8_to_utf16::utf8_to_utf16(string_view s) {
+  for_each_codepoint(s, [this](uint32_t cp, string_view) {
+    if (cp == invalid_code_point) FMT_THROW(std::runtime_error("invalid utf8"));
+    if (cp <= 0xFFFF) {
+      buffer_.push_back(static_cast<wchar_t>(cp));
+    } else {
+      cp -= 0x10000;
+      buffer_.push_back(static_cast<wchar_t>(0xD800 + (cp >> 10)));
+      buffer_.push_back(static_cast<wchar_t>(0xDC00 + (cp & 0x3FF)));
+    }
+    return true;
+  });
+  buffer_.push_back(0);
+}
+
+FMT_FUNC void format_system_error(detail::buffer<char>& out, int error_code,
+                                  const char* message) noexcept {
+  FMT_TRY {
+    auto ec = std::error_code(error_code, std::generic_category());
+    detail::write(appender(out), std::system_error(ec, message).what());
+    return;
+  }
+  FMT_CATCH(...) {}
+  format_error_code(out, error_code, message);
+}
+
+FMT_FUNC void report_system_error(int error_code,
+                                  const char* message) noexcept {
+  do_report_error(format_system_error, error_code, message);
+}
+
+FMT_FUNC auto vformat(string_view fmt, format_args args) -> std::string {
+  // Don't optimize the "{}" case to keep the binary size small and because it
+  // can be better optimized in fmt::format anyway.
+  auto buffer = memory_buffer();
+  detail::vformat_to(buffer, fmt, args);
+  return to_string(buffer);
+}
+
+namespace detail {
+
+FMT_FUNC void vformat_to(buffer<char>& buf, string_view fmt, format_args args,
+                         locale_ref loc) {
+  auto out = appender(buf);
+  if (fmt.size() == 2 && equal2(fmt.data(), "{}"))
+    return args.get(0).visit(default_arg_formatter<char>{out});
+  parse_format_string(fmt,
+                      format_handler<>{parse_context<>(fmt), {out, args, loc}});
+}
+
+template <typename T> struct span {
+  T* data;
+  size_t size;
+};
+
+template <typename F> auto flockfile(F* f) -> decltype(_lock_file(f)) {
+  _lock_file(f);
+}
+template <typename F> auto funlockfile(F* f) -> decltype(_unlock_file(f)) {
+  _unlock_file(f);
+}
+
+#ifndef getc_unlocked
+template <typename F> auto getc_unlocked(F* f) -> decltype(_fgetc_nolock(f)) {
+  return _fgetc_nolock(f);
+}
+#endif
+
+template <typename F = FILE, typename Enable = void>
+struct has_flockfile : std::false_type {};
+
+template <typename F>
+struct has_flockfile<F, void_t<decltype(flockfile(&std::declval<F&>()))>>
+    : std::true_type {};
+
+// A FILE wrapper. F is FILE defined as a template parameter to make system API
+// detection work.
+template <typename F> class file_base {
+ public:
+  F* file_;
+
+ public:
+  file_base(F* file) : file_(file) {}
+  operator F*() const { return file_; }
+
+  // Reads a code unit from the stream.
+  auto get() -> int {
+    int result = getc_unlocked(file_);
+    if (result == EOF && ferror(file_) != 0)
+      FMT_THROW(system_error(errno, FMT_STRING("getc failed")));
+    return result;
+  }
+
+  // Puts the code unit back into the stream buffer.
+  void unget(char c) {
+    if (ungetc(c, file_) == EOF)
+      FMT_THROW(system_error(errno, FMT_STRING("ungetc failed")));
+  }
+
+  void flush() { fflush(this->file_); }
+};
+
+// A FILE wrapper for glibc.
+template <typename F> class glibc_file : public file_base<F> {
+ private:
+  enum {
+    line_buffered = 0x200,  // _IO_LINE_BUF
+    unbuffered = 2          // _IO_UNBUFFERED
+  };
+
+ public:
+  using file_base<F>::file_base;
+
+  auto is_buffered() const -> bool {
+    return (this->file_->_flags & unbuffered) == 0;
+  }
+
+  void init_buffer() {
+    if (this->file_->_IO_write_ptr < this->file_->_IO_write_end) return;
+    // Force buffer initialization by placing and removing a char in a buffer.
+    putc_unlocked(0, this->file_);
+    --this->file_->_IO_write_ptr;
+  }
+
+  // Returns the file's read buffer.
+  auto get_read_buffer() const -> span<const char> {
+    auto ptr = this->file_->_IO_read_ptr;
+    return {ptr, to_unsigned(this->file_->_IO_read_end - ptr)};
+  }
+
+  // Returns the file's write buffer.
+  auto get_write_buffer() const -> span<char> {
+    auto ptr = this->file_->_IO_write_ptr;
+    return {ptr, to_unsigned(this->file_->_IO_buf_end - ptr)};
+  }
+
+  void advance_write_buffer(size_t size) { this->file_->_IO_write_ptr += size; }
+
+  auto needs_flush() const -> bool {
+    if ((this->file_->_flags & line_buffered) == 0) return false;
+    char* end = this->file_->_IO_write_end;
+    auto size = max_of<ptrdiff_t>(this->file_->_IO_write_ptr - end, 0);
+    return memchr(end, '\n', static_cast<size_t>(size));
+  }
+
+  void flush() { fflush_unlocked(this->file_); }
+};
+
+// A FILE wrapper for Apple's libc.
+template <typename F> class apple_file : public file_base<F> {
+ private:
+  enum {
+    line_buffered = 1,  // __SNBF
+    unbuffered = 2      // __SLBF
+  };
+
+ public:
+  using file_base<F>::file_base;
+
+  auto is_buffered() const -> bool {
+    return (this->file_->_flags & unbuffered) == 0;
+  }
+
+  void init_buffer() {
+    if (this->file_->_p) return;
+    // Force buffer initialization by placing and removing a char in a buffer.
+    if (!FMT_CLANG_ANALYZER) putc_unlocked(0, this->file_);
+    --this->file_->_p;
+    ++this->file_->_w;
+  }
+
+  auto get_read_buffer() const -> span<const char> {
+    return {reinterpret_cast<char*>(this->file_->_p),
+            to_unsigned(this->file_->_r)};
+  }
+
+  auto get_write_buffer() const -> span<char> {
+    return {reinterpret_cast<char*>(this->file_->_p),
+            to_unsigned(this->file_->_bf._base + this->file_->_bf._size -
+                        this->file_->_p)};
+  }
+
+  void advance_write_buffer(size_t size) {
+    this->file_->_p += size;
+    this->file_->_w -= size;
+  }
+
+  auto needs_flush() const -> bool {
+    if ((this->file_->_flags & line_buffered) == 0) return false;
+    return memchr(this->file_->_p + this->file_->_w, '\n',
+                  to_unsigned(-this->file_->_w));
+  }
+};
+
+// A fallback FILE wrapper.
+template <typename F> class fallback_file : public file_base<F> {
+ private:
+  char next_;  // The next unconsumed character in the buffer.
+  bool has_next_ = false;
+
+ public:
+  using file_base<F>::file_base;
+
+  auto is_buffered() const -> bool { return false; }
+  auto needs_flush() const -> bool { return false; }
+  void init_buffer() {}
+
+  auto get_read_buffer() const -> span<const char> {
+    return {&next_, has_next_ ? 1u : 0u};
+  }
+
+  auto get_write_buffer() const -> span<char> { return {nullptr, 0}; }
+
+  void advance_write_buffer(size_t) {}
+
+  auto get() -> int {
+    has_next_ = false;
+    return file_base<F>::get();
+  }
+
+  void unget(char c) {
+    file_base<F>::unget(c);
+    next_ = c;
+    has_next_ = true;
+  }
+};
+
+#ifndef FMT_USE_FALLBACK_FILE
+#  define FMT_USE_FALLBACK_FILE 0
+#endif
+
+template <typename F,
+          FMT_ENABLE_IF(sizeof(F::_p) != 0 && !FMT_USE_FALLBACK_FILE)>
+auto get_file(F* f, int) -> apple_file<F> {
+  return f;
+}
+template <typename F,
+          FMT_ENABLE_IF(sizeof(F::_IO_read_ptr) != 0 && !FMT_USE_FALLBACK_FILE)>
+inline auto get_file(F* f, int) -> glibc_file<F> {
+  return f;
+}
+
+inline auto get_file(FILE* f, ...) -> fallback_file<FILE> { return f; }
+
+using file_ref = decltype(get_file(static_cast<FILE*>(nullptr), 0));
+
+template <typename F = FILE, typename Enable = void>
+class file_print_buffer : public buffer<char> {
+ public:
+  explicit file_print_buffer(F*) : buffer(nullptr, size_t()) {}
+};
+
+template <typename F>
+class file_print_buffer<F, enable_if_t<has_flockfile<F>::value>>
+    : public buffer<char> {
+ private:
+  file_ref file_;
+
+  static void grow(buffer<char>& base, size_t) {
+    auto& self = static_cast<file_print_buffer&>(base);
+    self.file_.advance_write_buffer(self.size());
+    if (self.file_.get_write_buffer().size == 0) self.file_.flush();
+    auto buf = self.file_.get_write_buffer();
+    FMT_ASSERT(buf.size > 0, "");
+    self.set(buf.data, buf.size);
+    self.clear();
+  }
+
+ public:
+  explicit file_print_buffer(F* f) : buffer(grow, size_t()), file_(f) {
+    flockfile(f);
+    file_.init_buffer();
+    auto buf = file_.get_write_buffer();
+    set(buf.data, buf.size);
+  }
+  ~file_print_buffer() {
+    file_.advance_write_buffer(size());
+    bool flush = file_.needs_flush();
+    F* f = file_;    // Make funlockfile depend on the template parameter F
+    funlockfile(f);  // for the system API detection to work.
+    if (flush) fflush(file_);
+  }
+};
+
+#if !defined(_WIN32) || defined(FMT_USE_WRITE_CONSOLE)
+FMT_FUNC auto write_console(int, string_view) -> bool { return false; }
+#else
+using dword = conditional_t<sizeof(long) == 4, unsigned long, unsigned>;
+extern "C" __declspec(dllimport) int __stdcall WriteConsoleW(  //
+    void*, const void*, dword, dword*, void*);
+
+FMT_FUNC bool write_console(int fd, string_view text) {
+  auto u16 = utf8_to_utf16(text);
+  return WriteConsoleW(reinterpret_cast<void*>(_get_osfhandle(fd)), u16.c_str(),
+                       static_cast<dword>(u16.size()), nullptr, nullptr) != 0;
+}
+#endif
+
+#ifdef _WIN32
+// Print assuming legacy (non-Unicode) encoding.
+FMT_FUNC void vprint_mojibake(std::FILE* f, string_view fmt, format_args args,
+                              bool newline) {
+  auto buffer = memory_buffer();
+  detail::vformat_to(buffer, fmt, args);
+  if (newline) buffer.push_back('\n');
+  fwrite_all(buffer.data(), buffer.size(), f);
+}
+#endif
+
+FMT_FUNC void print(std::FILE* f, string_view text) {
+#if defined(_WIN32) && !defined(FMT_USE_WRITE_CONSOLE)
+  int fd = _fileno(f);
+  if (_isatty(fd)) {
+    std::fflush(f);
+    if (write_console(fd, text)) return;
+  }
+#endif
+  fwrite_all(text.data(), text.size(), f);
+}
+}  // namespace detail
+
+FMT_FUNC void vprint_buffered(std::FILE* f, string_view fmt, format_args args) {
+  auto buffer = memory_buffer();
+  detail::vformat_to(buffer, fmt, args);
+  detail::print(f, {buffer.data(), buffer.size()});
+}
+
+FMT_FUNC void vprint(std::FILE* f, string_view fmt, format_args args) {
+  if (!detail::file_ref(f).is_buffered() || !detail::has_flockfile<>())
+    return vprint_buffered(f, fmt, args);
+  auto&& buffer = detail::file_print_buffer<>(f);
+  return detail::vformat_to(buffer, fmt, args);
+}
+
+FMT_FUNC void vprintln(std::FILE* f, string_view fmt, format_args args) {
+  auto buffer = memory_buffer();
+  detail::vformat_to(buffer, fmt, args);
+  buffer.push_back('\n');
+  detail::print(f, {buffer.data(), buffer.size()});
+}
+
+FMT_FUNC void vprint(string_view fmt, format_args args) {
+  vprint(stdout, fmt, args);
+}
+
+namespace detail {
+
+struct singleton {
+  unsigned char upper;
+  unsigned char lower_count;
+};
+
+inline auto is_printable(uint16_t x, const singleton* singletons,
+                         size_t singletons_size,
+                         const unsigned char* singleton_lowers,
+                         const unsigned char* normal, size_t normal_size)
+    -> bool {
+  auto upper = x >> 8;
+  auto lower_start = 0;
+  for (size_t i = 0; i < singletons_size; ++i) {
+    auto s = singletons[i];
+    auto lower_end = lower_start + s.lower_count;
+    if (upper < s.upper) break;
+    if (upper == s.upper) {
+      for (auto j = lower_start; j < lower_end; ++j) {
+        if (singleton_lowers[j] == (x & 0xff)) return false;
+      }
+    }
+    lower_start = lower_end;
+  }
+
+  auto xsigned = static_cast<int>(x);
+  auto current = true;
+  for (size_t i = 0; i < normal_size; ++i) {
+    auto v = static_cast<int>(normal[i]);
+    auto len = (v & 0x80) != 0 ? (v & 0x7f) << 8 | normal[++i] : v;
+    xsigned -= len;
+    if (xsigned < 0) break;
+    current = !current;
+  }
+  return current;
+}
+
+// This code is generated by support/printable.py.
+FMT_FUNC auto is_printable(uint32_t cp) -> bool {
+  static constexpr singleton singletons0[] = {
+      {0x00, 1},  {0x03, 5},  {0x05, 6},  {0x06, 3},  {0x07, 6},  {0x08, 8},
+      {0x09, 17}, {0x0a, 28}, {0x0b, 25}, {0x0c, 20}, {0x0d, 16}, {0x0e, 13},
+      {0x0f, 4},  {0x10, 3},  {0x12, 18}, {0x13, 9},  {0x16, 1},  {0x17, 5},
+      {0x18, 2},  {0x19, 3},  {0x1a, 7},  {0x1c, 2},  {0x1d, 1},  {0x1f, 22},
+      {0x20, 3},  {0x2b, 3},  {0x2c, 2},  {0x2d, 11}, {0x2e, 1},  {0x30, 3},
+      {0x31, 2},  {0x32, 1},  {0xa7, 2},  {0xa9, 2},  {0xaa, 4},  {0xab, 8},
+      {0xfa, 2},  {0xfb, 5},  {0xfd, 4},  {0xfe, 3},  {0xff, 9},
+  };
+  static constexpr unsigned char singletons0_lower[] = {
+      0xad, 0x78, 0x79, 0x8b, 0x8d, 0xa2, 0x30, 0x57, 0x58, 0x8b, 0x8c, 0x90,
+      0x1c, 0x1d, 0xdd, 0x0e, 0x0f, 0x4b, 0x4c, 0xfb, 0xfc, 0x2e, 0x2f, 0x3f,
+      0x5c, 0x5d, 0x5f, 0xb5, 0xe2, 0x84, 0x8d, 0x8e, 0x91, 0x92, 0xa9, 0xb1,
+      0xba, 0xbb, 0xc5, 0xc6, 0xc9, 0xca, 0xde, 0xe4, 0xe5, 0xff, 0x00, 0x04,
+      0x11, 0x12, 0x29, 0x31, 0x34, 0x37, 0x3a, 0x3b, 0x3d, 0x49, 0x4a, 0x5d,
+      0x84, 0x8e, 0x92, 0xa9, 0xb1, 0xb4, 0xba, 0xbb, 0xc6, 0xca, 0xce, 0xcf,
+      0xe4, 0xe5, 0x00, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a,
+      0x3b, 0x45, 0x46, 0x49, 0x4a, 0x5e, 0x64, 0x65, 0x84, 0x91, 0x9b, 0x9d,
+      0xc9, 0xce, 0xcf, 0x0d, 0x11, 0x29, 0x45, 0x49, 0x57, 0x64, 0x65, 0x8d,
+      0x91, 0xa9, 0xb4, 0xba, 0xbb, 0xc5, 0xc9, 0xdf, 0xe4, 0xe5, 0xf0, 0x0d,
+      0x11, 0x45, 0x49, 0x64, 0x65, 0x80, 0x84, 0xb2, 0xbc, 0xbe, 0xbf, 0xd5,
+      0xd7, 0xf0, 0xf1, 0x83, 0x85, 0x8b, 0xa4, 0xa6, 0xbe, 0xbf, 0xc5, 0xc7,
+      0xce, 0xcf, 0xda, 0xdb, 0x48, 0x98, 0xbd, 0xcd, 0xc6, 0xce, 0xcf, 0x49,
+      0x4e, 0x4f, 0x57, 0x59, 0x5e, 0x5f, 0x89, 0x8e, 0x8f, 0xb1, 0xb6, 0xb7,
+      0xbf, 0xc1, 0xc6, 0xc7, 0xd7, 0x11, 0x16, 0x17, 0x5b, 0x5c, 0xf6, 0xf7,
+      0xfe, 0xff, 0x80, 0x0d, 0x6d, 0x71, 0xde, 0xdf, 0x0e, 0x0f, 0x1f, 0x6e,
+      0x6f, 0x1c, 0x1d, 0x5f, 0x7d, 0x7e, 0xae, 0xaf, 0xbb, 0xbc, 0xfa, 0x16,
+      0x17, 0x1e, 0x1f, 0x46, 0x47, 0x4e, 0x4f, 0x58, 0x5a, 0x5c, 0x5e, 0x7e,
+      0x7f, 0xb5, 0xc5, 0xd4, 0xd5, 0xdc, 0xf0, 0xf1, 0xf5, 0x72, 0x73, 0x8f,
+      0x74, 0x75, 0x96, 0x2f, 0x5f, 0x26, 0x2e, 0x2f, 0xa7, 0xaf, 0xb7, 0xbf,
+      0xc7, 0xcf, 0xd7, 0xdf, 0x9a, 0x40, 0x97, 0x98, 0x30, 0x8f, 0x1f, 0xc0,
+      0xc1, 0xce, 0xff, 0x4e, 0x4f, 0x5a, 0x5b, 0x07, 0x08, 0x0f, 0x10, 0x27,
+      0x2f, 0xee, 0xef, 0x6e, 0x6f, 0x37, 0x3d, 0x3f, 0x42, 0x45, 0x90, 0x91,
+      0xfe, 0xff, 0x53, 0x67, 0x75, 0xc8, 0xc9, 0xd0, 0xd1, 0xd8, 0xd9, 0xe7,
+      0xfe, 0xff,
+  };
+  static constexpr singleton singletons1[] = {
+      {0x00, 6},  {0x01, 1}, {0x03, 1},  {0x04, 2}, {0x08, 8},  {0x09, 2},
+      {0x0a, 5},  {0x0b, 2}, {0x0e, 4},  {0x10, 1}, {0x11, 2},  {0x12, 5},
+      {0x13, 17}, {0x14, 1}, {0x15, 2},  {0x17, 2}, {0x19, 13}, {0x1c, 5},
+      {0x1d, 8},  {0x24, 1}, {0x6a, 3},  {0x6b, 2}, {0xbc, 2},  {0xd1, 2},
+      {0xd4, 12}, {0xd5, 9}, {0xd6, 2},  {0xd7, 2}, {0xda, 1},  {0xe0, 5},
+      {0xe1, 2},  {0xe8, 2}, {0xee, 32}, {0xf0, 4}, {0xf8, 2},  {0xf9, 2},
+      {0xfa, 2},  {0xfb, 1},
+  };
+  static constexpr unsigned char singletons1_lower[] = {
+      0x0c, 0x27, 0x3b, 0x3e, 0x4e, 0x4f, 0x8f, 0x9e, 0x9e, 0x9f, 0x06, 0x07,
+      0x09, 0x36, 0x3d, 0x3e, 0x56, 0xf3, 0xd0, 0xd1, 0x04, 0x14, 0x18, 0x36,
+      0x37, 0x56, 0x57, 0x7f, 0xaa, 0xae, 0xaf, 0xbd, 0x35, 0xe0, 0x12, 0x87,
+      0x89, 0x8e, 0x9e, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a,
+      0x45, 0x46, 0x49, 0x4a, 0x4e, 0x4f, 0x64, 0x65, 0x5c, 0xb6, 0xb7, 0x1b,
+      0x1c, 0x07, 0x08, 0x0a, 0x0b, 0x14, 0x17, 0x36, 0x39, 0x3a, 0xa8, 0xa9,
+      0xd8, 0xd9, 0x09, 0x37, 0x90, 0x91, 0xa8, 0x07, 0x0a, 0x3b, 0x3e, 0x66,
+      0x69, 0x8f, 0x92, 0x6f, 0x5f, 0xee, 0xef, 0x5a, 0x62, 0x9a, 0x9b, 0x27,
+      0x28, 0x55, 0x9d, 0xa0, 0xa1, 0xa3, 0xa4, 0xa7, 0xa8, 0xad, 0xba, 0xbc,
+      0xc4, 0x06, 0x0b, 0x0c, 0x15, 0x1d, 0x3a, 0x3f, 0x45, 0x51, 0xa6, 0xa7,
+      0xcc, 0xcd, 0xa0, 0x07, 0x19, 0x1a, 0x22, 0x25, 0x3e, 0x3f, 0xc5, 0xc6,
+      0x04, 0x20, 0x23, 0x25, 0x26, 0x28, 0x33, 0x38, 0x3a, 0x48, 0x4a, 0x4c,
+      0x50, 0x53, 0x55, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x63, 0x65, 0x66,
+      0x6b, 0x73, 0x78, 0x7d, 0x7f, 0x8a, 0xa4, 0xaa, 0xaf, 0xb0, 0xc0, 0xd0,
+      0xae, 0xaf, 0x79, 0xcc, 0x6e, 0x6f, 0x93,
+  };
+  static constexpr unsigned char normal0[] = {
+      0x00, 0x20, 0x5f, 0x22, 0x82, 0xdf, 0x04, 0x82, 0x44, 0x08, 0x1b, 0x04,
+      0x06, 0x11, 0x81, 0xac, 0x0e, 0x80, 0xab, 0x35, 0x28, 0x0b, 0x80, 0xe0,
+      0x03, 0x19, 0x08, 0x01, 0x04, 0x2f, 0x04, 0x34, 0x04, 0x07, 0x03, 0x01,
+      0x07, 0x06, 0x07, 0x11, 0x0a, 0x50, 0x0f, 0x12, 0x07, 0x55, 0x07, 0x03,
+      0x04, 0x1c, 0x0a, 0x09, 0x03, 0x08, 0x03, 0x07, 0x03, 0x02, 0x03, 0x03,
+      0x03, 0x0c, 0x04, 0x05, 0x03, 0x0b, 0x06, 0x01, 0x0e, 0x15, 0x05, 0x3a,
+      0x03, 0x11, 0x07, 0x06, 0x05, 0x10, 0x07, 0x57, 0x07, 0x02, 0x07, 0x15,
+      0x0d, 0x50, 0x04, 0x43, 0x03, 0x2d, 0x03, 0x01, 0x04, 0x11, 0x06, 0x0f,
+      0x0c, 0x3a, 0x04, 0x1d, 0x25, 0x5f, 0x20, 0x6d, 0x04, 0x6a, 0x25, 0x80,
+      0xc8, 0x05, 0x82, 0xb0, 0x03, 0x1a, 0x06, 0x82, 0xfd, 0x03, 0x59, 0x07,
+      0x15, 0x0b, 0x17, 0x09, 0x14, 0x0c, 0x14, 0x0c, 0x6a, 0x06, 0x0a, 0x06,
+      0x1a, 0x06, 0x59, 0x07, 0x2b, 0x05, 0x46, 0x0a, 0x2c, 0x04, 0x0c, 0x04,
+      0x01, 0x03, 0x31, 0x0b, 0x2c, 0x04, 0x1a, 0x06, 0x0b, 0x03, 0x80, 0xac,
+      0x06, 0x0a, 0x06, 0x21, 0x3f, 0x4c, 0x04, 0x2d, 0x03, 0x74, 0x08, 0x3c,
+      0x03, 0x0f, 0x03, 0x3c, 0x07, 0x38, 0x08, 0x2b, 0x05, 0x82, 0xff, 0x11,
+      0x18, 0x08, 0x2f, 0x11, 0x2d, 0x03, 0x20, 0x10, 0x21, 0x0f, 0x80, 0x8c,
+      0x04, 0x82, 0x97, 0x19, 0x0b, 0x15, 0x88, 0x94, 0x05, 0x2f, 0x05, 0x3b,
+      0x07, 0x02, 0x0e, 0x18, 0x09, 0x80, 0xb3, 0x2d, 0x74, 0x0c, 0x80, 0xd6,
+      0x1a, 0x0c, 0x05, 0x80, 0xff, 0x05, 0x80, 0xdf, 0x0c, 0xee, 0x0d, 0x03,
+      0x84, 0x8d, 0x03, 0x37, 0x09, 0x81, 0x5c, 0x14, 0x80, 0xb8, 0x08, 0x80,
+      0xcb, 0x2a, 0x38, 0x03, 0x0a, 0x06, 0x38, 0x08, 0x46, 0x08, 0x0c, 0x06,
+      0x74, 0x0b, 0x1e, 0x03, 0x5a, 0x04, 0x59, 0x09, 0x80, 0x83, 0x18, 0x1c,
+      0x0a, 0x16, 0x09, 0x4c, 0x04, 0x80, 0x8a, 0x06, 0xab, 0xa4, 0x0c, 0x17,
+      0x04, 0x31, 0xa1, 0x04, 0x81, 0xda, 0x26, 0x07, 0x0c, 0x05, 0x05, 0x80,
+      0xa5, 0x11, 0x81, 0x6d, 0x10, 0x78, 0x28, 0x2a, 0x06, 0x4c, 0x04, 0x80,
+      0x8d, 0x04, 0x80, 0xbe, 0x03, 0x1b, 0x03, 0x0f, 0x0d,
+  };
+  static constexpr unsigned char normal1[] = {
+      0x5e, 0x22, 0x7b, 0x05, 0x03, 0x04, 0x2d, 0x03, 0x66, 0x03, 0x01, 0x2f,
+      0x2e, 0x80, 0x82, 0x1d, 0x03, 0x31, 0x0f, 0x1c, 0x04, 0x24, 0x09, 0x1e,
+      0x05, 0x2b, 0x05, 0x44, 0x04, 0x0e, 0x2a, 0x80, 0xaa, 0x06, 0x24, 0x04,
+      0x24, 0x04, 0x28, 0x08, 0x34, 0x0b, 0x01, 0x80, 0x90, 0x81, 0x37, 0x09,
+      0x16, 0x0a, 0x08, 0x80, 0x98, 0x39, 0x03, 0x63, 0x08, 0x09, 0x30, 0x16,
+      0x05, 0x21, 0x03, 0x1b, 0x05, 0x01, 0x40, 0x38, 0x04, 0x4b, 0x05, 0x2f,
+      0x04, 0x0a, 0x07, 0x09, 0x07, 0x40, 0x20, 0x27, 0x04, 0x0c, 0x09, 0x36,
+      0x03, 0x3a, 0x05, 0x1a, 0x07, 0x04, 0x0c, 0x07, 0x50, 0x49, 0x37, 0x33,
+      0x0d, 0x33, 0x07, 0x2e, 0x08, 0x0a, 0x81, 0x26, 0x52, 0x4e, 0x28, 0x08,
+      0x2a, 0x56, 0x1c, 0x14, 0x17, 0x09, 0x4e, 0x04, 0x1e, 0x0f, 0x43, 0x0e,
+      0x19, 0x07, 0x0a, 0x06, 0x48, 0x08, 0x27, 0x09, 0x75, 0x0b, 0x3f, 0x41,
+      0x2a, 0x06, 0x3b, 0x05, 0x0a, 0x06, 0x51, 0x06, 0x01, 0x05, 0x10, 0x03,
+      0x05, 0x80, 0x8b, 0x62, 0x1e, 0x48, 0x08, 0x0a, 0x80, 0xa6, 0x5e, 0x22,
+      0x45, 0x0b, 0x0a, 0x06, 0x0d, 0x13, 0x39, 0x07, 0x0a, 0x36, 0x2c, 0x04,
+      0x10, 0x80, 0xc0, 0x3c, 0x64, 0x53, 0x0c, 0x48, 0x09, 0x0a, 0x46, 0x45,
+      0x1b, 0x48, 0x08, 0x53, 0x1d, 0x39, 0x81, 0x07, 0x46, 0x0a, 0x1d, 0x03,
+      0x47, 0x49, 0x37, 0x03, 0x0e, 0x08, 0x0a, 0x06, 0x39, 0x07, 0x0a, 0x81,
+      0x36, 0x19, 0x80, 0xb7, 0x01, 0x0f, 0x32, 0x0d, 0x83, 0x9b, 0x66, 0x75,
+      0x0b, 0x80, 0xc4, 0x8a, 0xbc, 0x84, 0x2f, 0x8f, 0xd1, 0x82, 0x47, 0xa1,
+      0xb9, 0x82, 0x39, 0x07, 0x2a, 0x04, 0x02, 0x60, 0x26, 0x0a, 0x46, 0x0a,
+      0x28, 0x05, 0x13, 0x82, 0xb0, 0x5b, 0x65, 0x4b, 0x04, 0x39, 0x07, 0x11,
+      0x40, 0x05, 0x0b, 0x02, 0x0e, 0x97, 0xf8, 0x08, 0x84, 0xd6, 0x2a, 0x09,
+      0xa2, 0xf7, 0x81, 0x1f, 0x31, 0x03, 0x11, 0x04, 0x08, 0x81, 0x8c, 0x89,
+      0x04, 0x6b, 0x05, 0x0d, 0x03, 0x09, 0x07, 0x10, 0x93, 0x60, 0x80, 0xf6,
+      0x0a, 0x73, 0x08, 0x6e, 0x17, 0x46, 0x80, 0x9a, 0x14, 0x0c, 0x57, 0x09,
+      0x19, 0x80, 0x87, 0x81, 0x47, 0x03, 0x85, 0x42, 0x0f, 0x15, 0x85, 0x50,
+      0x2b, 0x80, 0xd5, 0x2d, 0x03, 0x1a, 0x04, 0x02, 0x81, 0x70, 0x3a, 0x05,
+      0x01, 0x85, 0x00, 0x80, 0xd7, 0x29, 0x4c, 0x04, 0x0a, 0x04, 0x02, 0x83,
+      0x11, 0x44, 0x4c, 0x3d, 0x80, 0xc2, 0x3c, 0x06, 0x01, 0x04, 0x55, 0x05,
+      0x1b, 0x34, 0x02, 0x81, 0x0e, 0x2c, 0x04, 0x64, 0x0c, 0x56, 0x0a, 0x80,
+      0xae, 0x38, 0x1d, 0x0d, 0x2c, 0x04, 0x09, 0x07, 0x02, 0x0e, 0x06, 0x80,
+      0x9a, 0x83, 0xd8, 0x08, 0x0d, 0x03, 0x0d, 0x03, 0x74, 0x0c, 0x59, 0x07,
+      0x0c, 0x14, 0x0c, 0x04, 0x38, 0x08, 0x0a, 0x06, 0x28, 0x08, 0x22, 0x4e,
+      0x81, 0x54, 0x0c, 0x15, 0x03, 0x03, 0x05, 0x07, 0x09, 0x19, 0x07, 0x07,
+      0x09, 0x03, 0x0d, 0x07, 0x29, 0x80, 0xcb, 0x25, 0x0a, 0x84, 0x06,
+  };
+  auto lower = static_cast<uint16_t>(cp);
+  if (cp < 0x10000) {
+    return is_printable(lower, singletons0,
+                        sizeof(singletons0) / sizeof(*singletons0),
+                        singletons0_lower, normal0, sizeof(normal0));
+  }
+  if (cp < 0x20000) {
+    return is_printable(lower, singletons1,
+                        sizeof(singletons1) / sizeof(*singletons1),
+                        singletons1_lower, normal1, sizeof(normal1));
+  }
+  if (0x2a6de <= cp && cp < 0x2a700) return false;
+  if (0x2b735 <= cp && cp < 0x2b740) return false;
+  if (0x2b81e <= cp && cp < 0x2b820) return false;
+  if (0x2cea2 <= cp && cp < 0x2ceb0) return false;
+  if (0x2ebe1 <= cp && cp < 0x2f800) return false;
+  if (0x2fa1e <= cp && cp < 0x30000) return false;
+  if (0x3134b <= cp && cp < 0xe0100) return false;
+  if (0xe01f0 <= cp && cp < 0x110000) return false;
+  return cp < 0x110000;
+}
+
+}  // namespace detail
+
+FMT_END_NAMESPACE
+
+#endif  // FMT_FORMAT_INL_H_

+ 4383 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/format.h

@@ -0,0 +1,4383 @@
+/*
+  Formatting library for C++
+
+  Copyright (c) 2012 - present, Victor Zverovich
+
+  Permission is hereby granted, free of charge, to any person obtaining
+  a copy of this software and associated documentation files (the
+  "Software"), to deal in the Software without restriction, including
+  without limitation the rights to use, copy, modify, merge, publish,
+  distribute, sublicense, and/or sell copies of the Software, and to
+  permit persons to whom the Software is furnished to do so, subject to
+  the following conditions:
+
+  The above copyright notice and this permission notice shall be
+  included in all copies or substantial portions of the Software.
+
+  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+  --- Optional exception to the license ---
+
+  As an exception, if, as a result of your compiling your source code, portions
+  of this Software are embedded into a machine-executable object form of such
+  source code, you may redistribute such embedded portions in such object form
+  without including the above copyright and permission notices.
+ */
+
+#ifndef FMT_FORMAT_H_
+#define FMT_FORMAT_H_
+
+#ifndef _LIBCPP_REMOVE_TRANSITIVE_INCLUDES
+#  define _LIBCPP_REMOVE_TRANSITIVE_INCLUDES
+#  define FMT_REMOVE_TRANSITIVE_INCLUDES
+#endif
+
+#include "base.h"
+
+#ifndef FMT_MODULE
+#  include <cmath>    // std::signbit
+#  include <cstddef>  // std::byte
+#  include <cstdint>  // uint32_t
+#  include <cstdlib>  // std::malloc, std::free
+#  include <cstring>  // std::memcpy
+#  include <limits>   // std::numeric_limits
+#  include <new>      // std::bad_alloc
+#  if defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI)
+// Workaround for pre gcc 5 libstdc++.
+#    include <memory>  // std::allocator_traits
+#  endif
+#  include <stdexcept>     // std::runtime_error
+#  include <string>        // std::string
+#  include <system_error>  // std::system_error
+
+// Check FMT_CPLUSPLUS to avoid a warning in MSVC.
+#  if FMT_HAS_INCLUDE(<bit>) && FMT_CPLUSPLUS > 201703L
+#    include <bit>  // std::bit_cast
+#  endif
+
+// libc++ supports string_view in pre-c++17.
+#  if FMT_HAS_INCLUDE(<string_view>) && \
+      (FMT_CPLUSPLUS >= 201703L || defined(_LIBCPP_VERSION))
+#    include <string_view>
+#    define FMT_USE_STRING_VIEW
+#  endif
+
+#  if FMT_MSC_VERSION
+#    include <intrin.h>  // _BitScanReverse[64], _umul128
+#  endif
+#endif  // FMT_MODULE
+
+#if defined(FMT_USE_NONTYPE_TEMPLATE_ARGS)
+// Use the provided definition.
+#elif defined(__NVCOMPILER)
+#  define FMT_USE_NONTYPE_TEMPLATE_ARGS 0
+#elif FMT_GCC_VERSION >= 903 && FMT_CPLUSPLUS >= 201709L
+#  define FMT_USE_NONTYPE_TEMPLATE_ARGS 1
+#elif defined(__cpp_nontype_template_args) && \
+    __cpp_nontype_template_args >= 201911L
+#  define FMT_USE_NONTYPE_TEMPLATE_ARGS 1
+#elif FMT_CLANG_VERSION >= 1200 && FMT_CPLUSPLUS >= 202002L
+#  define FMT_USE_NONTYPE_TEMPLATE_ARGS 1
+#else
+#  define FMT_USE_NONTYPE_TEMPLATE_ARGS 0
+#endif
+
+#if defined __cpp_inline_variables && __cpp_inline_variables >= 201606L
+#  define FMT_INLINE_VARIABLE inline
+#else
+#  define FMT_INLINE_VARIABLE
+#endif
+
+// Check if RTTI is disabled.
+#ifdef FMT_USE_RTTI
+// Use the provided definition.
+#elif defined(__GXX_RTTI) || FMT_HAS_FEATURE(cxx_rtti) || defined(_CPPRTTI) || \
+    defined(__INTEL_RTTI__) || defined(__RTTI)
+// __RTTI is for EDG compilers. _CPPRTTI is for MSVC.
+#  define FMT_USE_RTTI 1
+#else
+#  define FMT_USE_RTTI 0
+#endif
+
+// Visibility when compiled as a shared library/object.
+#if defined(FMT_LIB_EXPORT) || defined(FMT_SHARED)
+#  define FMT_SO_VISIBILITY(value) FMT_VISIBILITY(value)
+#else
+#  define FMT_SO_VISIBILITY(value)
+#endif
+
+#if FMT_GCC_VERSION || FMT_CLANG_VERSION
+#  define FMT_NOINLINE __attribute__((noinline))
+#else
+#  define FMT_NOINLINE
+#endif
+
+#ifdef FMT_DEPRECATED
+// Use the provided definition.
+#elif FMT_HAS_CPP14_ATTRIBUTE(deprecated)
+#  define FMT_DEPRECATED [[deprecated]]
+#else
+#  define FMT_DEPRECATED /* deprecated */
+#endif
+
+// Detect constexpr std::string.
+#if !FMT_USE_CONSTEVAL
+#  define FMT_USE_CONSTEXPR_STRING 0
+#elif defined(__cpp_lib_constexpr_string) && \
+    __cpp_lib_constexpr_string >= 201907L
+#  if FMT_CLANG_VERSION && FMT_GLIBCXX_RELEASE
+// clang + libstdc++ are able to work only starting with gcc13.3
+// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113294
+#    if FMT_GLIBCXX_RELEASE < 13
+#      define FMT_USE_CONSTEXPR_STRING 0
+#    elif FMT_GLIBCXX_RELEASE == 13 && __GLIBCXX__ < 20240521
+#      define FMT_USE_CONSTEXPR_STRING 0
+#    else
+#      define FMT_USE_CONSTEXPR_STRING 1
+#    endif
+#  else
+#    define FMT_USE_CONSTEXPR_STRING 1
+#  endif
+#else
+#  define FMT_USE_CONSTEXPR_STRING 0
+#endif
+#if FMT_USE_CONSTEXPR_STRING
+#  define FMT_CONSTEXPR_STRING constexpr
+#else
+#  define FMT_CONSTEXPR_STRING
+#endif
+
+// GCC 4.9 doesn't support qualified names in specializations.
+namespace std {
+template <typename T> struct iterator_traits<fmt::basic_appender<T>> {
+  using iterator_category = output_iterator_tag;
+  using value_type = T;
+  using difference_type =
+      decltype(static_cast<int*>(nullptr) - static_cast<int*>(nullptr));
+  using pointer = void;
+  using reference = void;
+};
+}  // namespace std
+
+#ifdef FMT_THROW
+// Use the provided definition.
+#elif FMT_USE_EXCEPTIONS
+#  define FMT_THROW(x) throw x
+#else
+#  define FMT_THROW(x) ::fmt::assert_fail(__FILE__, __LINE__, (x).what())
+#endif
+
+#ifdef __clang_analyzer__
+#  define FMT_CLANG_ANALYZER 1
+#else
+#  define FMT_CLANG_ANALYZER 0
+#endif
+
+// Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of
+// integer formatter template instantiations to just one by only using the
+// largest integer type. This results in a reduction in binary size but will
+// cause a decrease in integer formatting performance.
+#if !defined(FMT_REDUCE_INT_INSTANTIATIONS)
+#  define FMT_REDUCE_INT_INSTANTIATIONS 0
+#endif
+
+FMT_BEGIN_NAMESPACE
+
+template <typename Char, typename Traits, typename Allocator>
+struct is_contiguous<std::basic_string<Char, Traits, Allocator>>
+    : std::true_type {};
+
+namespace detail {
+
+// __builtin_clz is broken in clang with Microsoft codegen:
+// https://github.com/fmtlib/fmt/issues/519.
+#if !FMT_MSC_VERSION
+#  if FMT_HAS_BUILTIN(__builtin_clz) || FMT_GCC_VERSION || FMT_ICC_VERSION
+#    define FMT_BUILTIN_CLZ(n) __builtin_clz(n)
+#  endif
+#  if FMT_HAS_BUILTIN(__builtin_clzll) || FMT_GCC_VERSION || FMT_ICC_VERSION
+#    define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n)
+#  endif
+#endif
+
+// Some compilers masquerade as both MSVC and GCC but otherwise support
+// __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the
+// MSVC intrinsics if the clz and clzll builtins are not available.
+#if FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL)
+// Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning.
+#  ifndef __clang__
+#    pragma intrinsic(_BitScanReverse)
+#    ifdef _WIN64
+#      pragma intrinsic(_BitScanReverse64)
+#    endif
+#  endif
+
+inline auto clz(uint32_t x) -> int {
+  FMT_ASSERT(x != 0, "");
+  FMT_MSC_WARNING(suppress : 6102)  // Suppress a bogus static analysis warning.
+  unsigned long r = 0;
+  _BitScanReverse(&r, x);
+  return 31 ^ static_cast<int>(r);
+}
+#  define FMT_BUILTIN_CLZ(n) detail::clz(n)
+
+inline auto clzll(uint64_t x) -> int {
+  FMT_ASSERT(x != 0, "");
+  FMT_MSC_WARNING(suppress : 6102)  // Suppress a bogus static analysis warning.
+  unsigned long r = 0;
+#  ifdef _WIN64
+  _BitScanReverse64(&r, x);
+#  else
+  // Scan the high 32 bits.
+  if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32)))
+    return 63 ^ static_cast<int>(r + 32);
+  // Scan the low 32 bits.
+  _BitScanReverse(&r, static_cast<uint32_t>(x));
+#  endif
+  return 63 ^ static_cast<int>(r);
+}
+#  define FMT_BUILTIN_CLZLL(n) detail::clzll(n)
+#endif  // FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL)
+
+FMT_CONSTEXPR inline void abort_fuzzing_if(bool condition) {
+  ignore_unused(condition);
+#ifdef FMT_FUZZ
+  if (condition) throw std::runtime_error("fuzzing limit reached");
+#endif
+}
+
+#if defined(FMT_USE_STRING_VIEW)
+template <typename Char> using std_string_view = std::basic_string_view<Char>;
+#else
+template <typename Char> struct std_string_view {
+  operator basic_string_view<Char>() const;
+};
+#endif
+
+template <typename Char, Char... C> struct string_literal {
+  static constexpr Char value[sizeof...(C)] = {C...};
+  constexpr operator basic_string_view<Char>() const {
+    return {value, sizeof...(C)};
+  }
+};
+#if FMT_CPLUSPLUS < 201703L
+template <typename Char, Char... C>
+constexpr Char string_literal<Char, C...>::value[sizeof...(C)];
+#endif
+
+// Implementation of std::bit_cast for pre-C++20.
+template <typename To, typename From, FMT_ENABLE_IF(sizeof(To) == sizeof(From))>
+FMT_CONSTEXPR20 auto bit_cast(const From& from) -> To {
+#ifdef __cpp_lib_bit_cast
+  if (is_constant_evaluated()) return std::bit_cast<To>(from);
+#endif
+  auto to = To();
+  // The cast suppresses a bogus -Wclass-memaccess on GCC.
+  std::memcpy(static_cast<void*>(&to), &from, sizeof(to));
+  return to;
+}
+
+inline auto is_big_endian() -> bool {
+#ifdef _WIN32
+  return false;
+#elif defined(__BIG_ENDIAN__)
+  return true;
+#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__)
+  return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__;
+#else
+  struct bytes {
+    char data[sizeof(int)];
+  };
+  return bit_cast<bytes>(1).data[0] == 0;
+#endif
+}
+
+class uint128_fallback {
+ private:
+  uint64_t lo_, hi_;
+
+ public:
+  constexpr uint128_fallback(uint64_t hi, uint64_t lo) : lo_(lo), hi_(hi) {}
+  constexpr uint128_fallback(uint64_t value = 0) : lo_(value), hi_(0) {}
+
+  constexpr auto high() const noexcept -> uint64_t { return hi_; }
+  constexpr auto low() const noexcept -> uint64_t { return lo_; }
+
+  template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+  constexpr explicit operator T() const {
+    return static_cast<T>(lo_);
+  }
+
+  friend constexpr auto operator==(const uint128_fallback& lhs,
+                                   const uint128_fallback& rhs) -> bool {
+    return lhs.hi_ == rhs.hi_ && lhs.lo_ == rhs.lo_;
+  }
+  friend constexpr auto operator!=(const uint128_fallback& lhs,
+                                   const uint128_fallback& rhs) -> bool {
+    return !(lhs == rhs);
+  }
+  friend constexpr auto operator>(const uint128_fallback& lhs,
+                                  const uint128_fallback& rhs) -> bool {
+    return lhs.hi_ != rhs.hi_ ? lhs.hi_ > rhs.hi_ : lhs.lo_ > rhs.lo_;
+  }
+  friend constexpr auto operator|(const uint128_fallback& lhs,
+                                  const uint128_fallback& rhs)
+      -> uint128_fallback {
+    return {lhs.hi_ | rhs.hi_, lhs.lo_ | rhs.lo_};
+  }
+  friend constexpr auto operator&(const uint128_fallback& lhs,
+                                  const uint128_fallback& rhs)
+      -> uint128_fallback {
+    return {lhs.hi_ & rhs.hi_, lhs.lo_ & rhs.lo_};
+  }
+  friend constexpr auto operator~(const uint128_fallback& n)
+      -> uint128_fallback {
+    return {~n.hi_, ~n.lo_};
+  }
+  friend FMT_CONSTEXPR auto operator+(const uint128_fallback& lhs,
+                                      const uint128_fallback& rhs)
+      -> uint128_fallback {
+    auto result = uint128_fallback(lhs);
+    result += rhs;
+    return result;
+  }
+  friend FMT_CONSTEXPR auto operator*(const uint128_fallback& lhs, uint32_t rhs)
+      -> uint128_fallback {
+    FMT_ASSERT(lhs.hi_ == 0, "");
+    uint64_t hi = (lhs.lo_ >> 32) * rhs;
+    uint64_t lo = (lhs.lo_ & ~uint32_t()) * rhs;
+    uint64_t new_lo = (hi << 32) + lo;
+    return {(hi >> 32) + (new_lo < lo ? 1 : 0), new_lo};
+  }
+  friend constexpr auto operator-(const uint128_fallback& lhs, uint64_t rhs)
+      -> uint128_fallback {
+    return {lhs.hi_ - (lhs.lo_ < rhs ? 1 : 0), lhs.lo_ - rhs};
+  }
+  FMT_CONSTEXPR auto operator>>(int shift) const -> uint128_fallback {
+    if (shift == 64) return {0, hi_};
+    if (shift > 64) return uint128_fallback(0, hi_) >> (shift - 64);
+    return {hi_ >> shift, (hi_ << (64 - shift)) | (lo_ >> shift)};
+  }
+  FMT_CONSTEXPR auto operator<<(int shift) const -> uint128_fallback {
+    if (shift == 64) return {lo_, 0};
+    if (shift > 64) return uint128_fallback(lo_, 0) << (shift - 64);
+    return {hi_ << shift | (lo_ >> (64 - shift)), (lo_ << shift)};
+  }
+  FMT_CONSTEXPR auto operator>>=(int shift) -> uint128_fallback& {
+    return *this = *this >> shift;
+  }
+  FMT_CONSTEXPR void operator+=(uint128_fallback n) {
+    uint64_t new_lo = lo_ + n.lo_;
+    uint64_t new_hi = hi_ + n.hi_ + (new_lo < lo_ ? 1 : 0);
+    FMT_ASSERT(new_hi >= hi_, "");
+    lo_ = new_lo;
+    hi_ = new_hi;
+  }
+  FMT_CONSTEXPR void operator&=(uint128_fallback n) {
+    lo_ &= n.lo_;
+    hi_ &= n.hi_;
+  }
+
+  FMT_CONSTEXPR20 auto operator+=(uint64_t n) noexcept -> uint128_fallback& {
+    if (is_constant_evaluated()) {
+      lo_ += n;
+      hi_ += (lo_ < n ? 1 : 0);
+      return *this;
+    }
+#if FMT_HAS_BUILTIN(__builtin_addcll) && !defined(__ibmxl__)
+    unsigned long long carry;
+    lo_ = __builtin_addcll(lo_, n, 0, &carry);
+    hi_ += carry;
+#elif FMT_HAS_BUILTIN(__builtin_ia32_addcarryx_u64) && !defined(__ibmxl__)
+    unsigned long long result;
+    auto carry = __builtin_ia32_addcarryx_u64(0, lo_, n, &result);
+    lo_ = result;
+    hi_ += carry;
+#elif defined(_MSC_VER) && defined(_M_X64)
+    auto carry = _addcarry_u64(0, lo_, n, &lo_);
+    _addcarry_u64(carry, hi_, 0, &hi_);
+#else
+    lo_ += n;
+    hi_ += (lo_ < n ? 1 : 0);
+#endif
+    return *this;
+  }
+};
+
+using uint128_t = conditional_t<FMT_USE_INT128, uint128_opt, uint128_fallback>;
+
+#ifdef UINTPTR_MAX
+using uintptr_t = ::uintptr_t;
+#else
+using uintptr_t = uint128_t;
+#endif
+
+// Returns the largest possible value for type T. Same as
+// std::numeric_limits<T>::max() but shorter and not affected by the max macro.
+template <typename T> constexpr auto max_value() -> T {
+  return (std::numeric_limits<T>::max)();
+}
+template <typename T> constexpr auto num_bits() -> int {
+  return std::numeric_limits<T>::digits;
+}
+// std::numeric_limits<T>::digits may return 0 for 128-bit ints.
+template <> constexpr auto num_bits<int128_opt>() -> int { return 128; }
+template <> constexpr auto num_bits<uint128_opt>() -> int { return 128; }
+template <> constexpr auto num_bits<uint128_fallback>() -> int { return 128; }
+
+// A heterogeneous bit_cast used for converting 96-bit long double to uint128_t
+// and 128-bit pointers to uint128_fallback.
+template <typename To, typename From, FMT_ENABLE_IF(sizeof(To) > sizeof(From))>
+inline auto bit_cast(const From& from) -> To {
+  constexpr auto size = static_cast<int>(sizeof(From) / sizeof(unsigned short));
+  struct data_t {
+    unsigned short value[static_cast<unsigned>(size)];
+  } data = bit_cast<data_t>(from);
+  auto result = To();
+  if (const_check(is_big_endian())) {
+    for (int i = 0; i < size; ++i)
+      result = (result << num_bits<unsigned short>()) | data.value[i];
+  } else {
+    for (int i = size - 1; i >= 0; --i)
+      result = (result << num_bits<unsigned short>()) | data.value[i];
+  }
+  return result;
+}
+
+template <typename UInt>
+FMT_CONSTEXPR20 inline auto countl_zero_fallback(UInt n) -> int {
+  int lz = 0;
+  constexpr UInt msb_mask = static_cast<UInt>(1) << (num_bits<UInt>() - 1);
+  for (; (n & msb_mask) == 0; n <<= 1) lz++;
+  return lz;
+}
+
+FMT_CONSTEXPR20 inline auto countl_zero(uint32_t n) -> int {
+#ifdef FMT_BUILTIN_CLZ
+  if (!is_constant_evaluated()) return FMT_BUILTIN_CLZ(n);
+#endif
+  return countl_zero_fallback(n);
+}
+
+FMT_CONSTEXPR20 inline auto countl_zero(uint64_t n) -> int {
+#ifdef FMT_BUILTIN_CLZLL
+  if (!is_constant_evaluated()) return FMT_BUILTIN_CLZLL(n);
+#endif
+  return countl_zero_fallback(n);
+}
+
+FMT_INLINE void assume(bool condition) {
+  (void)condition;
+#if FMT_HAS_BUILTIN(__builtin_assume) && !FMT_ICC_VERSION
+  __builtin_assume(condition);
+#elif FMT_GCC_VERSION
+  if (!condition) __builtin_unreachable();
+#endif
+}
+
+// Attempts to reserve space for n extra characters in the output range.
+// Returns a pointer to the reserved range or a reference to it.
+template <typename OutputIt,
+          FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value&&
+                            is_contiguous<typename OutputIt::container>::value)>
+#if FMT_CLANG_VERSION >= 307 && !FMT_ICC_VERSION
+__attribute__((no_sanitize("undefined")))
+#endif
+FMT_CONSTEXPR20 inline auto
+reserve(OutputIt it, size_t n) -> typename OutputIt::value_type* {
+  auto& c = get_container(it);
+  size_t size = c.size();
+  c.resize(size + n);
+  return &c[size];
+}
+
+template <typename T>
+FMT_CONSTEXPR20 inline auto reserve(basic_appender<T> it, size_t n)
+    -> basic_appender<T> {
+  buffer<T>& buf = get_container(it);
+  buf.try_reserve(buf.size() + n);
+  return it;
+}
+
+template <typename Iterator>
+constexpr auto reserve(Iterator& it, size_t) -> Iterator& {
+  return it;
+}
+
+template <typename OutputIt>
+using reserve_iterator =
+    remove_reference_t<decltype(reserve(std::declval<OutputIt&>(), 0))>;
+
+template <typename T, typename OutputIt>
+constexpr auto to_pointer(OutputIt, size_t) -> T* {
+  return nullptr;
+}
+template <typename T> FMT_CONSTEXPR auto to_pointer(T*& ptr, size_t n) -> T* {
+  T* begin = ptr;
+  ptr += n;
+  return begin;
+}
+template <typename T>
+FMT_CONSTEXPR20 auto to_pointer(basic_appender<T> it, size_t n) -> T* {
+  buffer<T>& buf = get_container(it);
+  buf.try_reserve(buf.size() + n);
+  auto size = buf.size();
+  if (buf.capacity() < size + n) return nullptr;
+  buf.try_resize(size + n);
+  return buf.data() + size;
+}
+
+template <typename OutputIt,
+          FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value&&
+                            is_contiguous<typename OutputIt::container>::value)>
+inline auto base_iterator(OutputIt it,
+                          typename OutputIt::container_type::value_type*)
+    -> OutputIt {
+  return it;
+}
+
+template <typename Iterator>
+constexpr auto base_iterator(Iterator, Iterator it) -> Iterator {
+  return it;
+}
+
+// <algorithm> is spectacularly slow to compile in C++20 so use a simple fill_n
+// instead (#1998).
+template <typename OutputIt, typename Size, typename T>
+FMT_CONSTEXPR auto fill_n(OutputIt out, Size count, const T& value)
+    -> OutputIt {
+  for (Size i = 0; i < count; ++i) *out++ = value;
+  return out;
+}
+template <typename T, typename Size>
+FMT_CONSTEXPR20 auto fill_n(T* out, Size count, char value) -> T* {
+  if (is_constant_evaluated()) return fill_n<T*, Size, T>(out, count, value);
+  static_assert(sizeof(T) == 1,
+                "sizeof(T) must be 1 to use char for initialization");
+  std::memset(out, value, to_unsigned(count));
+  return out + count;
+}
+
+template <typename OutChar, typename InputIt, typename OutputIt>
+FMT_CONSTEXPR FMT_NOINLINE auto copy_noinline(InputIt begin, InputIt end,
+                                              OutputIt out) -> OutputIt {
+  return copy<OutChar>(begin, end, out);
+}
+
+// A public domain branchless UTF-8 decoder by Christopher Wellons:
+// https://github.com/skeeto/branchless-utf8
+/* Decode the next character, c, from s, reporting errors in e.
+ *
+ * Since this is a branchless decoder, four bytes will be read from the
+ * buffer regardless of the actual length of the next character. This
+ * means the buffer _must_ have at least three bytes of zero padding
+ * following the end of the data stream.
+ *
+ * Errors are reported in e, which will be non-zero if the parsed
+ * character was somehow invalid: invalid byte sequence, non-canonical
+ * encoding, or a surrogate half.
+ *
+ * The function returns a pointer to the next character. When an error
+ * occurs, this pointer will be a guess that depends on the particular
+ * error, but it will always advance at least one byte.
+ */
+FMT_CONSTEXPR inline auto utf8_decode(const char* s, uint32_t* c, int* e)
+    -> const char* {
+  constexpr int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07};
+  constexpr uint32_t mins[] = {4194304, 0, 128, 2048, 65536};
+  constexpr int shiftc[] = {0, 18, 12, 6, 0};
+  constexpr int shifte[] = {0, 6, 4, 2, 0};
+
+  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"
+      [static_cast<unsigned char>(*s) >> 3];
+  // Compute the pointer to the next character early so that the next
+  // iteration can start working on the next character. Neither Clang
+  // nor GCC figure out this reordering on their own.
+  const char* next = s + len + !len;
+
+  using uchar = unsigned char;
+
+  // Assume a four-byte character and load four bytes. Unused bits are
+  // shifted out.
+  *c = uint32_t(uchar(s[0]) & masks[len]) << 18;
+  *c |= uint32_t(uchar(s[1]) & 0x3f) << 12;
+  *c |= uint32_t(uchar(s[2]) & 0x3f) << 6;
+  *c |= uint32_t(uchar(s[3]) & 0x3f) << 0;
+  *c >>= shiftc[len];
+
+  // Accumulate the various error conditions.
+  *e = (*c < mins[len]) << 6;       // non-canonical encoding
+  *e |= ((*c >> 11) == 0x1b) << 7;  // surrogate half?
+  *e |= (*c > 0x10FFFF) << 8;       // out of range?
+  *e |= (uchar(s[1]) & 0xc0) >> 2;
+  *e |= (uchar(s[2]) & 0xc0) >> 4;
+  *e |= uchar(s[3]) >> 6;
+  *e ^= 0x2a;  // top two bits of each tail byte correct?
+  *e >>= shifte[len];
+
+  return next;
+}
+
+constexpr FMT_INLINE_VARIABLE uint32_t invalid_code_point = ~uint32_t();
+
+// Invokes f(cp, sv) for every code point cp in s with sv being the string view
+// corresponding to the code point. cp is invalid_code_point on error.
+template <typename F>
+FMT_CONSTEXPR void for_each_codepoint(string_view s, F f) {
+  auto decode = [f](const char* buf_ptr, const char* ptr) {
+    auto cp = uint32_t();
+    auto error = 0;
+    auto end = utf8_decode(buf_ptr, &cp, &error);
+    bool result = f(error ? invalid_code_point : cp,
+                    string_view(ptr, error ? 1 : to_unsigned(end - buf_ptr)));
+    return result ? (error ? buf_ptr + 1 : end) : nullptr;
+  };
+
+  auto p = s.data();
+  const size_t block_size = 4;  // utf8_decode always reads blocks of 4 chars.
+  if (s.size() >= block_size) {
+    for (auto end = p + s.size() - block_size + 1; p < end;) {
+      p = decode(p, p);
+      if (!p) return;
+    }
+  }
+  auto num_chars_left = to_unsigned(s.data() + s.size() - p);
+  if (num_chars_left == 0) return;
+
+  // Suppress bogus -Wstringop-overflow.
+  if (FMT_GCC_VERSION) num_chars_left &= 3;
+  char buf[2 * block_size - 1] = {};
+  copy<char>(p, p + num_chars_left, buf);
+  const char* buf_ptr = buf;
+  do {
+    auto end = decode(buf_ptr, p);
+    if (!end) return;
+    p += end - buf_ptr;
+    buf_ptr = end;
+  } while (buf_ptr < buf + num_chars_left);
+}
+
+FMT_CONSTEXPR inline auto display_width_of(uint32_t cp) noexcept -> size_t {
+  return to_unsigned(
+      1 + (cp >= 0x1100 &&
+           (cp <= 0x115f ||  // Hangul Jamo init. consonants
+            cp == 0x2329 ||  // LEFT-POINTING ANGLE BRACKET
+            cp == 0x232a ||  // RIGHT-POINTING ANGLE BRACKET
+            // CJK ... Yi except IDEOGRAPHIC HALF FILL SPACE:
+            (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) ||
+            (cp >= 0xac00 && cp <= 0xd7a3) ||    // Hangul Syllables
+            (cp >= 0xf900 && cp <= 0xfaff) ||    // CJK Compatibility Ideographs
+            (cp >= 0xfe10 && cp <= 0xfe19) ||    // Vertical Forms
+            (cp >= 0xfe30 && cp <= 0xfe6f) ||    // CJK Compatibility Forms
+            (cp >= 0xff00 && cp <= 0xff60) ||    // Fullwidth Forms
+            (cp >= 0xffe0 && cp <= 0xffe6) ||    // Fullwidth Forms
+            (cp >= 0x20000 && cp <= 0x2fffd) ||  // CJK
+            (cp >= 0x30000 && cp <= 0x3fffd) ||
+            // Miscellaneous Symbols and Pictographs + Emoticons:
+            (cp >= 0x1f300 && cp <= 0x1f64f) ||
+            // Supplemental Symbols and Pictographs:
+            (cp >= 0x1f900 && cp <= 0x1f9ff))));
+}
+
+template <typename T> struct is_integral : std::is_integral<T> {};
+template <> struct is_integral<int128_opt> : std::true_type {};
+template <> struct is_integral<uint128_t> : std::true_type {};
+
+template <typename T>
+using is_signed =
+    std::integral_constant<bool, std::numeric_limits<T>::is_signed ||
+                                     std::is_same<T, int128_opt>::value>;
+
+template <typename T>
+using is_integer =
+    bool_constant<is_integral<T>::value && !std::is_same<T, bool>::value &&
+                  !std::is_same<T, char>::value &&
+                  !std::is_same<T, wchar_t>::value>;
+
+#if defined(FMT_USE_FLOAT128)
+// Use the provided definition.
+#elif FMT_CLANG_VERSION >= 309 && FMT_HAS_INCLUDE(<quadmath.h>)
+#  define FMT_USE_FLOAT128 1
+#elif FMT_GCC_VERSION && defined(_GLIBCXX_USE_FLOAT128) && \
+    !defined(__STRICT_ANSI__)
+#  define FMT_USE_FLOAT128 1
+#else
+#  define FMT_USE_FLOAT128 0
+#endif
+#if FMT_USE_FLOAT128
+using float128 = __float128;
+#else
+struct float128 {};
+#endif
+
+template <typename T> using is_float128 = std::is_same<T, float128>;
+
+template <typename T> struct is_floating_point : std::is_floating_point<T> {};
+template <> struct is_floating_point<float128> : std::true_type {};
+
+template <typename T, bool = is_floating_point<T>::value>
+struct is_fast_float : bool_constant<std::numeric_limits<T>::is_iec559 &&
+                                     sizeof(T) <= sizeof(double)> {};
+template <typename T> struct is_fast_float<T, false> : std::false_type {};
+
+template <typename T>
+using fast_float_t = conditional_t<sizeof(T) == sizeof(double), double, float>;
+
+template <typename T>
+using is_double_double = bool_constant<std::numeric_limits<T>::digits == 106>;
+
+#ifndef FMT_USE_FULL_CACHE_DRAGONBOX
+#  define FMT_USE_FULL_CACHE_DRAGONBOX 0
+#endif
+
+// An allocator that uses malloc/free to allow removing dependency on the C++
+// standard libary runtime. std::decay is used for back_inserter to be found by
+// ADL when applied to memory_buffer.
+template <typename T> struct allocator : private std::decay<void> {
+  using value_type = T;
+
+  auto allocate(size_t n) -> T* {
+    FMT_ASSERT(n <= max_value<size_t>() / sizeof(T), "");
+    T* p = static_cast<T*>(std::malloc(n * sizeof(T)));
+    if (!p) FMT_THROW(std::bad_alloc());
+    return p;
+  }
+
+  void deallocate(T* p, size_t) { std::free(p); }
+
+  constexpr friend auto operator==(allocator, allocator) noexcept -> bool {
+    return true;  // All instances of this allocator are equivalent.
+  }
+  constexpr friend auto operator!=(allocator, allocator) noexcept -> bool {
+    return false;
+  }
+};
+
+}  // namespace detail
+
+FMT_BEGIN_EXPORT
+
+// The number of characters to store in the basic_memory_buffer object itself
+// to avoid dynamic memory allocation.
+enum { inline_buffer_size = 500 };
+
+/**
+ * A dynamically growing memory buffer for trivially copyable/constructible
+ * types with the first `SIZE` elements stored in the object itself. Most
+ * commonly used via the `memory_buffer` alias for `char`.
+ *
+ * **Example**:
+ *
+ *     auto out = fmt::memory_buffer();
+ *     fmt::format_to(std::back_inserter(out), "The answer is {}.", 42);
+ *
+ * This will append "The answer is 42." to `out`. The buffer content can be
+ * converted to `std::string` with `to_string(out)`.
+ */
+template <typename T, size_t SIZE = inline_buffer_size,
+          typename Allocator = detail::allocator<T>>
+class basic_memory_buffer : public detail::buffer<T> {
+ private:
+  T store_[SIZE];
+
+  // Don't inherit from Allocator to avoid generating type_info for it.
+  FMT_NO_UNIQUE_ADDRESS Allocator alloc_;
+
+  // Deallocate memory allocated by the buffer.
+  FMT_CONSTEXPR20 void deallocate() {
+    T* data = this->data();
+    if (data != store_) alloc_.deallocate(data, this->capacity());
+  }
+
+  static FMT_CONSTEXPR20 void grow(detail::buffer<T>& buf, size_t size) {
+    detail::abort_fuzzing_if(size > 5000);
+    auto& self = static_cast<basic_memory_buffer&>(buf);
+    const size_t max_size =
+        std::allocator_traits<Allocator>::max_size(self.alloc_);
+    size_t old_capacity = buf.capacity();
+    size_t new_capacity = old_capacity + old_capacity / 2;
+    if (size > new_capacity)
+      new_capacity = size;
+    else if (new_capacity > max_size)
+      new_capacity = max_of(size, max_size);
+    T* old_data = buf.data();
+    T* new_data = self.alloc_.allocate(new_capacity);
+    // Suppress a bogus -Wstringop-overflow in gcc 13.1 (#3481).
+    detail::assume(buf.size() <= new_capacity);
+    // The following code doesn't throw, so the raw pointer above doesn't leak.
+    memcpy(new_data, old_data, buf.size() * sizeof(T));
+    self.set(new_data, new_capacity);
+    // deallocate must not throw according to the standard, but even if it does,
+    // the buffer already uses the new storage and will deallocate it in
+    // destructor.
+    if (old_data != self.store_) self.alloc_.deallocate(old_data, old_capacity);
+  }
+
+ public:
+  using value_type = T;
+  using const_reference = const T&;
+
+  FMT_CONSTEXPR explicit basic_memory_buffer(
+      const Allocator& alloc = Allocator())
+      : detail::buffer<T>(grow), alloc_(alloc) {
+    this->set(store_, SIZE);
+    if (detail::is_constant_evaluated()) detail::fill_n(store_, SIZE, T());
+  }
+  FMT_CONSTEXPR20 ~basic_memory_buffer() { deallocate(); }
+
+ private:
+  template <typename Alloc = Allocator,
+            FMT_ENABLE_IF(std::allocator_traits<Alloc>::
+                              propagate_on_container_move_assignment::value)>
+  FMT_CONSTEXPR20 auto move_alloc(basic_memory_buffer& other) -> bool {
+    alloc_ = std::move(other.alloc_);
+    return true;
+  }
+  // If the allocator does not propagate then copy the data from other.
+  template <typename Alloc = Allocator,
+            FMT_ENABLE_IF(!std::allocator_traits<Alloc>::
+                              propagate_on_container_move_assignment::value)>
+  FMT_CONSTEXPR20 auto move_alloc(basic_memory_buffer& other) -> bool {
+    T* data = other.data();
+    if (alloc_ == other.alloc_ || data == other.store_) return true;
+    size_t size = other.size();
+    // Perform copy operation, allocators are different.
+    this->resize(size);
+    detail::copy<T>(data, data + size, this->data());
+    return false;
+  }
+
+  // Move data from other to this buffer.
+  FMT_CONSTEXPR20 void move(basic_memory_buffer& other) {
+    T* data = other.data();
+    size_t size = other.size(), capacity = other.capacity();
+    if (!move_alloc(other)) return;
+    if (data == other.store_) {
+      this->set(store_, capacity);
+      detail::copy<T>(other.store_, other.store_ + size, store_);
+    } else {
+      this->set(data, capacity);
+      // Set pointer to the inline array so that delete is not called
+      // when deallocating.
+      other.set(other.store_, 0);
+      other.clear();
+    }
+    this->resize(size);
+  }
+
+ public:
+  /// Constructs a `basic_memory_buffer` object moving the content of the other
+  /// object to it.
+  FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other) noexcept
+      : detail::buffer<T>(grow) {
+    move(other);
+  }
+
+  /// Moves the content of the other `basic_memory_buffer` object to this one.
+  auto operator=(basic_memory_buffer&& other) noexcept -> basic_memory_buffer& {
+    FMT_ASSERT(this != &other, "");
+    deallocate();
+    move(other);
+    return *this;
+  }
+
+  // Returns a copy of the allocator associated with this buffer.
+  auto get_allocator() const -> Allocator { return alloc_; }
+
+  /// Resizes the buffer to contain `count` elements. If T is a POD type new
+  /// elements may not be initialized.
+  FMT_CONSTEXPR void resize(size_t count) { this->try_resize(count); }
+
+  /// Increases the buffer capacity to `new_capacity`.
+  void reserve(size_t new_capacity) { this->try_reserve(new_capacity); }
+
+  using detail::buffer<T>::append;
+  template <typename ContiguousRange>
+  FMT_CONSTEXPR20 void append(const ContiguousRange& range) {
+    append(range.data(), range.data() + range.size());
+  }
+};
+
+using memory_buffer = basic_memory_buffer<char>;
+
+template <size_t SIZE>
+FMT_NODISCARD auto to_string(const basic_memory_buffer<char, SIZE>& buf)
+    -> std::string {
+  auto size = buf.size();
+  detail::assume(size < std::string().max_size());
+  return {buf.data(), size};
+}
+
+// A writer to a buffered stream. It doesn't own the underlying stream.
+class writer {
+ private:
+  detail::buffer<char>* buf_;
+
+  // We cannot create a file buffer in advance because any write to a FILE may
+  // invalidate it.
+  FILE* file_;
+
+ public:
+  inline writer(FILE* f) : buf_(nullptr), file_(f) {}
+  inline writer(detail::buffer<char>& buf) : buf_(&buf) {}
+
+  /// Formats `args` according to specifications in `fmt` and writes the
+  /// output to the file.
+  template <typename... T> void print(format_string<T...> fmt, T&&... args) {
+    if (buf_)
+      fmt::format_to(appender(*buf_), fmt, std::forward<T>(args)...);
+    else
+      fmt::print(file_, fmt, std::forward<T>(args)...);
+  }
+};
+
+class string_buffer {
+ private:
+  std::string str_;
+  detail::container_buffer<std::string> buf_;
+
+ public:
+  inline string_buffer() : buf_(str_) {}
+
+  inline operator writer() { return buf_; }
+  inline auto str() -> std::string& { return str_; }
+};
+
+template <typename T, size_t SIZE, typename Allocator>
+struct is_contiguous<basic_memory_buffer<T, SIZE, Allocator>> : std::true_type {
+};
+
+// Suppress a misleading warning in older versions of clang.
+FMT_PRAGMA_CLANG(diagnostic ignored "-Wweak-vtables")
+
+/// An error reported from a formatting function.
+class FMT_SO_VISIBILITY("default") format_error : public std::runtime_error {
+ public:
+  using std::runtime_error::runtime_error;
+};
+
+class loc_value;
+
+FMT_END_EXPORT
+namespace detail {
+FMT_API auto write_console(int fd, string_view text) -> bool;
+FMT_API void print(FILE*, string_view);
+}  // namespace detail
+
+namespace detail {
+template <typename Char, size_t N> struct fixed_string {
+  FMT_CONSTEXPR20 fixed_string(const Char (&s)[N]) {
+    detail::copy<Char, const Char*, Char*>(static_cast<const Char*>(s), s + N,
+                                           data);
+  }
+  Char data[N] = {};
+};
+
+// Converts a compile-time string to basic_string_view.
+FMT_EXPORT template <typename Char, size_t N>
+constexpr auto compile_string_to_view(const Char (&s)[N])
+    -> basic_string_view<Char> {
+  // Remove trailing NUL character if needed. Won't be present if this is used
+  // with a raw character array (i.e. not defined as a string).
+  return {s, N - (std::char_traits<Char>::to_int_type(s[N - 1]) == 0 ? 1 : 0)};
+}
+FMT_EXPORT template <typename Char>
+constexpr auto compile_string_to_view(basic_string_view<Char> s)
+    -> basic_string_view<Char> {
+  return s;
+}
+
+// Returns true if value is negative, false otherwise.
+// Same as `value < 0` but doesn't produce warnings if T is an unsigned type.
+template <typename T, FMT_ENABLE_IF(is_signed<T>::value)>
+constexpr auto is_negative(T value) -> bool {
+  return value < 0;
+}
+template <typename T, FMT_ENABLE_IF(!is_signed<T>::value)>
+constexpr auto is_negative(T) -> bool {
+  return false;
+}
+
+// Smallest of uint32_t, uint64_t, uint128_t that is large enough to
+// represent all values of an integral type T.
+template <typename T>
+using uint32_or_64_or_128_t =
+    conditional_t<num_bits<T>() <= 32 && !FMT_REDUCE_INT_INSTANTIATIONS,
+                  uint32_t,
+                  conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>>;
+template <typename T>
+using uint64_or_128_t = conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>;
+
+#define FMT_POWERS_OF_10(factor)                                  \
+  factor * 10, (factor) * 100, (factor) * 1000, (factor) * 10000, \
+      (factor) * 100000, (factor) * 1000000, (factor) * 10000000, \
+      (factor) * 100000000, (factor) * 1000000000
+
+// Converts value in the range [0, 100) to a string.
+// GCC generates slightly better code when value is pointer-size.
+inline auto digits2(size_t value) -> const char* {
+  // Align data since unaligned access may be slower when crossing a
+  // hardware-specific boundary.
+  alignas(2) static const char data[] =
+      "0001020304050607080910111213141516171819"
+      "2021222324252627282930313233343536373839"
+      "4041424344454647484950515253545556575859"
+      "6061626364656667686970717273747576777879"
+      "8081828384858687888990919293949596979899";
+  return &data[value * 2];
+}
+
+template <typename Char> constexpr auto getsign(sign s) -> Char {
+  return static_cast<char>(((' ' << 24) | ('+' << 16) | ('-' << 8)) >>
+                           (static_cast<int>(s) * 8));
+}
+
+template <typename T> FMT_CONSTEXPR auto count_digits_fallback(T n) -> int {
+  int count = 1;
+  for (;;) {
+    // Integer division is slow so do it for a group of four digits instead
+    // of for every digit. The idea comes from the talk by Alexandrescu
+    // "Three Optimization Tips for C++". See speed-test for a comparison.
+    if (n < 10) return count;
+    if (n < 100) return count + 1;
+    if (n < 1000) return count + 2;
+    if (n < 10000) return count + 3;
+    n /= 10000u;
+    count += 4;
+  }
+}
+#if FMT_USE_INT128
+FMT_CONSTEXPR inline auto count_digits(uint128_opt n) -> int {
+  return count_digits_fallback(n);
+}
+#endif
+
+#ifdef FMT_BUILTIN_CLZLL
+// It is a separate function rather than a part of count_digits to workaround
+// the lack of static constexpr in constexpr functions.
+inline auto do_count_digits(uint64_t n) -> int {
+  // This has comparable performance to the version by Kendall Willets
+  // (https://github.com/fmtlib/format-benchmark/blob/master/digits10)
+  // but uses smaller tables.
+  // Maps bsr(n) to ceil(log10(pow(2, bsr(n) + 1) - 1)).
+  static constexpr uint8_t bsr2log10[] = {
+      1,  1,  1,  2,  2,  2,  3,  3,  3,  4,  4,  4,  4,  5,  5,  5,
+      6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  9,  9,  9,  10, 10, 10,
+      10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 15,
+      15, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20};
+  auto t = bsr2log10[FMT_BUILTIN_CLZLL(n | 1) ^ 63];
+  static constexpr uint64_t zero_or_powers_of_10[] = {
+      0, 0, FMT_POWERS_OF_10(1U), FMT_POWERS_OF_10(1000000000ULL),
+      10000000000000000000ULL};
+  return t - (n < zero_or_powers_of_10[t]);
+}
+#endif
+
+// Returns the number of decimal digits in n. Leading zeros are not counted
+// except for n == 0 in which case count_digits returns 1.
+FMT_CONSTEXPR20 inline auto count_digits(uint64_t n) -> int {
+#ifdef FMT_BUILTIN_CLZLL
+  if (!is_constant_evaluated() && !FMT_OPTIMIZE_SIZE) return do_count_digits(n);
+#endif
+  return count_digits_fallback(n);
+}
+
+// Counts the number of digits in n. BITS = log2(radix).
+template <int BITS, typename UInt>
+FMT_CONSTEXPR auto count_digits(UInt n) -> int {
+#ifdef FMT_BUILTIN_CLZ
+  if (!is_constant_evaluated() && num_bits<UInt>() == 32)
+    return (FMT_BUILTIN_CLZ(static_cast<uint32_t>(n) | 1) ^ 31) / BITS + 1;
+#endif
+  // Lambda avoids unreachable code warnings from NVHPC.
+  return [](UInt m) {
+    int num_digits = 0;
+    do {
+      ++num_digits;
+    } while ((m >>= BITS) != 0);
+    return num_digits;
+  }(n);
+}
+
+#ifdef FMT_BUILTIN_CLZ
+// It is a separate function rather than a part of count_digits to workaround
+// the lack of static constexpr in constexpr functions.
+FMT_INLINE auto do_count_digits(uint32_t n) -> int {
+// An optimization by Kendall Willets from https://bit.ly/3uOIQrB.
+// This increments the upper 32 bits (log10(T) - 1) when >= T is added.
+#  define FMT_INC(T) (((sizeof(#T) - 1ull) << 32) - T)
+  static constexpr uint64_t table[] = {
+      FMT_INC(0),          FMT_INC(0),          FMT_INC(0),           // 8
+      FMT_INC(10),         FMT_INC(10),         FMT_INC(10),          // 64
+      FMT_INC(100),        FMT_INC(100),        FMT_INC(100),         // 512
+      FMT_INC(1000),       FMT_INC(1000),       FMT_INC(1000),        // 4096
+      FMT_INC(10000),      FMT_INC(10000),      FMT_INC(10000),       // 32k
+      FMT_INC(100000),     FMT_INC(100000),     FMT_INC(100000),      // 256k
+      FMT_INC(1000000),    FMT_INC(1000000),    FMT_INC(1000000),     // 2048k
+      FMT_INC(10000000),   FMT_INC(10000000),   FMT_INC(10000000),    // 16M
+      FMT_INC(100000000),  FMT_INC(100000000),  FMT_INC(100000000),   // 128M
+      FMT_INC(1000000000), FMT_INC(1000000000), FMT_INC(1000000000),  // 1024M
+      FMT_INC(1000000000), FMT_INC(1000000000)                        // 4B
+  };
+  auto inc = table[FMT_BUILTIN_CLZ(n | 1) ^ 31];
+  return static_cast<int>((n + inc) >> 32);
+}
+#endif
+
+// Optional version of count_digits for better performance on 32-bit platforms.
+FMT_CONSTEXPR20 inline auto count_digits(uint32_t n) -> int {
+#ifdef FMT_BUILTIN_CLZ
+  if (!is_constant_evaluated() && !FMT_OPTIMIZE_SIZE) return do_count_digits(n);
+#endif
+  return count_digits_fallback(n);
+}
+
+template <typename Int> constexpr auto digits10() noexcept -> int {
+  return std::numeric_limits<Int>::digits10;
+}
+template <> constexpr auto digits10<int128_opt>() noexcept -> int { return 38; }
+template <> constexpr auto digits10<uint128_t>() noexcept -> int { return 38; }
+
+template <typename Char> struct thousands_sep_result {
+  std::string grouping;
+  Char thousands_sep;
+};
+
+template <typename Char>
+FMT_API auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result<Char>;
+template <typename Char>
+inline auto thousands_sep(locale_ref loc) -> thousands_sep_result<Char> {
+  auto result = thousands_sep_impl<char>(loc);
+  return {result.grouping, Char(result.thousands_sep)};
+}
+template <>
+inline auto thousands_sep(locale_ref loc) -> thousands_sep_result<wchar_t> {
+  return thousands_sep_impl<wchar_t>(loc);
+}
+
+template <typename Char>
+FMT_API auto decimal_point_impl(locale_ref loc) -> Char;
+template <typename Char> inline auto decimal_point(locale_ref loc) -> Char {
+  return Char(decimal_point_impl<char>(loc));
+}
+template <> inline auto decimal_point(locale_ref loc) -> wchar_t {
+  return decimal_point_impl<wchar_t>(loc);
+}
+
+#ifndef FMT_HEADER_ONLY
+FMT_BEGIN_EXPORT
+extern template FMT_API auto thousands_sep_impl<char>(locale_ref)
+    -> thousands_sep_result<char>;
+extern template FMT_API auto thousands_sep_impl<wchar_t>(locale_ref)
+    -> thousands_sep_result<wchar_t>;
+extern template FMT_API auto decimal_point_impl(locale_ref) -> char;
+extern template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t;
+FMT_END_EXPORT
+#endif  // FMT_HEADER_ONLY
+
+// Compares two characters for equality.
+template <typename Char> auto equal2(const Char* lhs, const char* rhs) -> bool {
+  return lhs[0] == Char(rhs[0]) && lhs[1] == Char(rhs[1]);
+}
+inline auto equal2(const char* lhs, const char* rhs) -> bool {
+  return memcmp(lhs, rhs, 2) == 0;
+}
+
+// Writes a two-digit value to out.
+template <typename Char>
+FMT_CONSTEXPR20 FMT_INLINE void write2digits(Char* out, size_t value) {
+  if (!is_constant_evaluated() && std::is_same<Char, char>::value &&
+      !FMT_OPTIMIZE_SIZE) {
+    memcpy(out, digits2(value), 2);
+    return;
+  }
+  *out++ = static_cast<Char>('0' + value / 10);
+  *out = static_cast<Char>('0' + value % 10);
+}
+
+// Formats a decimal unsigned integer value writing to out pointing to a buffer
+// of specified size. The caller must ensure that the buffer is large enough.
+template <typename Char, typename UInt>
+FMT_CONSTEXPR20 auto do_format_decimal(Char* out, UInt value, int size)
+    -> Char* {
+  FMT_ASSERT(size >= count_digits(value), "invalid digit count");
+  unsigned n = to_unsigned(size);
+  while (value >= 100) {
+    // Integer division is slow so do it for a group of two digits instead
+    // of for every digit. The idea comes from the talk by Alexandrescu
+    // "Three Optimization Tips for C++". See speed-test for a comparison.
+    n -= 2;
+    write2digits(out + n, static_cast<unsigned>(value % 100));
+    value /= 100;
+  }
+  if (value >= 10) {
+    n -= 2;
+    write2digits(out + n, static_cast<unsigned>(value));
+  } else {
+    out[--n] = static_cast<Char>('0' + value);
+  }
+  return out + n;
+}
+
+template <typename Char, typename UInt>
+FMT_CONSTEXPR FMT_INLINE auto format_decimal(Char* out, UInt value,
+                                             int num_digits) -> Char* {
+  do_format_decimal(out, value, num_digits);
+  return out + num_digits;
+}
+
+template <typename Char, typename UInt, typename OutputIt,
+          FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<OutputIt>>::value)>
+FMT_CONSTEXPR auto format_decimal(OutputIt out, UInt value, int num_digits)
+    -> OutputIt {
+  if (auto ptr = to_pointer<Char>(out, to_unsigned(num_digits))) {
+    do_format_decimal(ptr, value, num_digits);
+    return out;
+  }
+  // Buffer is large enough to hold all digits (digits10 + 1).
+  char buffer[digits10<UInt>() + 1];
+  if (is_constant_evaluated()) fill_n(buffer, sizeof(buffer), '\0');
+  do_format_decimal(buffer, value, num_digits);
+  return copy_noinline<Char>(buffer, buffer + num_digits, out);
+}
+
+template <typename Char, typename UInt>
+FMT_CONSTEXPR auto do_format_base2e(int base_bits, Char* out, UInt value,
+                                    int size, bool upper = false) -> Char* {
+  out += size;
+  do {
+    const char* digits = upper ? "0123456789ABCDEF" : "0123456789abcdef";
+    unsigned digit = static_cast<unsigned>(value & ((1u << base_bits) - 1));
+    *--out = static_cast<Char>(base_bits < 4 ? static_cast<char>('0' + digit)
+                                             : digits[digit]);
+  } while ((value >>= base_bits) != 0);
+  return out;
+}
+
+// Formats an unsigned integer in the power of two base (binary, octal, hex).
+template <typename Char, typename UInt>
+FMT_CONSTEXPR auto format_base2e(int base_bits, Char* out, UInt value,
+                                 int num_digits, bool upper = false) -> Char* {
+  do_format_base2e(base_bits, out, value, num_digits, upper);
+  return out + num_digits;
+}
+
+template <typename Char, typename OutputIt, typename UInt,
+          FMT_ENABLE_IF(is_back_insert_iterator<OutputIt>::value)>
+FMT_CONSTEXPR inline auto format_base2e(int base_bits, OutputIt out, UInt value,
+                                        int num_digits, bool upper = false)
+    -> OutputIt {
+  if (auto ptr = to_pointer<Char>(out, to_unsigned(num_digits))) {
+    format_base2e(base_bits, ptr, value, num_digits, upper);
+    return out;
+  }
+  // Make buffer large enough for any base.
+  char buffer[num_bits<UInt>()];
+  if (is_constant_evaluated()) fill_n(buffer, sizeof(buffer), '\0');
+  format_base2e(base_bits, buffer, value, num_digits, upper);
+  return detail::copy_noinline<Char>(buffer, buffer + num_digits, out);
+}
+
+// A converter from UTF-8 to UTF-16.
+class utf8_to_utf16 {
+ private:
+  basic_memory_buffer<wchar_t> buffer_;
+
+ public:
+  FMT_API explicit utf8_to_utf16(string_view s);
+  inline operator basic_string_view<wchar_t>() const {
+    return {&buffer_[0], size()};
+  }
+  inline auto size() const -> size_t { return buffer_.size() - 1; }
+  inline auto c_str() const -> const wchar_t* { return &buffer_[0]; }
+  inline auto str() const -> std::wstring { return {&buffer_[0], size()}; }
+};
+
+enum class to_utf8_error_policy { abort, replace };
+
+// A converter from UTF-16/UTF-32 (host endian) to UTF-8.
+template <typename WChar, typename Buffer = memory_buffer> class to_utf8 {
+ private:
+  Buffer buffer_;
+
+ public:
+  to_utf8() {}
+  explicit to_utf8(basic_string_view<WChar> s,
+                   to_utf8_error_policy policy = to_utf8_error_policy::abort) {
+    static_assert(sizeof(WChar) == 2 || sizeof(WChar) == 4,
+                  "expected utf16 or utf32");
+    if (!convert(s, policy)) {
+      FMT_THROW(std::runtime_error(sizeof(WChar) == 2 ? "invalid utf16"
+                                                      : "invalid utf32"));
+    }
+  }
+  operator string_view() const { return string_view(&buffer_[0], size()); }
+  auto size() const -> size_t { return buffer_.size() - 1; }
+  auto c_str() const -> const char* { return &buffer_[0]; }
+  auto str() const -> std::string { return std::string(&buffer_[0], size()); }
+
+  // Performs conversion returning a bool instead of throwing exception on
+  // conversion error. This method may still throw in case of memory allocation
+  // error.
+  auto convert(basic_string_view<WChar> s,
+               to_utf8_error_policy policy = to_utf8_error_policy::abort)
+      -> bool {
+    if (!convert(buffer_, s, policy)) return false;
+    buffer_.push_back(0);
+    return true;
+  }
+  static auto convert(Buffer& buf, basic_string_view<WChar> s,
+                      to_utf8_error_policy policy = to_utf8_error_policy::abort)
+      -> bool {
+    for (auto p = s.begin(); p != s.end(); ++p) {
+      uint32_t c = static_cast<uint32_t>(*p);
+      if (sizeof(WChar) == 2 && c >= 0xd800 && c <= 0xdfff) {
+        // Handle a surrogate pair.
+        ++p;
+        if (p == s.end() || (c & 0xfc00) != 0xd800 || (*p & 0xfc00) != 0xdc00) {
+          if (policy == to_utf8_error_policy::abort) return false;
+          buf.append(string_view("\xEF\xBF\xBD"));
+          --p;
+          continue;
+        }
+        c = (c << 10) + static_cast<uint32_t>(*p) - 0x35fdc00;
+      }
+      if (c < 0x80) {
+        buf.push_back(static_cast<char>(c));
+      } else if (c < 0x800) {
+        buf.push_back(static_cast<char>(0xc0 | (c >> 6)));
+        buf.push_back(static_cast<char>(0x80 | (c & 0x3f)));
+      } else if ((c >= 0x800 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xffff)) {
+        buf.push_back(static_cast<char>(0xe0 | (c >> 12)));
+        buf.push_back(static_cast<char>(0x80 | ((c & 0xfff) >> 6)));
+        buf.push_back(static_cast<char>(0x80 | (c & 0x3f)));
+      } else if (c >= 0x10000 && c <= 0x10ffff) {
+        buf.push_back(static_cast<char>(0xf0 | (c >> 18)));
+        buf.push_back(static_cast<char>(0x80 | ((c & 0x3ffff) >> 12)));
+        buf.push_back(static_cast<char>(0x80 | ((c & 0xfff) >> 6)));
+        buf.push_back(static_cast<char>(0x80 | (c & 0x3f)));
+      } else {
+        return false;
+      }
+    }
+    return true;
+  }
+};
+
+// Computes 128-bit result of multiplication of two 64-bit unsigned integers.
+FMT_INLINE auto umul128(uint64_t x, uint64_t y) noexcept -> uint128_fallback {
+#if FMT_USE_INT128
+  auto p = static_cast<uint128_opt>(x) * static_cast<uint128_opt>(y);
+  return {static_cast<uint64_t>(p >> 64), static_cast<uint64_t>(p)};
+#elif defined(_MSC_VER) && defined(_M_X64)
+  auto hi = uint64_t();
+  auto lo = _umul128(x, y, &hi);
+  return {hi, lo};
+#else
+  const uint64_t mask = static_cast<uint64_t>(max_value<uint32_t>());
+
+  uint64_t a = x >> 32;
+  uint64_t b = x & mask;
+  uint64_t c = y >> 32;
+  uint64_t d = y & mask;
+
+  uint64_t ac = a * c;
+  uint64_t bc = b * c;
+  uint64_t ad = a * d;
+  uint64_t bd = b * d;
+
+  uint64_t intermediate = (bd >> 32) + (ad & mask) + (bc & mask);
+
+  return {ac + (intermediate >> 32) + (ad >> 32) + (bc >> 32),
+          (intermediate << 32) + (bd & mask)};
+#endif
+}
+
+namespace dragonbox {
+// Computes floor(log10(pow(2, e))) for e in [-2620, 2620] using the method from
+// https://fmt.dev/papers/Dragonbox.pdf#page=28, section 6.1.
+inline auto floor_log10_pow2(int e) noexcept -> int {
+  FMT_ASSERT(e <= 2620 && e >= -2620, "too large exponent");
+  static_assert((-1 >> 1) == -1, "right shift is not arithmetic");
+  return (e * 315653) >> 20;
+}
+
+inline auto floor_log2_pow10(int e) noexcept -> int {
+  FMT_ASSERT(e <= 1233 && e >= -1233, "too large exponent");
+  return (e * 1741647) >> 19;
+}
+
+// Computes upper 64 bits of multiplication of two 64-bit unsigned integers.
+inline auto umul128_upper64(uint64_t x, uint64_t y) noexcept -> uint64_t {
+#if FMT_USE_INT128
+  auto p = static_cast<uint128_opt>(x) * static_cast<uint128_opt>(y);
+  return static_cast<uint64_t>(p >> 64);
+#elif defined(_MSC_VER) && defined(_M_X64)
+  return __umulh(x, y);
+#else
+  return umul128(x, y).high();
+#endif
+}
+
+// Computes upper 128 bits of multiplication of a 64-bit unsigned integer and a
+// 128-bit unsigned integer.
+inline auto umul192_upper128(uint64_t x, uint128_fallback y) noexcept
+    -> uint128_fallback {
+  uint128_fallback r = umul128(x, y.high());
+  r += umul128_upper64(x, y.low());
+  return r;
+}
+
+FMT_API auto get_cached_power(int k) noexcept -> uint128_fallback;
+
+// Type-specific information that Dragonbox uses.
+template <typename T, typename Enable = void> struct float_info;
+
+template <> struct float_info<float> {
+  using carrier_uint = uint32_t;
+  static const int exponent_bits = 8;
+  static const int kappa = 1;
+  static const int big_divisor = 100;
+  static const int small_divisor = 10;
+  static const int min_k = -31;
+  static const int max_k = 46;
+  static const int shorter_interval_tie_lower_threshold = -35;
+  static const int shorter_interval_tie_upper_threshold = -35;
+};
+
+template <> struct float_info<double> {
+  using carrier_uint = uint64_t;
+  static const int exponent_bits = 11;
+  static const int kappa = 2;
+  static const int big_divisor = 1000;
+  static const int small_divisor = 100;
+  static const int min_k = -292;
+  static const int max_k = 341;
+  static const int shorter_interval_tie_lower_threshold = -77;
+  static const int shorter_interval_tie_upper_threshold = -77;
+};
+
+// An 80- or 128-bit floating point number.
+template <typename T>
+struct float_info<T, enable_if_t<std::numeric_limits<T>::digits == 64 ||
+                                 std::numeric_limits<T>::digits == 113 ||
+                                 is_float128<T>::value>> {
+  using carrier_uint = detail::uint128_t;
+  static const int exponent_bits = 15;
+};
+
+// A double-double floating point number.
+template <typename T>
+struct float_info<T, enable_if_t<is_double_double<T>::value>> {
+  using carrier_uint = detail::uint128_t;
+};
+
+template <typename T> struct decimal_fp {
+  using significand_type = typename float_info<T>::carrier_uint;
+  significand_type significand;
+  int exponent;
+};
+
+template <typename T> FMT_API auto to_decimal(T x) noexcept -> decimal_fp<T>;
+}  // namespace dragonbox
+
+// Returns true iff Float has the implicit bit which is not stored.
+template <typename Float> constexpr auto has_implicit_bit() -> bool {
+  // An 80-bit FP number has a 64-bit significand an no implicit bit.
+  return std::numeric_limits<Float>::digits != 64;
+}
+
+// Returns the number of significand bits stored in Float. The implicit bit is
+// not counted since it is not stored.
+template <typename Float> constexpr auto num_significand_bits() -> int {
+  // std::numeric_limits may not support __float128.
+  return is_float128<Float>() ? 112
+                              : (std::numeric_limits<Float>::digits -
+                                 (has_implicit_bit<Float>() ? 1 : 0));
+}
+
+template <typename Float>
+constexpr auto exponent_mask() ->
+    typename dragonbox::float_info<Float>::carrier_uint {
+  using float_uint = typename dragonbox::float_info<Float>::carrier_uint;
+  return ((float_uint(1) << dragonbox::float_info<Float>::exponent_bits) - 1)
+         << num_significand_bits<Float>();
+}
+template <typename Float> constexpr auto exponent_bias() -> int {
+  // std::numeric_limits may not support __float128.
+  return is_float128<Float>() ? 16383
+                              : std::numeric_limits<Float>::max_exponent - 1;
+}
+
+FMT_CONSTEXPR inline auto compute_exp_size(int exp) -> int {
+  auto prefix_size = 2;  // sign + 'e'
+  auto abs_exp = exp >= 0 ? exp : -exp;
+  if (abs_exp < 100) return prefix_size + 2;
+  return prefix_size + (abs_exp >= 1000 ? 4 : 3);
+}
+
+// Writes the exponent exp in the form "[+-]d{2,3}" to buffer.
+template <typename Char, typename OutputIt>
+FMT_CONSTEXPR auto write_exponent(int exp, OutputIt out) -> OutputIt {
+  FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range");
+  if (exp < 0) {
+    *out++ = static_cast<Char>('-');
+    exp = -exp;
+  } else {
+    *out++ = static_cast<Char>('+');
+  }
+  auto uexp = static_cast<uint32_t>(exp);
+  if (is_constant_evaluated()) {
+    if (uexp < 10) *out++ = '0';
+    return format_decimal<Char>(out, uexp, count_digits(uexp));
+  }
+  if (uexp >= 100u) {
+    const char* top = digits2(uexp / 100);
+    if (uexp >= 1000u) *out++ = static_cast<Char>(top[0]);
+    *out++ = static_cast<Char>(top[1]);
+    uexp %= 100;
+  }
+  const char* d = digits2(uexp);
+  *out++ = static_cast<Char>(d[0]);
+  *out++ = static_cast<Char>(d[1]);
+  return out;
+}
+
+// A floating-point number f * pow(2, e) where F is an unsigned type.
+template <typename F> struct basic_fp {
+  F f;
+  int e;
+
+  static constexpr int num_significand_bits =
+      static_cast<int>(sizeof(F) * num_bits<unsigned char>());
+
+  constexpr basic_fp() : f(0), e(0) {}
+  constexpr basic_fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {}
+
+  // Constructs fp from an IEEE754 floating-point number.
+  template <typename Float> FMT_CONSTEXPR basic_fp(Float n) { assign(n); }
+
+  // Assigns n to this and return true iff predecessor is closer than successor.
+  template <typename Float, FMT_ENABLE_IF(!is_double_double<Float>::value)>
+  FMT_CONSTEXPR auto assign(Float n) -> bool {
+    static_assert(std::numeric_limits<Float>::digits <= 113, "unsupported FP");
+    // Assume Float is in the format [sign][exponent][significand].
+    using carrier_uint = typename dragonbox::float_info<Float>::carrier_uint;
+    const auto num_float_significand_bits =
+        detail::num_significand_bits<Float>();
+    const auto implicit_bit = carrier_uint(1) << num_float_significand_bits;
+    const auto significand_mask = implicit_bit - 1;
+    auto u = bit_cast<carrier_uint>(n);
+    f = static_cast<F>(u & significand_mask);
+    auto biased_e = static_cast<int>((u & exponent_mask<Float>()) >>
+                                     num_float_significand_bits);
+    // The predecessor is closer if n is a normalized power of 2 (f == 0)
+    // other than the smallest normalized number (biased_e > 1).
+    auto is_predecessor_closer = f == 0 && biased_e > 1;
+    if (biased_e == 0)
+      biased_e = 1;  // Subnormals use biased exponent 1 (min exponent).
+    else if (has_implicit_bit<Float>())
+      f += static_cast<F>(implicit_bit);
+    e = biased_e - exponent_bias<Float>() - num_float_significand_bits;
+    if (!has_implicit_bit<Float>()) ++e;
+    return is_predecessor_closer;
+  }
+
+  template <typename Float, FMT_ENABLE_IF(is_double_double<Float>::value)>
+  FMT_CONSTEXPR auto assign(Float n) -> bool {
+    static_assert(std::numeric_limits<double>::is_iec559, "unsupported FP");
+    return assign(static_cast<double>(n));
+  }
+};
+
+using fp = basic_fp<unsigned long long>;
+
+// Normalizes the value converted from double and multiplied by (1 << SHIFT).
+template <int SHIFT = 0, typename F>
+FMT_CONSTEXPR auto normalize(basic_fp<F> value) -> basic_fp<F> {
+  // Handle subnormals.
+  const auto implicit_bit = F(1) << num_significand_bits<double>();
+  const auto shifted_implicit_bit = implicit_bit << SHIFT;
+  while ((value.f & shifted_implicit_bit) == 0) {
+    value.f <<= 1;
+    --value.e;
+  }
+  // Subtract 1 to account for hidden bit.
+  const auto offset = basic_fp<F>::num_significand_bits -
+                      num_significand_bits<double>() - SHIFT - 1;
+  value.f <<= offset;
+  value.e -= offset;
+  return value;
+}
+
+// Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking.
+FMT_CONSTEXPR inline auto multiply(uint64_t lhs, uint64_t rhs) -> uint64_t {
+#if FMT_USE_INT128
+  auto product = static_cast<__uint128_t>(lhs) * rhs;
+  auto f = static_cast<uint64_t>(product >> 64);
+  return (static_cast<uint64_t>(product) & (1ULL << 63)) != 0 ? f + 1 : f;
+#else
+  // Multiply 32-bit parts of significands.
+  uint64_t mask = (1ULL << 32) - 1;
+  uint64_t a = lhs >> 32, b = lhs & mask;
+  uint64_t c = rhs >> 32, d = rhs & mask;
+  uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d;
+  // Compute mid 64-bit of result and round.
+  uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31);
+  return ac + (ad >> 32) + (bc >> 32) + (mid >> 32);
+#endif
+}
+
+FMT_CONSTEXPR inline auto operator*(fp x, fp y) -> fp {
+  return {multiply(x.f, y.f), x.e + y.e + 64};
+}
+
+template <typename T, bool doublish = num_bits<T>() == num_bits<double>()>
+using convert_float_result =
+    conditional_t<std::is_same<T, float>::value || doublish, double, T>;
+
+template <typename T>
+constexpr auto convert_float(T value) -> convert_float_result<T> {
+  return static_cast<convert_float_result<T>>(value);
+}
+
+template <bool C, typename T, typename F, FMT_ENABLE_IF(C)>
+auto select(T true_value, F) -> T {
+  return true_value;
+}
+template <bool C, typename T, typename F, FMT_ENABLE_IF(!C)>
+auto select(T, F false_value) -> F {
+  return false_value;
+}
+
+template <typename Char, typename OutputIt>
+FMT_CONSTEXPR FMT_NOINLINE auto fill(OutputIt it, size_t n,
+                                     const basic_specs& specs) -> OutputIt {
+  auto fill_size = specs.fill_size();
+  if (fill_size == 1) return detail::fill_n(it, n, specs.fill_unit<Char>());
+  if (const Char* data = specs.fill<Char>()) {
+    for (size_t i = 0; i < n; ++i) it = copy<Char>(data, data + fill_size, it);
+  }
+  return it;
+}
+
+// Writes the output of f, padded according to format specifications in specs.
+// size: output size in code units.
+// width: output display width in (terminal) column positions.
+template <typename Char, align default_align = align::left, typename OutputIt,
+          typename F>
+FMT_CONSTEXPR auto write_padded(OutputIt out, const format_specs& specs,
+                                size_t size, size_t width, F&& f) -> OutputIt {
+  static_assert(default_align == align::left || default_align == align::right,
+                "");
+  unsigned spec_width = to_unsigned(specs.width);
+  size_t padding = spec_width > width ? spec_width - width : 0;
+  // Shifts are encoded as string literals because static constexpr is not
+  // supported in constexpr functions.
+  auto* shifts =
+      default_align == align::left ? "\x1f\x1f\x00\x01" : "\x00\x1f\x00\x01";
+  size_t left_padding = padding >> shifts[static_cast<int>(specs.align())];
+  size_t right_padding = padding - left_padding;
+  auto it = reserve(out, size + padding * specs.fill_size());
+  if (left_padding != 0) it = fill<Char>(it, left_padding, specs);
+  it = f(it);
+  if (right_padding != 0) it = fill<Char>(it, right_padding, specs);
+  return base_iterator(out, it);
+}
+
+template <typename Char, align default_align = align::left, typename OutputIt,
+          typename F>
+constexpr auto write_padded(OutputIt out, const format_specs& specs,
+                            size_t size, F&& f) -> OutputIt {
+  return write_padded<Char, default_align>(out, specs, size, size, f);
+}
+
+template <typename Char, align default_align = align::left, typename OutputIt>
+FMT_CONSTEXPR auto write_bytes(OutputIt out, string_view bytes,
+                               const format_specs& specs = {}) -> OutputIt {
+  return write_padded<Char, default_align>(
+      out, specs, bytes.size(), [bytes](reserve_iterator<OutputIt> it) {
+        const char* data = bytes.data();
+        return copy<Char>(data, data + bytes.size(), it);
+      });
+}
+
+template <typename Char, typename OutputIt, typename UIntPtr>
+auto write_ptr(OutputIt out, UIntPtr value, const format_specs* specs)
+    -> OutputIt {
+  int num_digits = count_digits<4>(value);
+  auto size = to_unsigned(num_digits) + size_t(2);
+  auto write = [=](reserve_iterator<OutputIt> it) {
+    *it++ = static_cast<Char>('0');
+    *it++ = static_cast<Char>('x');
+    return format_base2e<Char>(4, it, value, num_digits);
+  };
+  return specs ? write_padded<Char, align::right>(out, *specs, size, write)
+               : base_iterator(out, write(reserve(out, size)));
+}
+
+// Returns true iff the code point cp is printable.
+FMT_API auto is_printable(uint32_t cp) -> bool;
+
+inline auto needs_escape(uint32_t cp) -> bool {
+  if (cp < 0x20 || cp == 0x7f || cp == '"' || cp == '\\') return true;
+  if (const_check(FMT_OPTIMIZE_SIZE > 1)) return false;
+  return !is_printable(cp);
+}
+
+template <typename Char> struct find_escape_result {
+  const Char* begin;
+  const Char* end;
+  uint32_t cp;
+};
+
+template <typename Char>
+auto find_escape(const Char* begin, const Char* end)
+    -> find_escape_result<Char> {
+  for (; begin != end; ++begin) {
+    uint32_t cp = static_cast<unsigned_char<Char>>(*begin);
+    if (const_check(sizeof(Char) == 1) && cp >= 0x80) continue;
+    if (needs_escape(cp)) return {begin, begin + 1, cp};
+  }
+  return {begin, nullptr, 0};
+}
+
+inline auto find_escape(const char* begin, const char* end)
+    -> find_escape_result<char> {
+  if (const_check(!use_utf8)) return find_escape<char>(begin, end);
+  auto result = find_escape_result<char>{end, nullptr, 0};
+  for_each_codepoint(string_view(begin, to_unsigned(end - begin)),
+                     [&](uint32_t cp, string_view sv) {
+                       if (needs_escape(cp)) {
+                         result = {sv.begin(), sv.end(), cp};
+                         return false;
+                       }
+                       return true;
+                     });
+  return result;
+}
+
+template <size_t width, typename Char, typename OutputIt>
+auto write_codepoint(OutputIt out, char prefix, uint32_t cp) -> OutputIt {
+  *out++ = static_cast<Char>('\\');
+  *out++ = static_cast<Char>(prefix);
+  Char buf[width];
+  fill_n(buf, width, static_cast<Char>('0'));
+  format_base2e(4, buf, cp, width);
+  return copy<Char>(buf, buf + width, out);
+}
+
+template <typename OutputIt, typename Char>
+auto write_escaped_cp(OutputIt out, const find_escape_result<Char>& escape)
+    -> OutputIt {
+  auto c = static_cast<Char>(escape.cp);
+  switch (escape.cp) {
+  case '\n':
+    *out++ = static_cast<Char>('\\');
+    c = static_cast<Char>('n');
+    break;
+  case '\r':
+    *out++ = static_cast<Char>('\\');
+    c = static_cast<Char>('r');
+    break;
+  case '\t':
+    *out++ = static_cast<Char>('\\');
+    c = static_cast<Char>('t');
+    break;
+  case '"':  FMT_FALLTHROUGH;
+  case '\'': FMT_FALLTHROUGH;
+  case '\\': *out++ = static_cast<Char>('\\'); break;
+  default:
+    if (escape.cp < 0x100) return write_codepoint<2, Char>(out, 'x', escape.cp);
+    if (escape.cp < 0x10000)
+      return write_codepoint<4, Char>(out, 'u', escape.cp);
+    if (escape.cp < 0x110000)
+      return write_codepoint<8, Char>(out, 'U', escape.cp);
+    for (Char escape_char : basic_string_view<Char>(
+             escape.begin, to_unsigned(escape.end - escape.begin))) {
+      out = write_codepoint<2, Char>(out, 'x',
+                                     static_cast<uint32_t>(escape_char) & 0xFF);
+    }
+    return out;
+  }
+  *out++ = c;
+  return out;
+}
+
+template <typename Char, typename OutputIt>
+auto write_escaped_string(OutputIt out, basic_string_view<Char> str)
+    -> OutputIt {
+  *out++ = static_cast<Char>('"');
+  auto begin = str.begin(), end = str.end();
+  do {
+    auto escape = find_escape(begin, end);
+    out = copy<Char>(begin, escape.begin, out);
+    begin = escape.end;
+    if (!begin) break;
+    out = write_escaped_cp<OutputIt, Char>(out, escape);
+  } while (begin != end);
+  *out++ = static_cast<Char>('"');
+  return out;
+}
+
+template <typename Char, typename OutputIt>
+auto write_escaped_char(OutputIt out, Char v) -> OutputIt {
+  Char v_array[1] = {v};
+  *out++ = static_cast<Char>('\'');
+  if ((needs_escape(static_cast<uint32_t>(v)) && v != static_cast<Char>('"')) ||
+      v == static_cast<Char>('\'')) {
+    out = write_escaped_cp(out,
+                           find_escape_result<Char>{v_array, v_array + 1,
+                                                    static_cast<uint32_t>(v)});
+  } else {
+    *out++ = v;
+  }
+  *out++ = static_cast<Char>('\'');
+  return out;
+}
+
+template <typename Char, typename OutputIt>
+FMT_CONSTEXPR auto write_char(OutputIt out, Char value,
+                              const format_specs& specs) -> OutputIt {
+  bool is_debug = specs.type() == presentation_type::debug;
+  return write_padded<Char>(out, specs, 1, [=](reserve_iterator<OutputIt> it) {
+    if (is_debug) return write_escaped_char(it, value);
+    *it++ = value;
+    return it;
+  });
+}
+
+template <typename Char> class digit_grouping {
+ private:
+  std::string grouping_;
+  std::basic_string<Char> thousands_sep_;
+
+  struct next_state {
+    std::string::const_iterator group;
+    int pos;
+  };
+  auto initial_state() const -> next_state { return {grouping_.begin(), 0}; }
+
+  // Returns the next digit group separator position.
+  auto next(next_state& state) const -> int {
+    if (thousands_sep_.empty()) return max_value<int>();
+    if (state.group == grouping_.end()) return state.pos += grouping_.back();
+    if (*state.group <= 0 || *state.group == max_value<char>())
+      return max_value<int>();
+    state.pos += *state.group++;
+    return state.pos;
+  }
+
+ public:
+  explicit digit_grouping(locale_ref loc, bool localized = true) {
+    if (!localized) return;
+    auto sep = thousands_sep<Char>(loc);
+    grouping_ = sep.grouping;
+    if (sep.thousands_sep) thousands_sep_.assign(1, sep.thousands_sep);
+  }
+  digit_grouping(std::string grouping, std::basic_string<Char> sep)
+      : grouping_(std::move(grouping)), thousands_sep_(std::move(sep)) {}
+
+  auto has_separator() const -> bool { return !thousands_sep_.empty(); }
+
+  auto count_separators(int num_digits) const -> int {
+    int count = 0;
+    auto state = initial_state();
+    while (num_digits > next(state)) ++count;
+    return count;
+  }
+
+  // Applies grouping to digits and writes the output to out.
+  template <typename Out, typename C>
+  auto apply(Out out, basic_string_view<C> digits) const -> Out {
+    auto num_digits = static_cast<int>(digits.size());
+    auto separators = basic_memory_buffer<int>();
+    separators.push_back(0);
+    auto state = initial_state();
+    while (int i = next(state)) {
+      if (i >= num_digits) break;
+      separators.push_back(i);
+    }
+    for (int i = 0, sep_index = static_cast<int>(separators.size() - 1);
+         i < num_digits; ++i) {
+      if (num_digits - i == separators[sep_index]) {
+        out = copy<Char>(thousands_sep_.data(),
+                         thousands_sep_.data() + thousands_sep_.size(), out);
+        --sep_index;
+      }
+      *out++ = static_cast<Char>(digits[to_unsigned(i)]);
+    }
+    return out;
+  }
+};
+
+FMT_CONSTEXPR inline void prefix_append(unsigned& prefix, unsigned value) {
+  prefix |= prefix != 0 ? value << 8 : value;
+  prefix += (1u + (value > 0xff ? 1 : 0)) << 24;
+}
+
+// Writes a decimal integer with digit grouping.
+template <typename OutputIt, typename UInt, typename Char>
+auto write_int(OutputIt out, UInt value, unsigned prefix,
+               const format_specs& specs, const digit_grouping<Char>& grouping)
+    -> OutputIt {
+  static_assert(std::is_same<uint64_or_128_t<UInt>, UInt>::value, "");
+  int num_digits = 0;
+  auto buffer = memory_buffer();
+  switch (specs.type()) {
+  default: FMT_ASSERT(false, ""); FMT_FALLTHROUGH;
+  case presentation_type::none:
+  case presentation_type::dec:
+    num_digits = count_digits(value);
+    format_decimal<char>(appender(buffer), value, num_digits);
+    break;
+  case presentation_type::hex:
+    if (specs.alt())
+      prefix_append(prefix, unsigned(specs.upper() ? 'X' : 'x') << 8 | '0');
+    num_digits = count_digits<4>(value);
+    format_base2e<char>(4, appender(buffer), value, num_digits, specs.upper());
+    break;
+  case presentation_type::oct:
+    num_digits = count_digits<3>(value);
+    // Octal prefix '0' is counted as a digit, so only add it if precision
+    // is not greater than the number of digits.
+    if (specs.alt() && specs.precision <= num_digits && value != 0)
+      prefix_append(prefix, '0');
+    format_base2e<char>(3, appender(buffer), value, num_digits);
+    break;
+  case presentation_type::bin:
+    if (specs.alt())
+      prefix_append(prefix, unsigned(specs.upper() ? 'B' : 'b') << 8 | '0');
+    num_digits = count_digits<1>(value);
+    format_base2e<char>(1, appender(buffer), value, num_digits);
+    break;
+  case presentation_type::chr:
+    return write_char<Char>(out, static_cast<Char>(value), specs);
+  }
+
+  unsigned size = (prefix != 0 ? prefix >> 24 : 0) + to_unsigned(num_digits) +
+                  to_unsigned(grouping.count_separators(num_digits));
+  return write_padded<Char, align::right>(
+      out, specs, size, size, [&](reserve_iterator<OutputIt> it) {
+        for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
+          *it++ = static_cast<Char>(p & 0xff);
+        return grouping.apply(it, string_view(buffer.data(), buffer.size()));
+      });
+}
+
+#if FMT_USE_LOCALE
+// Writes a localized value.
+FMT_API auto write_loc(appender out, loc_value value, const format_specs& specs,
+                       locale_ref loc) -> bool;
+auto write_loc(basic_appender<wchar_t> out, loc_value value,
+               const format_specs& specs, locale_ref loc) -> bool;
+#endif
+template <typename OutputIt>
+inline auto write_loc(OutputIt, const loc_value&, const format_specs&,
+                      locale_ref) -> bool {
+  return false;
+}
+
+template <typename UInt> struct write_int_arg {
+  UInt abs_value;
+  unsigned prefix;
+};
+
+template <typename T>
+FMT_CONSTEXPR auto make_write_int_arg(T value, sign s)
+    -> write_int_arg<uint32_or_64_or_128_t<T>> {
+  auto prefix = 0u;
+  auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
+  if (is_negative(value)) {
+    prefix = 0x01000000 | '-';
+    abs_value = 0 - abs_value;
+  } else {
+    constexpr unsigned prefixes[4] = {0, 0, 0x1000000u | '+', 0x1000000u | ' '};
+    prefix = prefixes[static_cast<int>(s)];
+  }
+  return {abs_value, prefix};
+}
+
+template <typename Char = char> struct loc_writer {
+  basic_appender<Char> out;
+  const format_specs& specs;
+  std::basic_string<Char> sep;
+  std::string grouping;
+  std::basic_string<Char> decimal_point;
+
+  template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
+  auto operator()(T value) -> bool {
+    auto arg = make_write_int_arg(value, specs.sign());
+    write_int(out, static_cast<uint64_or_128_t<T>>(arg.abs_value), arg.prefix,
+              specs, digit_grouping<Char>(grouping, sep));
+    return true;
+  }
+
+  template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
+  auto operator()(T) -> bool {
+    return false;
+  }
+};
+
+// Size and padding computation separate from write_int to avoid template bloat.
+struct size_padding {
+  unsigned size;
+  unsigned padding;
+
+  FMT_CONSTEXPR size_padding(int num_digits, unsigned prefix,
+                             const format_specs& specs)
+      : size((prefix >> 24) + to_unsigned(num_digits)), padding(0) {
+    if (specs.align() == align::numeric) {
+      auto width = to_unsigned(specs.width);
+      if (width > size) {
+        padding = width - size;
+        size = width;
+      }
+    } else if (specs.precision > num_digits) {
+      size = (prefix >> 24) + to_unsigned(specs.precision);
+      padding = to_unsigned(specs.precision - num_digits);
+    }
+  }
+};
+
+template <typename Char, typename OutputIt, typename T>
+FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, write_int_arg<T> arg,
+                                        const format_specs& specs) -> OutputIt {
+  static_assert(std::is_same<T, uint32_or_64_or_128_t<T>>::value, "");
+
+  constexpr size_t buffer_size = num_bits<T>();
+  char buffer[buffer_size];
+  if (is_constant_evaluated()) fill_n(buffer, buffer_size, '\0');
+  const char* begin = nullptr;
+  const char* end = buffer + buffer_size;
+
+  auto abs_value = arg.abs_value;
+  auto prefix = arg.prefix;
+  switch (specs.type()) {
+  default: FMT_ASSERT(false, ""); FMT_FALLTHROUGH;
+  case presentation_type::none:
+  case presentation_type::dec:
+    begin = do_format_decimal(buffer, abs_value, buffer_size);
+    break;
+  case presentation_type::hex:
+    begin = do_format_base2e(4, buffer, abs_value, buffer_size, specs.upper());
+    if (specs.alt())
+      prefix_append(prefix, unsigned(specs.upper() ? 'X' : 'x') << 8 | '0');
+    break;
+  case presentation_type::oct: {
+    begin = do_format_base2e(3, buffer, abs_value, buffer_size);
+    // Octal prefix '0' is counted as a digit, so only add it if precision
+    // is not greater than the number of digits.
+    auto num_digits = end - begin;
+    if (specs.alt() && specs.precision <= num_digits && abs_value != 0)
+      prefix_append(prefix, '0');
+    break;
+  }
+  case presentation_type::bin:
+    begin = do_format_base2e(1, buffer, abs_value, buffer_size);
+    if (specs.alt())
+      prefix_append(prefix, unsigned(specs.upper() ? 'B' : 'b') << 8 | '0');
+    break;
+  case presentation_type::chr:
+    return write_char<Char>(out, static_cast<Char>(abs_value), specs);
+  }
+
+  // Write an integer in the format
+  //   <left-padding><prefix><numeric-padding><digits><right-padding>
+  // prefix contains chars in three lower bytes and the size in the fourth byte.
+  int num_digits = static_cast<int>(end - begin);
+  // Slightly faster check for specs.width == 0 && specs.precision == -1.
+  if ((specs.width | (specs.precision + 1)) == 0) {
+    auto it = reserve(out, to_unsigned(num_digits) + (prefix >> 24));
+    for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
+      *it++ = static_cast<Char>(p & 0xff);
+    return base_iterator(out, copy<Char>(begin, end, it));
+  }
+  auto sp = size_padding(num_digits, prefix, specs);
+  unsigned padding = sp.padding;
+  return write_padded<Char, align::right>(
+      out, specs, sp.size, [=](reserve_iterator<OutputIt> it) {
+        for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8)
+          *it++ = static_cast<Char>(p & 0xff);
+        it = detail::fill_n(it, padding, static_cast<Char>('0'));
+        return copy<Char>(begin, end, it);
+      });
+}
+
+template <typename Char, typename OutputIt, typename T>
+FMT_CONSTEXPR FMT_NOINLINE auto write_int_noinline(OutputIt out,
+                                                   write_int_arg<T> arg,
+                                                   const format_specs& specs)
+    -> OutputIt {
+  return write_int<Char>(out, arg, specs);
+}
+
+template <typename Char, typename T,
+          FMT_ENABLE_IF(is_integral<T>::value &&
+                        !std::is_same<T, bool>::value &&
+                        !std::is_same<T, Char>::value)>
+FMT_CONSTEXPR FMT_INLINE auto write(basic_appender<Char> out, T value,
+                                    const format_specs& specs, locale_ref loc)
+    -> basic_appender<Char> {
+  if (specs.localized() && write_loc(out, value, specs, loc)) return out;
+  return write_int_noinline<Char>(out, make_write_int_arg(value, specs.sign()),
+                                  specs);
+}
+
+// An inlined version of write used in format string compilation.
+template <typename Char, typename OutputIt, typename T,
+          FMT_ENABLE_IF(is_integral<T>::value &&
+                        !std::is_same<T, bool>::value &&
+                        !std::is_same<T, Char>::value &&
+                        !std::is_same<OutputIt, basic_appender<Char>>::value)>
+FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value,
+                                    const format_specs& specs, locale_ref loc)
+    -> OutputIt {
+  if (specs.localized() && write_loc(out, value, specs, loc)) return out;
+  return write_int<Char>(out, make_write_int_arg(value, specs.sign()), specs);
+}
+
+template <typename Char, typename OutputIt>
+FMT_CONSTEXPR auto write(OutputIt out, Char value, const format_specs& specs,
+                         locale_ref loc = {}) -> OutputIt {
+  // char is formatted as unsigned char for consistency across platforms.
+  using unsigned_type =
+      conditional_t<std::is_same<Char, char>::value, unsigned char, unsigned>;
+  return check_char_specs(specs)
+             ? write_char<Char>(out, value, specs)
+             : write<Char>(out, static_cast<unsigned_type>(value), specs, loc);
+}
+
+template <typename Char, typename OutputIt,
+          FMT_ENABLE_IF(std::is_same<Char, char>::value)>
+FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,
+                         const format_specs& specs) -> OutputIt {
+  bool is_debug = specs.type() == presentation_type::debug;
+  if (specs.precision < 0 && specs.width == 0) {
+    auto&& it = reserve(out, s.size());
+    return is_debug ? write_escaped_string(it, s) : copy<char>(s, it);
+  }
+
+  size_t display_width_limit =
+      specs.precision < 0 ? SIZE_MAX : to_unsigned(specs.precision);
+  size_t display_width =
+      !is_debug || specs.precision == 0 ? 0 : 1;  // Account for opening '"'.
+  size_t size = !is_debug || specs.precision == 0 ? 0 : 1;
+  for_each_codepoint(s, [&](uint32_t cp, string_view sv) {
+    if (is_debug && needs_escape(cp)) {
+      counting_buffer<char> buf;
+      write_escaped_cp(basic_appender<char>(buf),
+                       find_escape_result<char>{sv.begin(), sv.end(), cp});
+      // We're reinterpreting bytes as display width. That's okay
+      // because write_escaped_cp() only writes ASCII characters.
+      size_t cp_width = buf.count();
+      if (display_width + cp_width <= display_width_limit) {
+        display_width += cp_width;
+        size += cp_width;
+        // If this is the end of the string, account for closing '"'.
+        if (display_width < display_width_limit && sv.end() == s.end()) {
+          ++display_width;
+          ++size;
+        }
+        return true;
+      }
+
+      size += display_width_limit - display_width;
+      display_width = display_width_limit;
+      return false;
+    }
+
+    size_t cp_width = display_width_of(cp);
+    if (cp_width + display_width <= display_width_limit) {
+      display_width += cp_width;
+      size += sv.size();
+      // If this is the end of the string, account for closing '"'.
+      if (is_debug && display_width < display_width_limit &&
+          sv.end() == s.end()) {
+        ++display_width;
+        ++size;
+      }
+      return true;
+    }
+
+    return false;
+  });
+
+  struct bounded_output_iterator {
+    reserve_iterator<OutputIt> underlying_iterator;
+    size_t bound;
+
+    FMT_CONSTEXPR auto operator*() -> bounded_output_iterator& { return *this; }
+    FMT_CONSTEXPR auto operator++() -> bounded_output_iterator& {
+      return *this;
+    }
+    FMT_CONSTEXPR auto operator++(int) -> bounded_output_iterator& {
+      return *this;
+    }
+    FMT_CONSTEXPR auto operator=(char c) -> bounded_output_iterator& {
+      if (bound > 0) {
+        *underlying_iterator++ = c;
+        --bound;
+      }
+      return *this;
+    }
+  };
+
+  return write_padded<char>(
+      out, specs, size, display_width, [=](reserve_iterator<OutputIt> it) {
+        return is_debug
+                   ? write_escaped_string(bounded_output_iterator{it, size}, s)
+                         .underlying_iterator
+                   : copy<char>(s.data(), s.data() + size, it);
+      });
+}
+
+template <typename Char, typename OutputIt,
+          FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
+FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,
+                         const format_specs& specs) -> OutputIt {
+  auto data = s.data();
+  auto size = s.size();
+  if (specs.precision >= 0 && to_unsigned(specs.precision) < size)
+    size = to_unsigned(specs.precision);
+
+  bool is_debug = specs.type() == presentation_type::debug;
+  if (is_debug) {
+    auto buf = counting_buffer<Char>();
+    write_escaped_string(basic_appender<Char>(buf), s);
+    size = buf.count();
+  }
+
+  return write_padded<Char>(
+      out, specs, size, [=](reserve_iterator<OutputIt> it) {
+        return is_debug ? write_escaped_string(it, s)
+                        : copy<Char>(data, data + size, it);
+      });
+}
+
+template <typename Char, typename OutputIt>
+FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> s,
+                         const format_specs& specs, locale_ref) -> OutputIt {
+  return write<Char>(out, s, specs);
+}
+
+template <typename Char, typename OutputIt>
+FMT_CONSTEXPR auto write(OutputIt out, const Char* s, const format_specs& specs,
+                         locale_ref) -> OutputIt {
+  if (specs.type() == presentation_type::pointer)
+    return write_ptr<Char>(out, bit_cast<uintptr_t>(s), &specs);
+  if (!s) report_error("string pointer is null");
+  return write<Char>(out, basic_string_view<Char>(s), specs, {});
+}
+
+template <typename Char, typename OutputIt, typename T,
+          FMT_ENABLE_IF(is_integral<T>::value &&
+                        !std::is_same<T, bool>::value &&
+                        !std::is_same<T, Char>::value)>
+FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
+  auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
+  bool negative = is_negative(value);
+  // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer.
+  if (negative) abs_value = ~abs_value + 1;
+  int num_digits = count_digits(abs_value);
+  auto size = (negative ? 1 : 0) + static_cast<size_t>(num_digits);
+  if (auto ptr = to_pointer<Char>(out, size)) {
+    if (negative) *ptr++ = static_cast<Char>('-');
+    format_decimal<Char>(ptr, abs_value, num_digits);
+    return out;
+  }
+  if (negative) *out++ = static_cast<Char>('-');
+  return format_decimal<Char>(out, abs_value, num_digits);
+}
+
+template <typename Char>
+FMT_CONSTEXPR auto parse_align(const Char* begin, const Char* end,
+                               format_specs& specs) -> const Char* {
+  FMT_ASSERT(begin != end, "");
+  auto alignment = align::none;
+  auto p = begin + code_point_length(begin);
+  if (end - p <= 0) p = begin;
+  for (;;) {
+    switch (to_ascii(*p)) {
+    case '<': alignment = align::left; break;
+    case '>': alignment = align::right; break;
+    case '^': alignment = align::center; break;
+    }
+    if (alignment != align::none) {
+      if (p != begin) {
+        auto c = *begin;
+        if (c == '}') return begin;
+        if (c == '{') {
+          report_error("invalid fill character '{'");
+          return begin;
+        }
+        specs.set_fill(basic_string_view<Char>(begin, to_unsigned(p - begin)));
+        begin = p + 1;
+      } else {
+        ++begin;
+      }
+      break;
+    } else if (p == begin) {
+      break;
+    }
+    p = begin;
+  }
+  specs.set_align(alignment);
+  return begin;
+}
+
+template <typename Char, typename OutputIt>
+FMT_CONSTEXPR20 auto write_nonfinite(OutputIt out, bool isnan,
+                                     format_specs specs, sign s) -> OutputIt {
+  auto str =
+      isnan ? (specs.upper() ? "NAN" : "nan") : (specs.upper() ? "INF" : "inf");
+  constexpr size_t str_size = 3;
+  auto size = str_size + (s != sign::none ? 1 : 0);
+  // Replace '0'-padding with space for non-finite values.
+  const bool is_zero_fill =
+      specs.fill_size() == 1 && specs.fill_unit<Char>() == '0';
+  if (is_zero_fill) specs.set_fill(' ');
+  return write_padded<Char>(out, specs, size,
+                            [=](reserve_iterator<OutputIt> it) {
+                              if (s != sign::none)
+                                *it++ = detail::getsign<Char>(s);
+                              return copy<Char>(str, str + str_size, it);
+                            });
+}
+
+// A decimal floating-point number significand * pow(10, exp).
+struct big_decimal_fp {
+  const char* significand;
+  int significand_size;
+  int exponent;
+};
+
+constexpr auto get_significand_size(const big_decimal_fp& f) -> int {
+  return f.significand_size;
+}
+template <typename T>
+inline auto get_significand_size(const dragonbox::decimal_fp<T>& f) -> int {
+  return count_digits(f.significand);
+}
+
+template <typename Char, typename OutputIt>
+constexpr auto write_significand(OutputIt out, const char* significand,
+                                 int significand_size) -> OutputIt {
+  return copy<Char>(significand, significand + significand_size, out);
+}
+template <typename Char, typename OutputIt, typename UInt>
+inline auto write_significand(OutputIt out, UInt significand,
+                              int significand_size) -> OutputIt {
+  return format_decimal<Char>(out, significand, significand_size);
+}
+template <typename Char, typename OutputIt, typename T, typename Grouping>
+FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,
+                                       int significand_size, int exponent,
+                                       const Grouping& grouping) -> OutputIt {
+  if (!grouping.has_separator()) {
+    out = write_significand<Char>(out, significand, significand_size);
+    return detail::fill_n(out, exponent, static_cast<Char>('0'));
+  }
+  auto buffer = memory_buffer();
+  write_significand<char>(appender(buffer), significand, significand_size);
+  detail::fill_n(appender(buffer), exponent, '0');
+  return grouping.apply(out, string_view(buffer.data(), buffer.size()));
+}
+
+template <typename Char, typename UInt,
+          FMT_ENABLE_IF(std::is_integral<UInt>::value)>
+inline auto write_significand(Char* out, UInt significand, int significand_size,
+                              int integral_size, Char decimal_point) -> Char* {
+  if (!decimal_point) return format_decimal(out, significand, significand_size);
+  out += significand_size + 1;
+  Char* end = out;
+  int floating_size = significand_size - integral_size;
+  for (int i = floating_size / 2; i > 0; --i) {
+    out -= 2;
+    write2digits(out, static_cast<size_t>(significand % 100));
+    significand /= 100;
+  }
+  if (floating_size % 2 != 0) {
+    *--out = static_cast<Char>('0' + significand % 10);
+    significand /= 10;
+  }
+  *--out = decimal_point;
+  format_decimal(out - integral_size, significand, integral_size);
+  return end;
+}
+
+template <typename OutputIt, typename UInt, typename Char,
+          FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<OutputIt>>::value)>
+inline auto write_significand(OutputIt out, UInt significand,
+                              int significand_size, int integral_size,
+                              Char decimal_point) -> OutputIt {
+  // Buffer is large enough to hold digits (digits10 + 1) and a decimal point.
+  Char buffer[digits10<UInt>() + 2];
+  auto end = write_significand(buffer, significand, significand_size,
+                               integral_size, decimal_point);
+  return detail::copy_noinline<Char>(buffer, end, out);
+}
+
+template <typename OutputIt, typename Char>
+FMT_CONSTEXPR auto write_significand(OutputIt out, const char* significand,
+                                     int significand_size, int integral_size,
+                                     Char decimal_point) -> OutputIt {
+  out = detail::copy_noinline<Char>(significand, significand + integral_size,
+                                    out);
+  if (!decimal_point) return out;
+  *out++ = decimal_point;
+  return detail::copy_noinline<Char>(significand + integral_size,
+                                     significand + significand_size, out);
+}
+
+template <typename OutputIt, typename Char, typename T, typename Grouping>
+FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand,
+                                       int significand_size, int integral_size,
+                                       Char decimal_point,
+                                       const Grouping& grouping) -> OutputIt {
+  if (!grouping.has_separator()) {
+    return write_significand(out, significand, significand_size, integral_size,
+                             decimal_point);
+  }
+  auto buffer = basic_memory_buffer<Char>();
+  write_significand(basic_appender<Char>(buffer), significand, significand_size,
+                    integral_size, decimal_point);
+  grouping.apply(
+      out, basic_string_view<Char>(buffer.data(), to_unsigned(integral_size)));
+  return detail::copy_noinline<Char>(buffer.data() + integral_size,
+                                     buffer.end(), out);
+}
+
+// Numbers with exponents greater or equal to the returned value will use
+// the exponential notation.
+template <typename T> FMT_CONSTEVAL auto exp_upper() -> int {
+  return std::numeric_limits<T>::digits10 != 0
+             ? min_of(16, std::numeric_limits<T>::digits10 + 1)
+             : 16;
+}
+
+// Use the fixed notation if the exponent is in [-4, exp_upper),
+// e.g. 0.0001 instead of 1e-04. Otherwise use the exponent notation.
+constexpr auto use_fixed(int exp, int exp_upper) -> bool {
+  return exp >= -4 && exp < exp_upper;
+}
+
+template <typename Char> class fallback_digit_grouping {
+ public:
+  constexpr fallback_digit_grouping(locale_ref, bool) {}
+
+  constexpr auto has_separator() const -> bool { return false; }
+
+  constexpr auto count_separators(int) const -> int { return 0; }
+
+  template <typename Out, typename C>
+  constexpr auto apply(Out out, basic_string_view<C>) const -> Out {
+    return out;
+  }
+};
+
+template <typename Char, typename Grouping, typename OutputIt,
+          typename DecimalFP>
+FMT_CONSTEXPR20 auto write_fixed(OutputIt out, const DecimalFP& f,
+                                 int significand_size, Char decimal_point,
+                                 const format_specs& specs, sign s,
+                                 locale_ref loc = {}) -> OutputIt {
+  using iterator = reserve_iterator<OutputIt>;
+
+  int exp = f.exponent + significand_size;
+  long long size = significand_size + (s != sign::none ? 1 : 0);
+  if (f.exponent >= 0) {
+    // 1234e5 -> 123400000[.0+]
+    size += f.exponent;
+    int num_zeros = specs.precision - exp;
+    abort_fuzzing_if(num_zeros > 5000);
+    if (specs.alt()) {
+      ++size;
+      if (num_zeros <= 0 && specs.type() != presentation_type::fixed)
+        num_zeros = 0;
+      if (num_zeros > 0) size += num_zeros;
+    }
+    auto grouping = Grouping(loc, specs.localized());
+    size += grouping.count_separators(exp);
+    return write_padded<Char, align::right>(
+        out, specs, to_unsigned(size), [&](iterator it) {
+          if (s != sign::none) *it++ = detail::getsign<Char>(s);
+          it = write_significand<Char>(it, f.significand, significand_size,
+                                       f.exponent, grouping);
+          if (!specs.alt()) return it;
+          *it++ = decimal_point;
+          return num_zeros > 0 ? detail::fill_n(it, num_zeros, Char('0')) : it;
+        });
+  }
+  if (exp > 0) {
+    // 1234e-2 -> 12.34[0+]
+    int num_zeros = specs.alt() ? specs.precision - significand_size : 0;
+    size += 1 + max_of(num_zeros, 0);
+    auto grouping = Grouping(loc, specs.localized());
+    size += grouping.count_separators(exp);
+    return write_padded<Char, align::right>(
+        out, specs, to_unsigned(size), [&](iterator it) {
+          if (s != sign::none) *it++ = detail::getsign<Char>(s);
+          it = write_significand(it, f.significand, significand_size, exp,
+                                 decimal_point, grouping);
+          return num_zeros > 0 ? detail::fill_n(it, num_zeros, Char('0')) : it;
+        });
+  }
+  // 1234e-6 -> 0.001234
+  int num_zeros = -exp;
+  if (significand_size == 0 && specs.precision >= 0 &&
+      specs.precision < num_zeros) {
+    num_zeros = specs.precision;
+  }
+  bool pointy = num_zeros != 0 || significand_size != 0 || specs.alt();
+  size += 1 + (pointy ? 1 : 0) + num_zeros;
+  return write_padded<Char, align::right>(
+      out, specs, to_unsigned(size), [&](iterator it) {
+        if (s != sign::none) *it++ = detail::getsign<Char>(s);
+        *it++ = Char('0');
+        if (!pointy) return it;
+        *it++ = decimal_point;
+        it = detail::fill_n(it, num_zeros, Char('0'));
+        return write_significand<Char>(it, f.significand, significand_size);
+      });
+}
+
+template <typename Char, typename Grouping, typename OutputIt,
+          typename DecimalFP>
+FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& f,
+                                    const format_specs& specs, sign s,
+                                    int exp_upper, locale_ref loc) -> OutputIt {
+  Char point = specs.localized() ? detail::decimal_point<Char>(loc) : Char('.');
+  int significand_size = get_significand_size(f);
+  int exp = f.exponent + significand_size - 1;
+  if (specs.type() == presentation_type::fixed ||
+      (specs.type() != presentation_type::exp &&
+       use_fixed(exp, specs.precision > 0 ? specs.precision : exp_upper))) {
+    return write_fixed<Char, Grouping>(out, f, significand_size, point, specs,
+                                       s, loc);
+  }
+
+  // Write value in the exponential format.
+  int num_zeros = 0;
+  long long size = significand_size + (s != sign::none ? 1 : 0);
+  if (specs.alt()) {
+    num_zeros = max_of(specs.precision - significand_size, 0);
+    size += num_zeros;
+  } else if (significand_size == 1) {
+    point = Char();
+  }
+  size += (point ? 1 : 0) + compute_exp_size(exp);
+  char exp_char = specs.upper() ? 'E' : 'e';
+  auto write = [=](reserve_iterator<OutputIt> it) {
+    if (s != sign::none) *it++ = detail::getsign<Char>(s);
+    // Insert a decimal point after the first digit and add an exponent.
+    it = write_significand(it, f.significand, significand_size, 1, point);
+    if (num_zeros > 0) it = detail::fill_n(it, num_zeros, Char('0'));
+    *it++ = Char(exp_char);
+    return write_exponent<Char>(exp, it);
+  };
+  auto usize = to_unsigned(size);
+  return specs.width > 0
+             ? write_padded<Char, align::right>(out, specs, usize, write)
+             : base_iterator(out, write(reserve(out, usize)));
+}
+
+template <typename Char, typename OutputIt, typename DecimalFP>
+FMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& f,
+                                 const format_specs& specs, sign s,
+                                 int exp_upper, locale_ref loc) -> OutputIt {
+  if (is_constant_evaluated()) {
+    return do_write_float<Char, fallback_digit_grouping<Char>>(out, f, specs, s,
+                                                               exp_upper, loc);
+  } else {
+    return do_write_float<Char, digit_grouping<Char>>(out, f, specs, s,
+                                                      exp_upper, loc);
+  }
+}
+
+template <typename T> constexpr auto isnan(T value) -> bool {
+  return value != value;  // std::isnan doesn't support __float128.
+}
+
+template <typename T, typename Enable = void>
+struct has_isfinite : std::false_type {};
+
+template <typename T>
+struct has_isfinite<T, enable_if_t<sizeof(std::isfinite(T())) != 0>>
+    : std::true_type {};
+
+template <typename T,
+          FMT_ENABLE_IF(is_floating_point<T>::value&& has_isfinite<T>::value)>
+FMT_CONSTEXPR20 auto isfinite(T value) -> bool {
+  constexpr T inf = T(std::numeric_limits<double>::infinity());
+  if (is_constant_evaluated())
+    return !detail::isnan(value) && value < inf && value > -inf;
+  return std::isfinite(value);
+}
+template <typename T, FMT_ENABLE_IF(!has_isfinite<T>::value)>
+FMT_CONSTEXPR auto isfinite(T value) -> bool {
+  T inf = T(std::numeric_limits<double>::infinity());
+  // std::isfinite doesn't support __float128.
+  return !detail::isnan(value) && value < inf && value > -inf;
+}
+
+template <typename T, FMT_ENABLE_IF(is_floating_point<T>::value)>
+FMT_INLINE FMT_CONSTEXPR auto signbit(T value) -> bool {
+  if (is_constant_evaluated()) {
+#ifdef __cpp_if_constexpr
+    if constexpr (std::numeric_limits<double>::is_iec559) {
+      auto bits = detail::bit_cast<uint64_t>(static_cast<double>(value));
+      return (bits >> (num_bits<uint64_t>() - 1)) != 0;
+    }
+#endif
+  }
+  return std::signbit(static_cast<double>(value));
+}
+
+inline FMT_CONSTEXPR20 void adjust_precision(int& precision, int exp10) {
+  // Adjust fixed precision by exponent because it is relative to decimal
+  // point.
+  if (exp10 > 0 && precision > max_value<int>() - exp10)
+    FMT_THROW(format_error("number is too big"));
+  precision += exp10;
+}
+
+class bigint {
+ private:
+  // A bigint is a number in the form bigit_[N - 1] ... bigit_[0] * 32^exp_.
+  using bigit = uint32_t;  // A big digit.
+  using double_bigit = uint64_t;
+  enum { bigit_bits = num_bits<bigit>() };
+  enum { bigits_capacity = 32 };
+  basic_memory_buffer<bigit, bigits_capacity> bigits_;
+  int exp_;
+
+  friend struct formatter<bigint>;
+
+  FMT_CONSTEXPR auto get_bigit(int i) const -> bigit {
+    return i >= exp_ && i < num_bigits() ? bigits_[i - exp_] : 0;
+  }
+
+  FMT_CONSTEXPR void subtract_bigits(int index, bigit other, bigit& borrow) {
+    auto result = double_bigit(bigits_[index]) - other - borrow;
+    bigits_[index] = static_cast<bigit>(result);
+    borrow = static_cast<bigit>(result >> (bigit_bits * 2 - 1));
+  }
+
+  FMT_CONSTEXPR void remove_leading_zeros() {
+    int num_bigits = static_cast<int>(bigits_.size()) - 1;
+    while (num_bigits > 0 && bigits_[num_bigits] == 0) --num_bigits;
+    bigits_.resize(to_unsigned(num_bigits + 1));
+  }
+
+  // Computes *this -= other assuming aligned bigints and *this >= other.
+  FMT_CONSTEXPR void subtract_aligned(const bigint& other) {
+    FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints");
+    FMT_ASSERT(compare(*this, other) >= 0, "");
+    bigit borrow = 0;
+    int i = other.exp_ - exp_;
+    for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j)
+      subtract_bigits(i, other.bigits_[j], borrow);
+    if (borrow != 0) subtract_bigits(i, 0, borrow);
+    FMT_ASSERT(borrow == 0, "");
+    remove_leading_zeros();
+  }
+
+  FMT_CONSTEXPR void multiply(uint32_t value) {
+    bigit carry = 0;
+    const double_bigit wide_value = value;
+    for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
+      double_bigit result = bigits_[i] * wide_value + carry;
+      bigits_[i] = static_cast<bigit>(result);
+      carry = static_cast<bigit>(result >> bigit_bits);
+    }
+    if (carry != 0) bigits_.push_back(carry);
+  }
+
+  template <typename UInt, FMT_ENABLE_IF(std::is_same<UInt, uint64_t>::value ||
+                                         std::is_same<UInt, uint128_t>::value)>
+  FMT_CONSTEXPR void multiply(UInt value) {
+    using half_uint =
+        conditional_t<std::is_same<UInt, uint128_t>::value, uint64_t, uint32_t>;
+    const int shift = num_bits<half_uint>() - bigit_bits;
+    const UInt lower = static_cast<half_uint>(value);
+    const UInt upper = value >> num_bits<half_uint>();
+    UInt carry = 0;
+    for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
+      UInt result = lower * bigits_[i] + static_cast<bigit>(carry);
+      carry = (upper * bigits_[i] << shift) + (result >> bigit_bits) +
+              (carry >> bigit_bits);
+      bigits_[i] = static_cast<bigit>(result);
+    }
+    while (carry != 0) {
+      bigits_.push_back(static_cast<bigit>(carry));
+      carry >>= bigit_bits;
+    }
+  }
+
+  template <typename UInt, FMT_ENABLE_IF(std::is_same<UInt, uint64_t>::value ||
+                                         std::is_same<UInt, uint128_t>::value)>
+  FMT_CONSTEXPR void assign(UInt n) {
+    size_t num_bigits = 0;
+    do {
+      bigits_[num_bigits++] = static_cast<bigit>(n);
+      n >>= bigit_bits;
+    } while (n != 0);
+    bigits_.resize(num_bigits);
+    exp_ = 0;
+  }
+
+ public:
+  FMT_CONSTEXPR bigint() : exp_(0) {}
+  explicit bigint(uint64_t n) { assign(n); }
+
+  bigint(const bigint&) = delete;
+  void operator=(const bigint&) = delete;
+
+  FMT_CONSTEXPR void assign(const bigint& other) {
+    auto size = other.bigits_.size();
+    bigits_.resize(size);
+    auto data = other.bigits_.data();
+    copy<bigit>(data, data + size, bigits_.data());
+    exp_ = other.exp_;
+  }
+
+  template <typename Int> FMT_CONSTEXPR void operator=(Int n) {
+    FMT_ASSERT(n > 0, "");
+    assign(uint64_or_128_t<Int>(n));
+  }
+
+  FMT_CONSTEXPR auto num_bigits() const -> int {
+    return static_cast<int>(bigits_.size()) + exp_;
+  }
+
+  FMT_CONSTEXPR auto operator<<=(int shift) -> bigint& {
+    FMT_ASSERT(shift >= 0, "");
+    exp_ += shift / bigit_bits;
+    shift %= bigit_bits;
+    if (shift == 0) return *this;
+    bigit carry = 0;
+    for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
+      bigit c = bigits_[i] >> (bigit_bits - shift);
+      bigits_[i] = (bigits_[i] << shift) + carry;
+      carry = c;
+    }
+    if (carry != 0) bigits_.push_back(carry);
+    return *this;
+  }
+
+  template <typename Int> FMT_CONSTEXPR auto operator*=(Int value) -> bigint& {
+    FMT_ASSERT(value > 0, "");
+    multiply(uint32_or_64_or_128_t<Int>(value));
+    return *this;
+  }
+
+  friend FMT_CONSTEXPR auto compare(const bigint& b1, const bigint& b2) -> int {
+    int num_bigits1 = b1.num_bigits(), num_bigits2 = b2.num_bigits();
+    if (num_bigits1 != num_bigits2) return num_bigits1 > num_bigits2 ? 1 : -1;
+    int i = static_cast<int>(b1.bigits_.size()) - 1;
+    int j = static_cast<int>(b2.bigits_.size()) - 1;
+    int end = i - j;
+    if (end < 0) end = 0;
+    for (; i >= end; --i, --j) {
+      bigit b1_bigit = b1.bigits_[i], b2_bigit = b2.bigits_[j];
+      if (b1_bigit != b2_bigit) return b1_bigit > b2_bigit ? 1 : -1;
+    }
+    if (i != j) return i > j ? 1 : -1;
+    return 0;
+  }
+
+  // Returns compare(lhs1 + lhs2, rhs).
+  friend FMT_CONSTEXPR auto add_compare(const bigint& lhs1, const bigint& lhs2,
+                                        const bigint& rhs) -> int {
+    int max_lhs_bigits = max_of(lhs1.num_bigits(), lhs2.num_bigits());
+    int num_rhs_bigits = rhs.num_bigits();
+    if (max_lhs_bigits + 1 < num_rhs_bigits) return -1;
+    if (max_lhs_bigits > num_rhs_bigits) return 1;
+    double_bigit borrow = 0;
+    int min_exp = min_of(min_of(lhs1.exp_, lhs2.exp_), rhs.exp_);
+    for (int i = num_rhs_bigits - 1; i >= min_exp; --i) {
+      double_bigit sum = double_bigit(lhs1.get_bigit(i)) + lhs2.get_bigit(i);
+      bigit rhs_bigit = rhs.get_bigit(i);
+      if (sum > rhs_bigit + borrow) return 1;
+      borrow = rhs_bigit + borrow - sum;
+      if (borrow > 1) return -1;
+      borrow <<= bigit_bits;
+    }
+    return borrow != 0 ? -1 : 0;
+  }
+
+  // Assigns pow(10, exp) to this bigint.
+  FMT_CONSTEXPR20 void assign_pow10(int exp) {
+    FMT_ASSERT(exp >= 0, "");
+    if (exp == 0) return *this = 1;
+    int bitmask = 1 << (num_bits<unsigned>() -
+                        countl_zero(static_cast<uint32_t>(exp)) - 1);
+    // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by
+    // repeated squaring and multiplication.
+    *this = 5;
+    bitmask >>= 1;
+    while (bitmask != 0) {
+      square();
+      if ((exp & bitmask) != 0) *this *= 5;
+      bitmask >>= 1;
+    }
+    *this <<= exp;  // Multiply by pow(2, exp) by shifting.
+  }
+
+  FMT_CONSTEXPR20 void square() {
+    int num_bigits = static_cast<int>(bigits_.size());
+    int num_result_bigits = 2 * num_bigits;
+    basic_memory_buffer<bigit, bigits_capacity> n(std::move(bigits_));
+    bigits_.resize(to_unsigned(num_result_bigits));
+    auto sum = uint128_t();
+    for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) {
+      // Compute bigit at position bigit_index of the result by adding
+      // cross-product terms n[i] * n[j] such that i + j == bigit_index.
+      for (int i = 0, j = bigit_index; j >= 0; ++i, --j) {
+        // Most terms are multiplied twice which can be optimized in the future.
+        sum += double_bigit(n[i]) * n[j];
+      }
+      bigits_[bigit_index] = static_cast<bigit>(sum);
+      sum >>= num_bits<bigit>();  // Compute the carry.
+    }
+    // Do the same for the top half.
+    for (int bigit_index = num_bigits; bigit_index < num_result_bigits;
+         ++bigit_index) {
+      for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;)
+        sum += double_bigit(n[i++]) * n[j--];
+      bigits_[bigit_index] = static_cast<bigit>(sum);
+      sum >>= num_bits<bigit>();
+    }
+    remove_leading_zeros();
+    exp_ *= 2;
+  }
+
+  // If this bigint has a bigger exponent than other, adds trailing zero to make
+  // exponents equal. This simplifies some operations such as subtraction.
+  FMT_CONSTEXPR void align(const bigint& other) {
+    int exp_difference = exp_ - other.exp_;
+    if (exp_difference <= 0) return;
+    int num_bigits = static_cast<int>(bigits_.size());
+    bigits_.resize(to_unsigned(num_bigits + exp_difference));
+    for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j)
+      bigits_[j] = bigits_[i];
+    fill_n(bigits_.data(), to_unsigned(exp_difference), 0U);
+    exp_ -= exp_difference;
+  }
+
+  // Divides this bignum by divisor, assigning the remainder to this and
+  // returning the quotient.
+  FMT_CONSTEXPR auto divmod_assign(const bigint& divisor) -> int {
+    FMT_ASSERT(this != &divisor, "");
+    if (compare(*this, divisor) < 0) return 0;
+    FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, "");
+    align(divisor);
+    int quotient = 0;
+    do {
+      subtract_aligned(divisor);
+      ++quotient;
+    } while (compare(*this, divisor) >= 0);
+    return quotient;
+  }
+};
+
+// format_dragon flags.
+enum dragon {
+  predecessor_closer = 1,
+  fixup = 2,  // Run fixup to correct exp10 which can be off by one.
+  fixed = 4,
+};
+
+// Formats a floating-point number using a variation of the Fixed-Precision
+// Positive Floating-Point Printout ((FPP)^2) algorithm by Steele & White:
+// https://fmt.dev/papers/p372-steele.pdf.
+FMT_CONSTEXPR20 inline void format_dragon(basic_fp<uint128_t> value,
+                                          unsigned flags, int num_digits,
+                                          buffer<char>& buf, int& exp10) {
+  bigint numerator;    // 2 * R in (FPP)^2.
+  bigint denominator;  // 2 * S in (FPP)^2.
+  // lower and upper are differences between value and corresponding boundaries.
+  bigint lower;             // (M^- in (FPP)^2).
+  bigint upper_store;       // upper's value if different from lower.
+  bigint* upper = nullptr;  // (M^+ in (FPP)^2).
+  // Shift numerator and denominator by an extra bit or two (if lower boundary
+  // is closer) to make lower and upper integers. This eliminates multiplication
+  // by 2 during later computations.
+  bool is_predecessor_closer = (flags & dragon::predecessor_closer) != 0;
+  int shift = is_predecessor_closer ? 2 : 1;
+  if (value.e >= 0) {
+    numerator = value.f;
+    numerator <<= value.e + shift;
+    lower = 1;
+    lower <<= value.e;
+    if (is_predecessor_closer) {
+      upper_store = 1;
+      upper_store <<= value.e + 1;
+      upper = &upper_store;
+    }
+    denominator.assign_pow10(exp10);
+    denominator <<= shift;
+  } else if (exp10 < 0) {
+    numerator.assign_pow10(-exp10);
+    lower.assign(numerator);
+    if (is_predecessor_closer) {
+      upper_store.assign(numerator);
+      upper_store <<= 1;
+      upper = &upper_store;
+    }
+    numerator *= value.f;
+    numerator <<= shift;
+    denominator = 1;
+    denominator <<= shift - value.e;
+  } else {
+    numerator = value.f;
+    numerator <<= shift;
+    denominator.assign_pow10(exp10);
+    denominator <<= shift - value.e;
+    lower = 1;
+    if (is_predecessor_closer) {
+      upper_store = 1ULL << 1;
+      upper = &upper_store;
+    }
+  }
+  int even = static_cast<int>((value.f & 1) == 0);
+  if (!upper) upper = &lower;
+  bool shortest = num_digits < 0;
+  if ((flags & dragon::fixup) != 0) {
+    if (add_compare(numerator, *upper, denominator) + even <= 0) {
+      --exp10;
+      numerator *= 10;
+      if (num_digits < 0) {
+        lower *= 10;
+        if (upper != &lower) *upper *= 10;
+      }
+    }
+    if ((flags & dragon::fixed) != 0) adjust_precision(num_digits, exp10 + 1);
+  }
+  // Invariant: value == (numerator / denominator) * pow(10, exp10).
+  if (shortest) {
+    // Generate the shortest representation.
+    num_digits = 0;
+    char* data = buf.data();
+    for (;;) {
+      int digit = numerator.divmod_assign(denominator);
+      bool low = compare(numerator, lower) - even < 0;  // numerator <[=] lower.
+      // numerator + upper >[=] pow10:
+      bool high = add_compare(numerator, *upper, denominator) + even > 0;
+      data[num_digits++] = static_cast<char>('0' + digit);
+      if (low || high) {
+        if (!low) {
+          ++data[num_digits - 1];
+        } else if (high) {
+          int result = add_compare(numerator, numerator, denominator);
+          // Round half to even.
+          if (result > 0 || (result == 0 && (digit % 2) != 0))
+            ++data[num_digits - 1];
+        }
+        buf.try_resize(to_unsigned(num_digits));
+        exp10 -= num_digits - 1;
+        return;
+      }
+      numerator *= 10;
+      lower *= 10;
+      if (upper != &lower) *upper *= 10;
+    }
+  }
+  // Generate the given number of digits.
+  exp10 -= num_digits - 1;
+  if (num_digits <= 0) {
+    auto digit = '0';
+    if (num_digits == 0) {
+      denominator *= 10;
+      digit = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0';
+    }
+    buf.push_back(digit);
+    return;
+  }
+  buf.try_resize(to_unsigned(num_digits));
+  for (int i = 0; i < num_digits - 1; ++i) {
+    int digit = numerator.divmod_assign(denominator);
+    buf[i] = static_cast<char>('0' + digit);
+    numerator *= 10;
+  }
+  int digit = numerator.divmod_assign(denominator);
+  auto result = add_compare(numerator, numerator, denominator);
+  if (result > 0 || (result == 0 && (digit % 2) != 0)) {
+    if (digit == 9) {
+      const auto overflow = '0' + 10;
+      buf[num_digits - 1] = overflow;
+      // Propagate the carry.
+      for (int i = num_digits - 1; i > 0 && buf[i] == overflow; --i) {
+        buf[i] = '0';
+        ++buf[i - 1];
+      }
+      if (buf[0] == overflow) {
+        buf[0] = '1';
+        if ((flags & dragon::fixed) != 0)
+          buf.push_back('0');
+        else
+          ++exp10;
+      }
+      return;
+    }
+    ++digit;
+  }
+  buf[num_digits - 1] = static_cast<char>('0' + digit);
+}
+
+// Formats a floating-point number using the hexfloat format.
+template <typename Float, FMT_ENABLE_IF(!is_double_double<Float>::value)>
+FMT_CONSTEXPR20 void format_hexfloat(Float value, format_specs specs,
+                                     buffer<char>& buf) {
+  // float is passed as double to reduce the number of instantiations and to
+  // simplify implementation.
+  static_assert(!std::is_same<Float, float>::value, "");
+
+  using info = dragonbox::float_info<Float>;
+
+  // Assume Float is in the format [sign][exponent][significand].
+  using carrier_uint = typename info::carrier_uint;
+
+  const auto num_float_significand_bits = detail::num_significand_bits<Float>();
+
+  basic_fp<carrier_uint> f(value);
+  f.e += num_float_significand_bits;
+  if (!has_implicit_bit<Float>()) --f.e;
+
+  const auto num_fraction_bits =
+      num_float_significand_bits + (has_implicit_bit<Float>() ? 1 : 0);
+  const auto num_xdigits = (num_fraction_bits + 3) / 4;
+
+  const auto leading_shift = ((num_xdigits - 1) * 4);
+  const auto leading_mask = carrier_uint(0xF) << leading_shift;
+  const auto leading_xdigit =
+      static_cast<uint32_t>((f.f & leading_mask) >> leading_shift);
+  if (leading_xdigit > 1) f.e -= (32 - countl_zero(leading_xdigit) - 1);
+
+  int print_xdigits = num_xdigits - 1;
+  if (specs.precision >= 0 && print_xdigits > specs.precision) {
+    const int shift = ((print_xdigits - specs.precision - 1) * 4);
+    const auto mask = carrier_uint(0xF) << shift;
+    const auto v = static_cast<uint32_t>((f.f & mask) >> shift);
+
+    if (v >= 8) {
+      const auto inc = carrier_uint(1) << (shift + 4);
+      f.f += inc;
+      f.f &= ~(inc - 1);
+    }
+
+    // Check long double overflow
+    if (!has_implicit_bit<Float>()) {
+      const auto implicit_bit = carrier_uint(1) << num_float_significand_bits;
+      if ((f.f & implicit_bit) == implicit_bit) {
+        f.f >>= 4;
+        f.e += 4;
+      }
+    }
+
+    print_xdigits = specs.precision;
+  }
+
+  char xdigits[num_bits<carrier_uint>() / 4];
+  detail::fill_n(xdigits, sizeof(xdigits), '0');
+  format_base2e(4, xdigits, f.f, num_xdigits, specs.upper());
+
+  // Remove zero tail
+  while (print_xdigits > 0 && xdigits[print_xdigits] == '0') --print_xdigits;
+
+  buf.push_back('0');
+  buf.push_back(specs.upper() ? 'X' : 'x');
+  buf.push_back(xdigits[0]);
+  if (specs.alt() || print_xdigits > 0 || print_xdigits < specs.precision)
+    buf.push_back('.');
+  buf.append(xdigits + 1, xdigits + 1 + print_xdigits);
+  for (; print_xdigits < specs.precision; ++print_xdigits) buf.push_back('0');
+
+  buf.push_back(specs.upper() ? 'P' : 'p');
+
+  uint32_t abs_e;
+  if (f.e < 0) {
+    buf.push_back('-');
+    abs_e = static_cast<uint32_t>(-f.e);
+  } else {
+    buf.push_back('+');
+    abs_e = static_cast<uint32_t>(f.e);
+  }
+  format_decimal<char>(appender(buf), abs_e, detail::count_digits(abs_e));
+}
+
+template <typename Float, FMT_ENABLE_IF(is_double_double<Float>::value)>
+FMT_CONSTEXPR20 void format_hexfloat(Float value, format_specs specs,
+                                     buffer<char>& buf) {
+  format_hexfloat(static_cast<double>(value), specs, buf);
+}
+
+constexpr auto fractional_part_rounding_thresholds(int index) -> uint32_t {
+  // For checking rounding thresholds.
+  // The kth entry is chosen to be the smallest integer such that the
+  // upper 32-bits of 10^(k+1) times it is strictly bigger than 5 * 10^k.
+  // It is equal to ceil(2^31 + 2^32/10^(k + 1)).
+  // These are stored in a string literal because we cannot have static arrays
+  // in constexpr functions and non-static ones are poorly optimized.
+  return U"\x9999999a\x828f5c29\x80418938\x80068db9\x8000a7c6\x800010c7"
+         U"\x800001ae\x8000002b"[index];
+}
+
+template <typename Float>
+FMT_CONSTEXPR20 auto format_float(Float value, int precision,
+                                  const format_specs& specs, bool binary32,
+                                  buffer<char>& buf) -> int {
+  // float is passed as double to reduce the number of instantiations.
+  static_assert(!std::is_same<Float, float>::value, "");
+  auto converted_value = convert_float(value);
+
+  const bool fixed = specs.type() == presentation_type::fixed;
+  if (value == 0) {
+    if (precision <= 0 || !fixed) {
+      buf.push_back('0');
+      return 0;
+    }
+    buf.try_resize(to_unsigned(precision));
+    fill_n(buf.data(), precision, '0');
+    return -precision;
+  }
+
+  int exp = 0;
+  bool use_dragon = true;
+  unsigned dragon_flags = 0;
+  if (!is_fast_float<Float>() || is_constant_evaluated()) {
+    const auto inv_log2_10 = 0.3010299956639812;  // 1 / log2(10)
+    using info = dragonbox::float_info<decltype(converted_value)>;
+    const auto f = basic_fp<typename info::carrier_uint>(converted_value);
+    // Compute exp, an approximate power of 10, such that
+    //   10^(exp - 1) <= value < 10^exp or 10^exp <= value < 10^(exp + 1).
+    // This is based on log10(value) == log2(value) / log2(10) and approximation
+    // of log2(value) by e + num_fraction_bits idea from double-conversion.
+    auto e = (f.e + count_digits<1>(f.f) - 1) * inv_log2_10 - 1e-10;
+    exp = static_cast<int>(e);
+    if (e > exp) ++exp;  // Compute ceil.
+    dragon_flags = dragon::fixup;
+  } else {
+    // Extract significand bits and exponent bits.
+    using info = dragonbox::float_info<double>;
+    auto br = bit_cast<uint64_t>(static_cast<double>(value));
+
+    const uint64_t significand_mask =
+        (static_cast<uint64_t>(1) << num_significand_bits<double>()) - 1;
+    uint64_t significand = (br & significand_mask);
+    int exponent = static_cast<int>((br & exponent_mask<double>()) >>
+                                    num_significand_bits<double>());
+
+    if (exponent != 0) {  // Check if normal.
+      exponent -= exponent_bias<double>() + num_significand_bits<double>();
+      significand |=
+          (static_cast<uint64_t>(1) << num_significand_bits<double>());
+      significand <<= 1;
+    } else {
+      // Normalize subnormal inputs.
+      FMT_ASSERT(significand != 0, "zeros should not appear here");
+      int shift = countl_zero(significand);
+      FMT_ASSERT(shift >= num_bits<uint64_t>() - num_significand_bits<double>(),
+                 "");
+      shift -= (num_bits<uint64_t>() - num_significand_bits<double>() - 2);
+      exponent = (std::numeric_limits<double>::min_exponent -
+                  num_significand_bits<double>()) -
+                 shift;
+      significand <<= shift;
+    }
+
+    // Compute the first several nonzero decimal significand digits.
+    // We call the number we get the first segment.
+    const int k = info::kappa - dragonbox::floor_log10_pow2(exponent);
+    exp = -k;
+    const int beta = exponent + dragonbox::floor_log2_pow10(k);
+    uint64_t first_segment;
+    bool has_more_segments;
+    int digits_in_the_first_segment;
+    {
+      const auto r = dragonbox::umul192_upper128(
+          significand << beta, dragonbox::get_cached_power(k));
+      first_segment = r.high();
+      has_more_segments = r.low() != 0;
+
+      // The first segment can have 18 ~ 19 digits.
+      if (first_segment >= 1000000000000000000ULL) {
+        digits_in_the_first_segment = 19;
+      } else {
+        // When it is of 18-digits, we align it to 19-digits by adding a bogus
+        // zero at the end.
+        digits_in_the_first_segment = 18;
+        first_segment *= 10;
+      }
+    }
+
+    // Compute the actual number of decimal digits to print.
+    if (fixed) adjust_precision(precision, exp + digits_in_the_first_segment);
+
+    // Use Dragon4 only when there might be not enough digits in the first
+    // segment.
+    if (digits_in_the_first_segment > precision) {
+      use_dragon = false;
+
+      if (precision <= 0) {
+        exp += digits_in_the_first_segment;
+
+        if (precision < 0) {
+          // Nothing to do, since all we have are just leading zeros.
+          buf.try_resize(0);
+        } else {
+          // We may need to round-up.
+          buf.try_resize(1);
+          if ((first_segment | static_cast<uint64_t>(has_more_segments)) >
+              5000000000000000000ULL) {
+            buf[0] = '1';
+          } else {
+            buf[0] = '0';
+          }
+        }
+      }  // precision <= 0
+      else {
+        exp += digits_in_the_first_segment - precision;
+
+        // When precision > 0, we divide the first segment into three
+        // subsegments, each with 9, 9, and 0 ~ 1 digits so that each fits
+        // in 32-bits which usually allows faster calculation than in
+        // 64-bits. Since some compiler (e.g. MSVC) doesn't know how to optimize
+        // division-by-constant for large 64-bit divisors, we do it here
+        // manually. The magic number 7922816251426433760 below is equal to
+        // ceil(2^(64+32) / 10^10).
+        const uint32_t first_subsegment = static_cast<uint32_t>(
+            dragonbox::umul128_upper64(first_segment, 7922816251426433760ULL) >>
+            32);
+        const uint64_t second_third_subsegments =
+            first_segment - first_subsegment * 10000000000ULL;
+
+        uint64_t prod;
+        uint32_t digits;
+        bool should_round_up;
+        int number_of_digits_to_print = min_of(precision, 9);
+
+        // Print a 9-digits subsegment, either the first or the second.
+        auto print_subsegment = [&](uint32_t subsegment, char* buffer) {
+          int number_of_digits_printed = 0;
+
+          // If we want to print an odd number of digits from the subsegment,
+          if ((number_of_digits_to_print & 1) != 0) {
+            // Convert to 64-bit fixed-point fractional form with 1-digit
+            // integer part. The magic number 720575941 is a good enough
+            // approximation of 2^(32 + 24) / 10^8; see
+            // https://jk-jeon.github.io/posts/2022/12/fixed-precision-formatting/#fixed-length-case
+            // for details.
+            prod = ((subsegment * static_cast<uint64_t>(720575941)) >> 24) + 1;
+            digits = static_cast<uint32_t>(prod >> 32);
+            *buffer = static_cast<char>('0' + digits);
+            number_of_digits_printed++;
+          }
+          // If we want to print an even number of digits from the
+          // first_subsegment,
+          else {
+            // Convert to 64-bit fixed-point fractional form with 2-digits
+            // integer part. The magic number 450359963 is a good enough
+            // approximation of 2^(32 + 20) / 10^7; see
+            // https://jk-jeon.github.io/posts/2022/12/fixed-precision-formatting/#fixed-length-case
+            // for details.
+            prod = ((subsegment * static_cast<uint64_t>(450359963)) >> 20) + 1;
+            digits = static_cast<uint32_t>(prod >> 32);
+            write2digits(buffer, digits);
+            number_of_digits_printed += 2;
+          }
+
+          // Print all digit pairs.
+          while (number_of_digits_printed < number_of_digits_to_print) {
+            prod = static_cast<uint32_t>(prod) * static_cast<uint64_t>(100);
+            digits = static_cast<uint32_t>(prod >> 32);
+            write2digits(buffer + number_of_digits_printed, digits);
+            number_of_digits_printed += 2;
+          }
+        };
+
+        // Print first subsegment.
+        print_subsegment(first_subsegment, buf.data());
+
+        // Perform rounding if the first subsegment is the last subsegment to
+        // print.
+        if (precision <= 9) {
+          // Rounding inside the subsegment.
+          // We round-up if:
+          //  - either the fractional part is strictly larger than 1/2, or
+          //  - the fractional part is exactly 1/2 and the last digit is odd.
+          // We rely on the following observations:
+          //  - If fractional_part >= threshold, then the fractional part is
+          //    strictly larger than 1/2.
+          //  - If the MSB of fractional_part is set, then the fractional part
+          //    must be at least 1/2.
+          //  - When the MSB of fractional_part is set, either
+          //    second_third_subsegments being nonzero or has_more_segments
+          //    being true means there are further digits not printed, so the
+          //    fractional part is strictly larger than 1/2.
+          if (precision < 9) {
+            uint32_t fractional_part = static_cast<uint32_t>(prod);
+            should_round_up =
+                fractional_part >= fractional_part_rounding_thresholds(
+                                       8 - number_of_digits_to_print) ||
+                ((fractional_part >> 31) &
+                 ((digits & 1) | (second_third_subsegments != 0) |
+                  has_more_segments)) != 0;
+          }
+          // Rounding at the subsegment boundary.
+          // In this case, the fractional part is at least 1/2 if and only if
+          // second_third_subsegments >= 5000000000ULL, and is strictly larger
+          // than 1/2 if we further have either second_third_subsegments >
+          // 5000000000ULL or has_more_segments == true.
+          else {
+            should_round_up = second_third_subsegments > 5000000000ULL ||
+                              (second_third_subsegments == 5000000000ULL &&
+                               ((digits & 1) != 0 || has_more_segments));
+          }
+        }
+        // Otherwise, print the second subsegment.
+        else {
+          // Compilers are not aware of how to leverage the maximum value of
+          // second_third_subsegments to find out a better magic number which
+          // allows us to eliminate an additional shift. 1844674407370955162 =
+          // ceil(2^64/10) < ceil(2^64*(10^9/(10^10 - 1))).
+          const uint32_t second_subsegment =
+              static_cast<uint32_t>(dragonbox::umul128_upper64(
+                  second_third_subsegments, 1844674407370955162ULL));
+          const uint32_t third_subsegment =
+              static_cast<uint32_t>(second_third_subsegments) -
+              second_subsegment * 10;
+
+          number_of_digits_to_print = precision - 9;
+          print_subsegment(second_subsegment, buf.data() + 9);
+
+          // Rounding inside the subsegment.
+          if (precision < 18) {
+            // The condition third_subsegment != 0 implies that the segment was
+            // of 19 digits, so in this case the third segment should be
+            // consisting of a genuine digit from the input.
+            uint32_t fractional_part = static_cast<uint32_t>(prod);
+            should_round_up =
+                fractional_part >= fractional_part_rounding_thresholds(
+                                       8 - number_of_digits_to_print) ||
+                ((fractional_part >> 31) &
+                 ((digits & 1) | (third_subsegment != 0) |
+                  has_more_segments)) != 0;
+          }
+          // Rounding at the subsegment boundary.
+          else {
+            // In this case, the segment must be of 19 digits, thus
+            // the third subsegment should be consisting of a genuine digit from
+            // the input.
+            should_round_up = third_subsegment > 5 ||
+                              (third_subsegment == 5 &&
+                               ((digits & 1) != 0 || has_more_segments));
+          }
+        }
+
+        // Round-up if necessary.
+        if (should_round_up) {
+          ++buf[precision - 1];
+          for (int i = precision - 1; i > 0 && buf[i] > '9'; --i) {
+            buf[i] = '0';
+            ++buf[i - 1];
+          }
+          if (buf[0] > '9') {
+            buf[0] = '1';
+            if (fixed)
+              buf[precision++] = '0';
+            else
+              ++exp;
+          }
+        }
+        buf.try_resize(to_unsigned(precision));
+      }
+    }  // if (digits_in_the_first_segment > precision)
+    else {
+      // Adjust the exponent for its use in Dragon4.
+      exp += digits_in_the_first_segment - 1;
+    }
+  }
+  if (use_dragon) {
+    auto f = basic_fp<uint128_t>();
+    bool is_predecessor_closer = binary32 ? f.assign(static_cast<float>(value))
+                                          : f.assign(converted_value);
+    if (is_predecessor_closer) dragon_flags |= dragon::predecessor_closer;
+    if (fixed) dragon_flags |= dragon::fixed;
+    // Limit precision to the maximum possible number of significant digits in
+    // an IEEE754 double because we don't need to generate zeros.
+    const int max_double_digits = 767;
+    if (precision > max_double_digits) precision = max_double_digits;
+    format_dragon(f, dragon_flags, precision, buf, exp);
+  }
+  if (!fixed && !specs.alt()) {
+    // Remove trailing zeros.
+    auto num_digits = buf.size();
+    while (num_digits > 0 && buf[num_digits - 1] == '0') {
+      --num_digits;
+      ++exp;
+    }
+    buf.try_resize(num_digits);
+  }
+  return exp;
+}
+
+template <typename Char, typename OutputIt, typename T,
+          FMT_ENABLE_IF(is_floating_point<T>::value)>
+FMT_CONSTEXPR20 auto write(OutputIt out, T value, format_specs specs,
+                           locale_ref loc = {}) -> OutputIt {
+  if (specs.localized() && write_loc(out, value, specs, loc)) return out;
+
+  // Use signbit because value < 0 is false for NaN.
+  sign s = detail::signbit(value) ? sign::minus : specs.sign();
+
+  if (!detail::isfinite(value))
+    return write_nonfinite<Char>(out, detail::isnan(value), specs, s);
+
+  if (specs.align() == align::numeric && s != sign::none) {
+    *out++ = detail::getsign<Char>(s);
+    s = sign::none;
+    if (specs.width != 0) --specs.width;
+  }
+
+  const int exp_upper = detail::exp_upper<T>();
+  int precision = specs.precision;
+  if (precision < 0) {
+    if (specs.type() != presentation_type::none) {
+      precision = 6;
+    } else if (is_fast_float<T>::value && !is_constant_evaluated()) {
+      // Use Dragonbox for the shortest format.
+      auto dec = dragonbox::to_decimal(static_cast<fast_float_t<T>>(value));
+      return write_float<Char>(out, dec, specs, s, exp_upper, loc);
+    }
+  }
+
+  memory_buffer buffer;
+  if (specs.type() == presentation_type::hexfloat) {
+    if (s != sign::none) buffer.push_back(detail::getsign<char>(s));
+    format_hexfloat(convert_float(value), specs, buffer);
+    return write_bytes<Char, align::right>(out, {buffer.data(), buffer.size()},
+                                           specs);
+  }
+
+  if (specs.type() == presentation_type::exp) {
+    if (precision == max_value<int>())
+      report_error("number is too big");
+    else
+      ++precision;
+    if (specs.precision != 0) specs.set_alt();
+  } else if (specs.type() == presentation_type::fixed) {
+    if (specs.precision != 0) specs.set_alt();
+  } else if (precision == 0) {
+    precision = 1;
+  }
+  int exp = format_float(convert_float(value), precision, specs,
+                         std::is_same<T, float>(), buffer);
+
+  specs.precision = precision;
+  auto f = big_decimal_fp{buffer.data(), static_cast<int>(buffer.size()), exp};
+  return write_float<Char>(out, f, specs, s, exp_upper, loc);
+}
+
+template <typename Char, typename OutputIt, typename T,
+          FMT_ENABLE_IF(is_fast_float<T>::value)>
+FMT_CONSTEXPR20 auto write(OutputIt out, T value) -> OutputIt {
+  if (is_constant_evaluated()) return write<Char>(out, value, format_specs());
+
+  auto s = detail::signbit(value) ? sign::minus : sign::none;
+  auto mask = exponent_mask<fast_float_t<T>>();
+  if ((bit_cast<decltype(mask)>(value) & mask) == mask)
+    return write_nonfinite<Char>(out, std::isnan(value), {}, s);
+
+  auto dec = dragonbox::to_decimal(static_cast<fast_float_t<T>>(value));
+  auto significand = dec.significand;
+  int significand_size = count_digits(significand);
+  int exponent = dec.exponent + significand_size - 1;
+  if (use_fixed(exponent, detail::exp_upper<T>())) {
+    return write_fixed<Char, fallback_digit_grouping<Char>>(
+        out, dec, significand_size, Char('.'), {}, s);
+  }
+
+  // Write value in the exponential format.
+  const char* prefix = "e+";
+  int abs_exponent = exponent;
+  if (exponent < 0) {
+    abs_exponent = -exponent;
+    prefix = "e-";
+  }
+  auto has_decimal_point = significand_size != 1;
+  size_t size = std::is_pointer<OutputIt>::value
+                    ? 0u
+                    : to_unsigned((s != sign::none ? 1 : 0) + significand_size +
+                                  (has_decimal_point ? 1 : 0) +
+                                  (abs_exponent >= 100 ? 5 : 4));
+  if (auto ptr = to_pointer<Char>(out, size)) {
+    if (s != sign::none) *ptr++ = Char('-');
+    if (has_decimal_point) {
+      auto begin = ptr;
+      ptr = format_decimal<Char>(ptr, significand, significand_size + 1);
+      *begin = begin[1];
+      begin[1] = '.';
+    } else {
+      *ptr++ = static_cast<Char>('0' + significand);
+    }
+    if (std::is_same<Char, char>::value) {
+      memcpy(ptr, prefix, 2);
+      ptr += 2;
+    } else {
+      *ptr++ = prefix[0];
+      *ptr++ = prefix[1];
+    }
+    if (abs_exponent >= 100) {
+      *ptr++ = static_cast<Char>('0' + abs_exponent / 100);
+      abs_exponent %= 100;
+    }
+    write2digits(ptr, static_cast<unsigned>(abs_exponent));
+    return select<std::is_pointer<OutputIt>::value>(ptr + 2, out);
+  }
+  auto it = reserve(out, size);
+  if (s != sign::none) *it++ = Char('-');
+  // Insert a decimal point after the first digit and add an exponent.
+  it = write_significand(it, significand, significand_size, 1,
+                         has_decimal_point ? Char('.') : Char());
+  *it++ = Char('e');
+  it = write_exponent<Char>(exponent, it);
+  return base_iterator(out, it);
+}
+
+template <typename Char, typename OutputIt, typename T,
+          FMT_ENABLE_IF(is_floating_point<T>::value &&
+                        !is_fast_float<T>::value)>
+inline auto write(OutputIt out, T value) -> OutputIt {
+  return write<Char>(out, value, {});
+}
+
+template <typename Char, typename OutputIt>
+auto write(OutputIt out, monostate, format_specs = {}, locale_ref = {})
+    -> OutputIt {
+  FMT_ASSERT(false, "");
+  return out;
+}
+
+template <typename Char, typename OutputIt>
+FMT_CONSTEXPR auto write(OutputIt out, basic_string_view<Char> value)
+    -> OutputIt {
+  return copy_noinline<Char>(value.begin(), value.end(), out);
+}
+
+template <typename Char, typename OutputIt, typename T,
+          FMT_ENABLE_IF(has_to_string_view<T>::value)>
+constexpr auto write(OutputIt out, const T& value) -> OutputIt {
+  return write<Char>(out, to_string_view(value));
+}
+
+// FMT_ENABLE_IF() condition separated to workaround an MSVC bug.
+template <
+    typename Char, typename OutputIt, typename T,
+    bool check = std::is_enum<T>::value && !std::is_same<T, Char>::value &&
+                 mapped_type_constant<T, Char>::value != type::custom_type,
+    FMT_ENABLE_IF(check)>
+FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt {
+  return write<Char>(out, static_cast<underlying_t<T>>(value));
+}
+
+template <typename Char, typename OutputIt, typename T,
+          FMT_ENABLE_IF(std::is_same<T, bool>::value)>
+FMT_CONSTEXPR auto write(OutputIt out, T value, const format_specs& specs = {},
+                         locale_ref = {}) -> OutputIt {
+  return specs.type() != presentation_type::none &&
+                 specs.type() != presentation_type::string
+             ? write<Char>(out, value ? 1 : 0, specs, {})
+             : write_bytes<Char>(out, value ? "true" : "false", specs);
+}
+
+template <typename Char, typename OutputIt>
+FMT_CONSTEXPR auto write(OutputIt out, Char value) -> OutputIt {
+  auto it = reserve(out, 1);
+  *it++ = value;
+  return base_iterator(out, it);
+}
+
+template <typename Char, typename OutputIt>
+FMT_CONSTEXPR20 auto write(OutputIt out, const Char* value) -> OutputIt {
+  if (value) return write(out, basic_string_view<Char>(value));
+  report_error("string pointer is null");
+  return out;
+}
+
+template <typename Char, typename OutputIt, typename T,
+          FMT_ENABLE_IF(std::is_same<T, void>::value)>
+auto write(OutputIt out, const T* value, const format_specs& specs = {},
+           locale_ref = {}) -> OutputIt {
+  return write_ptr<Char>(out, bit_cast<uintptr_t>(value), &specs);
+}
+
+template <typename Char, typename OutputIt, typename T,
+          FMT_ENABLE_IF(mapped_type_constant<T, Char>::value ==
+                            type::custom_type &&
+                        !std::is_fundamental<T>::value)>
+FMT_CONSTEXPR auto write(OutputIt out, const T& value) -> OutputIt {
+  auto f = formatter<T, Char>();
+  auto parse_ctx = parse_context<Char>({});
+  f.parse(parse_ctx);
+  auto ctx = basic_format_context<OutputIt, Char>(out, {}, {});
+  return f.format(value, ctx);
+}
+
+template <typename T>
+using is_builtin =
+    bool_constant<std::is_same<T, int>::value || FMT_BUILTIN_TYPES>;
+
+// An argument visitor that formats the argument and writes it via the output
+// iterator. It's a class and not a generic lambda for compatibility with C++11.
+template <typename Char> struct default_arg_formatter {
+  using context = buffered_context<Char>;
+
+  basic_appender<Char> out;
+
+  void operator()(monostate) { report_error("argument not found"); }
+
+  template <typename T, FMT_ENABLE_IF(is_builtin<T>::value)>
+  void operator()(T value) {
+    write<Char>(out, value);
+  }
+
+  template <typename T, FMT_ENABLE_IF(!is_builtin<T>::value)>
+  void operator()(T) {
+    FMT_ASSERT(false, "");
+  }
+
+  void operator()(typename basic_format_arg<context>::handle h) {
+    // Use a null locale since the default format must be unlocalized.
+    auto parse_ctx = parse_context<Char>({});
+    auto format_ctx = context(out, {}, {});
+    h.format(parse_ctx, format_ctx);
+  }
+};
+
+template <typename Char> struct arg_formatter {
+  basic_appender<Char> out;
+  const format_specs& specs;
+  FMT_NO_UNIQUE_ADDRESS locale_ref locale;
+
+  template <typename T, FMT_ENABLE_IF(is_builtin<T>::value)>
+  FMT_CONSTEXPR FMT_INLINE void operator()(T value) {
+    detail::write<Char>(out, value, specs, locale);
+  }
+
+  template <typename T, FMT_ENABLE_IF(!is_builtin<T>::value)>
+  void operator()(T) {
+    FMT_ASSERT(false, "");
+  }
+
+  void operator()(typename basic_format_arg<buffered_context<Char>>::handle) {
+    // User-defined types are handled separately because they require access
+    // to the parse context.
+  }
+};
+
+struct dynamic_spec_getter {
+  template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
+  FMT_CONSTEXPR auto operator()(T value) -> unsigned long long {
+    return is_negative(value) ? ~0ull : static_cast<unsigned long long>(value);
+  }
+
+  template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
+  FMT_CONSTEXPR auto operator()(T) -> unsigned long long {
+    report_error("width/precision is not integer");
+    return 0;
+  }
+};
+
+template <typename Context>
+FMT_CONSTEXPR void handle_dynamic_spec(
+    arg_id_kind kind, int& value,
+    const arg_ref<typename Context::char_type>& ref, Context& ctx) {
+  if (kind == arg_id_kind::none) return;
+  auto arg =
+      kind == arg_id_kind::index ? ctx.arg(ref.index) : ctx.arg(ref.name);
+  if (!arg) report_error("argument not found");
+  unsigned long long result = arg.visit(dynamic_spec_getter());
+  if (result > to_unsigned(max_value<int>()))
+    report_error("width/precision is out of range");
+  value = static_cast<int>(result);
+}
+
+#if FMT_USE_NONTYPE_TEMPLATE_ARGS
+template <typename T, typename Char, size_t N,
+          fmt::detail::fixed_string<Char, N> Str>
+struct static_named_arg : view {
+  static constexpr auto name = Str.data;
+
+  const T& value;
+  static_named_arg(const T& v) : value(v) {}
+};
+
+template <typename T, typename Char, size_t N,
+          fmt::detail::fixed_string<Char, N> Str>
+struct is_named_arg<static_named_arg<T, Char, N, Str>> : std::true_type {};
+
+template <typename T, typename Char, size_t N,
+          fmt::detail::fixed_string<Char, N> Str>
+struct is_static_named_arg<static_named_arg<T, Char, N, Str>> : std::true_type {
+};
+
+template <typename Char, size_t N, fmt::detail::fixed_string<Char, N> Str>
+struct udl_arg {
+  template <typename T> auto operator=(T&& value) const {
+    return static_named_arg<T, Char, N, Str>(std::forward<T>(value));
+  }
+};
+#else
+template <typename Char> struct udl_arg {
+  const Char* str;
+
+  template <typename T> auto operator=(T&& value) const -> named_arg<Char, T> {
+    return {str, std::forward<T>(value)};
+  }
+};
+#endif  // FMT_USE_NONTYPE_TEMPLATE_ARGS
+
+template <typename Char = char> struct format_handler {
+  parse_context<Char> parse_ctx;
+  buffered_context<Char> ctx;
+
+  void on_text(const Char* begin, const Char* end) {
+    copy_noinline<Char>(begin, end, ctx.out());
+  }
+
+  FMT_CONSTEXPR auto on_arg_id() -> int { return parse_ctx.next_arg_id(); }
+  FMT_CONSTEXPR auto on_arg_id(int id) -> int {
+    parse_ctx.check_arg_id(id);
+    return id;
+  }
+  FMT_CONSTEXPR auto on_arg_id(basic_string_view<Char> id) -> int {
+    parse_ctx.check_arg_id(id);
+    int arg_id = ctx.arg_id(id);
+    if (arg_id < 0) report_error("argument not found");
+    return arg_id;
+  }
+
+  FMT_INLINE void on_replacement_field(int id, const Char*) {
+    ctx.arg(id).visit(default_arg_formatter<Char>{ctx.out()});
+  }
+
+  auto on_format_specs(int id, const Char* begin, const Char* end)
+      -> const Char* {
+    auto arg = ctx.arg(id);
+    if (!arg) report_error("argument not found");
+    // Not using a visitor for custom types gives better codegen.
+    if (arg.format_custom(begin, parse_ctx, ctx)) return parse_ctx.begin();
+
+    auto specs = dynamic_format_specs<Char>();
+    begin = parse_format_specs(begin, end, specs, parse_ctx, arg.type());
+    if (specs.dynamic()) {
+      handle_dynamic_spec(specs.dynamic_width(), specs.width, specs.width_ref,
+                          ctx);
+      handle_dynamic_spec(specs.dynamic_precision(), specs.precision,
+                          specs.precision_ref, ctx);
+    }
+
+    arg.visit(arg_formatter<Char>{ctx.out(), specs, ctx.locale()});
+    return begin;
+  }
+
+  FMT_NORETURN void on_error(const char* message) { report_error(message); }
+};
+
+// It is used in format-inl.h and os.cc.
+using format_func = void (*)(detail::buffer<char>&, int, const char*);
+FMT_API void do_report_error(format_func func, int error_code,
+                             const char* message) noexcept;
+
+FMT_API void format_error_code(buffer<char>& out, int error_code,
+                               string_view message) noexcept;
+
+template <typename T, typename Char, type TYPE>
+template <typename FormatContext>
+FMT_CONSTEXPR auto native_formatter<T, Char, TYPE>::format(
+    const T& val, FormatContext& ctx) const -> decltype(ctx.out()) {
+  if (!specs_.dynamic())
+    return write<Char>(ctx.out(), val, specs_, ctx.locale());
+  auto specs = format_specs(specs_);
+  handle_dynamic_spec(specs.dynamic_width(), specs.width, specs_.width_ref,
+                      ctx);
+  handle_dynamic_spec(specs.dynamic_precision(), specs.precision,
+                      specs_.precision_ref, ctx);
+  return write<Char>(ctx.out(), val, specs, ctx.locale());
+}
+}  // namespace detail
+
+FMT_BEGIN_EXPORT
+
+// A generic formatting context with custom output iterator and character
+// (code unit) support. Char is the format string code unit type which can be
+// different from OutputIt::value_type.
+template <typename OutputIt, typename Char> class generic_context {
+ private:
+  OutputIt out_;
+  basic_format_args<generic_context> args_;
+  locale_ref loc_;
+
+ public:
+  using char_type = Char;
+  using iterator = OutputIt;
+  enum { builtin_types = FMT_BUILTIN_TYPES };
+
+  constexpr generic_context(OutputIt out,
+                            basic_format_args<generic_context> args,
+                            locale_ref loc = {})
+      : out_(out), args_(args), loc_(loc) {}
+  generic_context(generic_context&&) = default;
+  generic_context(const generic_context&) = delete;
+  void operator=(const generic_context&) = delete;
+
+  constexpr auto arg(int id) const -> basic_format_arg<generic_context> {
+    return args_.get(id);
+  }
+  auto arg(basic_string_view<Char> name) const
+      -> basic_format_arg<generic_context> {
+    return args_.get(name);
+  }
+  constexpr auto arg_id(basic_string_view<Char> name) const -> int {
+    return args_.get_id(name);
+  }
+
+  constexpr auto out() const -> iterator { return out_; }
+
+  void advance_to(iterator it) {
+    if (!detail::is_back_insert_iterator<iterator>()) out_ = it;
+  }
+
+  constexpr auto locale() const -> locale_ref { return loc_; }
+};
+
+class loc_value {
+ private:
+  basic_format_arg<context> value_;
+
+ public:
+  template <typename T, FMT_ENABLE_IF(!detail::is_float128<T>::value)>
+  loc_value(T value) : value_(value) {}
+
+  template <typename T, FMT_ENABLE_IF(detail::is_float128<T>::value)>
+  loc_value(T) {}
+
+  template <typename Visitor> auto visit(Visitor&& vis) -> decltype(vis(0)) {
+    return value_.visit(vis);
+  }
+};
+
+// A locale facet that formats values in UTF-8.
+// It is parameterized on the locale to avoid the heavy <locale> include.
+template <typename Locale> class format_facet : public Locale::facet {
+ private:
+  std::string separator_;
+  std::string grouping_;
+  std::string decimal_point_;
+
+ protected:
+  virtual auto do_put(appender out, loc_value val,
+                      const format_specs& specs) const -> bool;
+
+ public:
+  static FMT_API typename Locale::id id;
+
+  explicit format_facet(Locale& loc);
+  explicit format_facet(string_view sep = "", std::string grouping = "\3",
+                        std::string decimal_point = ".")
+      : separator_(sep.data(), sep.size()),
+        grouping_(grouping),
+        decimal_point_(decimal_point) {}
+
+  auto put(appender out, loc_value val, const format_specs& specs) const
+      -> bool {
+    return do_put(out, val, specs);
+  }
+};
+
+#define FMT_FORMAT_AS(Type, Base)                                   \
+  template <typename Char>                                          \
+  struct formatter<Type, Char> : formatter<Base, Char> {            \
+    template <typename FormatContext>                               \
+    FMT_CONSTEXPR auto format(Type value, FormatContext& ctx) const \
+        -> decltype(ctx.out()) {                                    \
+      return formatter<Base, Char>::format(value, ctx);             \
+    }                                                               \
+  }
+
+FMT_FORMAT_AS(signed char, int);
+FMT_FORMAT_AS(unsigned char, unsigned);
+FMT_FORMAT_AS(short, int);
+FMT_FORMAT_AS(unsigned short, unsigned);
+FMT_FORMAT_AS(long, detail::long_type);
+FMT_FORMAT_AS(unsigned long, detail::ulong_type);
+FMT_FORMAT_AS(Char*, const Char*);
+FMT_FORMAT_AS(detail::std_string_view<Char>, basic_string_view<Char>);
+FMT_FORMAT_AS(std::nullptr_t, const void*);
+FMT_FORMAT_AS(void*, const void*);
+
+template <typename Char, size_t N>
+struct formatter<Char[N], Char> : formatter<basic_string_view<Char>, Char> {};
+
+template <typename Char, typename Traits, typename Allocator>
+class formatter<std::basic_string<Char, Traits, Allocator>, Char>
+    : public formatter<basic_string_view<Char>, Char> {};
+
+template <int N, typename Char>
+struct formatter<detail::bitint<N>, Char> : formatter<long long, Char> {};
+template <int N, typename Char>
+struct formatter<detail::ubitint<N>, Char>
+    : formatter<unsigned long long, Char> {};
+
+template <typename Char>
+struct formatter<detail::float128, Char>
+    : detail::native_formatter<detail::float128, Char,
+                               detail::type::float_type> {};
+
+template <typename T, typename Char>
+struct formatter<T, Char, void_t<detail::format_as_result<T>>>
+    : formatter<detail::format_as_result<T>, Char> {
+  template <typename FormatContext>
+  FMT_CONSTEXPR auto format(const T& value, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    auto&& val = format_as(value);  // Make an lvalue reference for format.
+    return formatter<detail::format_as_result<T>, Char>::format(val, ctx);
+  }
+};
+
+/**
+ * Converts `p` to `const void*` for pointer formatting.
+ *
+ * **Example**:
+ *
+ *     auto s = fmt::format("{}", fmt::ptr(p));
+ */
+template <typename T> auto ptr(T p) -> const void* {
+  static_assert(std::is_pointer<T>::value, "fmt::ptr used with non-pointer");
+  return detail::bit_cast<const void*>(p);
+}
+
+/**
+ * Converts `e` to the underlying type.
+ *
+ * **Example**:
+ *
+ *     enum class color { red, green, blue };
+ *     auto s = fmt::format("{}", fmt::underlying(color::red));  // s == "0"
+ */
+template <typename Enum>
+constexpr auto underlying(Enum e) noexcept -> underlying_t<Enum> {
+  return static_cast<underlying_t<Enum>>(e);
+}
+
+namespace enums {
+template <typename Enum, FMT_ENABLE_IF(std::is_enum<Enum>::value)>
+constexpr auto format_as(Enum e) noexcept -> underlying_t<Enum> {
+  return static_cast<underlying_t<Enum>>(e);
+}
+}  // namespace enums
+
+#ifdef __cpp_lib_byte
+template <typename Char>
+struct formatter<std::byte, Char> : formatter<unsigned, Char> {
+  static auto format_as(std::byte b) -> unsigned char {
+    return static_cast<unsigned char>(b);
+  }
+  template <typename Context>
+  auto format(std::byte b, Context& ctx) const -> decltype(ctx.out()) {
+    return formatter<unsigned, Char>::format(format_as(b), ctx);
+  }
+};
+#endif
+
+struct bytes {
+  string_view data;
+
+  inline explicit bytes(string_view s) : data(s) {}
+};
+
+template <> struct formatter<bytes> {
+ private:
+  detail::dynamic_format_specs<> specs_;
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* {
+    return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx,
+                              detail::type::string_type);
+  }
+
+  template <typename FormatContext>
+  auto format(bytes b, FormatContext& ctx) const -> decltype(ctx.out()) {
+    auto specs = specs_;
+    detail::handle_dynamic_spec(specs.dynamic_width(), specs.width,
+                                specs.width_ref, ctx);
+    detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision,
+                                specs.precision_ref, ctx);
+    return detail::write_bytes<char>(ctx.out(), b.data, specs);
+  }
+};
+
+// group_digits_view is not derived from view because it copies the argument.
+template <typename T> struct group_digits_view {
+  T value;
+};
+
+/**
+ * Returns a view that formats an integer value using ',' as a
+ * locale-independent thousands separator.
+ *
+ * **Example**:
+ *
+ *     fmt::print("{}", fmt::group_digits(12345));
+ *     // Output: "12,345"
+ */
+template <typename T> auto group_digits(T value) -> group_digits_view<T> {
+  return {value};
+}
+
+template <typename T> struct formatter<group_digits_view<T>> : formatter<T> {
+ private:
+  detail::dynamic_format_specs<> specs_;
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* {
+    return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx,
+                              detail::type::int_type);
+  }
+
+  template <typename FormatContext>
+  auto format(group_digits_view<T> view, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    auto specs = specs_;
+    detail::handle_dynamic_spec(specs.dynamic_width(), specs.width,
+                                specs.width_ref, ctx);
+    detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision,
+                                specs.precision_ref, ctx);
+    auto arg = detail::make_write_int_arg(view.value, specs.sign());
+    return detail::write_int(
+        ctx.out(), static_cast<detail::uint64_or_128_t<T>>(arg.abs_value),
+        arg.prefix, specs, detail::digit_grouping<char>("\3", ","));
+  }
+};
+
+template <typename T, typename Char> struct nested_view {
+  const formatter<T, Char>* fmt;
+  const T* value;
+};
+
+template <typename T, typename Char>
+struct formatter<nested_view<T, Char>, Char> {
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    return ctx.begin();
+  }
+  template <typename FormatContext>
+  auto format(nested_view<T, Char> view, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    return view.fmt->format(*view.value, ctx);
+  }
+};
+
+template <typename T, typename Char = char> struct nested_formatter {
+ private:
+  basic_specs specs_;
+  int width_;
+  formatter<T, Char> formatter_;
+
+ public:
+  constexpr nested_formatter() : width_(0) {}
+
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    auto it = ctx.begin(), end = ctx.end();
+    if (it == end) return it;
+    auto specs = format_specs();
+    it = detail::parse_align(it, end, specs);
+    specs_ = specs;
+    Char c = *it;
+    auto width_ref = detail::arg_ref<Char>();
+    if ((c >= '0' && c <= '9') || c == '{') {
+      it = detail::parse_width(it, end, specs, width_ref, ctx);
+      width_ = specs.width;
+    }
+    ctx.advance_to(it);
+    return formatter_.parse(ctx);
+  }
+
+  template <typename FormatContext, typename F>
+  auto write_padded(FormatContext& ctx, F write) const -> decltype(ctx.out()) {
+    if (width_ == 0) return write(ctx.out());
+    auto buf = basic_memory_buffer<Char>();
+    write(basic_appender<Char>(buf));
+    auto specs = format_specs();
+    specs.width = width_;
+    specs.copy_fill_from(specs_);
+    specs.set_align(specs_.align());
+    return detail::write<Char>(
+        ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs);
+  }
+
+  auto nested(const T& value) const -> nested_view<T, Char> {
+    return nested_view<T, Char>{&formatter_, &value};
+  }
+};
+
+inline namespace literals {
+#if FMT_USE_NONTYPE_TEMPLATE_ARGS
+template <detail::fixed_string S> constexpr auto operator""_a() {
+  using char_t = remove_cvref_t<decltype(*S.data)>;
+  return detail::udl_arg<char_t, sizeof(S.data) / sizeof(char_t), S>();
+}
+#else
+/**
+ * User-defined literal equivalent of `fmt::arg`.
+ *
+ * **Example**:
+ *
+ *     using namespace fmt::literals;
+ *     fmt::print("The answer is {answer}.", "answer"_a=42);
+ */
+constexpr auto operator""_a(const char* s, size_t) -> detail::udl_arg<char> {
+  return {s};
+}
+#endif  // FMT_USE_NONTYPE_TEMPLATE_ARGS
+}  // namespace literals
+
+/// A fast integer formatter.
+class format_int {
+ private:
+  // Buffer should be large enough to hold all digits (digits10 + 1),
+  // a sign and a null character.
+  enum { buffer_size = std::numeric_limits<unsigned long long>::digits10 + 3 };
+  mutable char buffer_[buffer_size];
+  char* str_;
+
+  template <typename UInt>
+  FMT_CONSTEXPR20 auto format_unsigned(UInt value) -> char* {
+    auto n = static_cast<detail::uint32_or_64_or_128_t<UInt>>(value);
+    return detail::do_format_decimal(buffer_, n, buffer_size - 1);
+  }
+
+  template <typename Int>
+  FMT_CONSTEXPR20 auto format_signed(Int value) -> char* {
+    auto abs_value = static_cast<detail::uint32_or_64_or_128_t<Int>>(value);
+    bool negative = value < 0;
+    if (negative) abs_value = 0 - abs_value;
+    auto begin = format_unsigned(abs_value);
+    if (negative) *--begin = '-';
+    return begin;
+  }
+
+ public:
+  FMT_CONSTEXPR20 explicit format_int(int value) : str_(format_signed(value)) {}
+  FMT_CONSTEXPR20 explicit format_int(long value)
+      : str_(format_signed(value)) {}
+  FMT_CONSTEXPR20 explicit format_int(long long value)
+      : str_(format_signed(value)) {}
+  FMT_CONSTEXPR20 explicit format_int(unsigned value)
+      : str_(format_unsigned(value)) {}
+  FMT_CONSTEXPR20 explicit format_int(unsigned long value)
+      : str_(format_unsigned(value)) {}
+  FMT_CONSTEXPR20 explicit format_int(unsigned long long value)
+      : str_(format_unsigned(value)) {}
+
+  /// Returns the number of characters written to the output buffer.
+  FMT_CONSTEXPR20 auto size() const -> size_t {
+    return detail::to_unsigned(buffer_ - str_ + buffer_size - 1);
+  }
+
+  /// Returns a pointer to the output buffer content. No terminating null
+  /// character is appended.
+  FMT_CONSTEXPR20 auto data() const -> const char* { return str_; }
+
+  /// Returns a pointer to the output buffer content with terminating null
+  /// character appended.
+  FMT_CONSTEXPR20 auto c_str() const -> const char* {
+    buffer_[buffer_size - 1] = '\0';
+    return str_;
+  }
+
+  /// Returns the content of the output buffer as an `std::string`.
+  inline auto str() const -> std::string { return {str_, size()}; }
+};
+
+#if FMT_CLANG_ANALYZER
+#  define FMT_STRING_IMPL(s, base) s
+#else
+#  define FMT_STRING_IMPL(s, base)                                           \
+    [] {                                                                     \
+      /* Use the hidden visibility as a workaround for a GCC bug (#1973). */ \
+      /* Use a macro-like name to avoid shadowing warnings. */               \
+      struct FMT_VISIBILITY("hidden") FMT_COMPILE_STRING : base {            \
+        using char_type = fmt::remove_cvref_t<decltype(s[0])>;               \
+        constexpr explicit operator fmt::basic_string_view<char_type>()      \
+            const {                                                          \
+          return fmt::detail::compile_string_to_view<char_type>(s);          \
+        }                                                                    \
+      };                                                                     \
+      using FMT_STRING_VIEW =                                                \
+          fmt::basic_string_view<typename FMT_COMPILE_STRING::char_type>;    \
+      fmt::detail::ignore_unused(FMT_STRING_VIEW(FMT_COMPILE_STRING()));     \
+      return FMT_COMPILE_STRING();                                           \
+    }()
+#endif  // FMT_CLANG_ANALYZER
+
+/**
+ * Constructs a legacy compile-time format string from a string literal `s`.
+ *
+ * **Example**:
+ *
+ *     // A compile-time error because 'd' is an invalid specifier for strings.
+ *     std::string s = fmt::format(FMT_STRING("{:d}"), "foo");
+ */
+#define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::detail::compile_string)
+
+FMT_API auto vsystem_error(int error_code, string_view fmt, format_args args)
+    -> std::system_error;
+
+/**
+ * Constructs `std::system_error` with a message formatted with
+ * `fmt::format(fmt, args...)`.
+ * `error_code` is a system error code as given by `errno`.
+ *
+ * **Example**:
+ *
+ *     // This throws std::system_error with the description
+ *     //   cannot open file 'madeup': No such file or directory
+ *     // or similar (system message may vary).
+ *     const char* filename = "madeup";
+ *     FILE* file = fopen(filename, "r");
+ *     if (!file)
+ *       throw fmt::system_error(errno, "cannot open file '{}'", filename);
+ */
+template <typename... T>
+auto system_error(int error_code, format_string<T...> fmt, T&&... args)
+    -> std::system_error {
+  return vsystem_error(error_code, fmt.str, vargs<T...>{{args...}});
+}
+
+/**
+ * Formats an error message for an error returned by an operating system or a
+ * language runtime, for example a file opening error, and writes it to `out`.
+ * The format is the same as the one used by `std::system_error(ec, message)`
+ * where `ec` is `std::error_code(error_code, std::generic_category())`.
+ * It is implementation-defined but normally looks like:
+ *
+ *     <message>: <system-message>
+ *
+ * where `<message>` is the passed message and `<system-message>` is the system
+ * message corresponding to the error code.
+ * `error_code` is a system error code as given by `errno`.
+ */
+FMT_API void format_system_error(detail::buffer<char>& out, int error_code,
+                                 const char* message) noexcept;
+
+// Reports a system error without throwing an exception.
+// Can be used to report errors from destructors.
+FMT_API void report_system_error(int error_code, const char* message) noexcept;
+
+inline auto vformat(locale_ref loc, string_view fmt, format_args args)
+    -> std::string {
+  auto buf = memory_buffer();
+  detail::vformat_to(buf, fmt, args, loc);
+  return {buf.data(), buf.size()};
+}
+
+template <typename... T>
+FMT_INLINE auto format(locale_ref loc, format_string<T...> fmt, T&&... args)
+    -> std::string {
+  return vformat(loc, fmt.str, vargs<T...>{{args...}});
+}
+
+template <typename OutputIt,
+          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
+auto vformat_to(OutputIt out, locale_ref loc, string_view fmt, format_args args)
+    -> OutputIt {
+  auto&& buf = detail::get_buffer<char>(out);
+  detail::vformat_to(buf, fmt, args, loc);
+  return detail::get_iterator(buf, out);
+}
+
+template <typename OutputIt, typename... T,
+          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, char>::value)>
+FMT_INLINE auto format_to(OutputIt out, locale_ref loc, format_string<T...> fmt,
+                          T&&... args) -> OutputIt {
+  return fmt::vformat_to(out, loc, fmt.str, vargs<T...>{{args...}});
+}
+
+template <typename... T>
+FMT_NODISCARD FMT_INLINE auto formatted_size(locale_ref loc,
+                                             format_string<T...> fmt,
+                                             T&&... args) -> size_t {
+  auto buf = detail::counting_buffer<>();
+  detail::vformat_to(buf, fmt.str, vargs<T...>{{args...}}, loc);
+  return buf.count();
+}
+
+FMT_API auto vformat(string_view fmt, format_args args) -> std::string;
+
+/**
+ * Formats `args` according to specifications in `fmt` and returns the result
+ * as a string.
+ *
+ * **Example**:
+ *
+ *     #include <fmt/format.h>
+ *     std::string message = fmt::format("The answer is {}.", 42);
+ */
+template <typename... T>
+FMT_NODISCARD FMT_INLINE auto format(format_string<T...> fmt, T&&... args)
+    -> std::string {
+  return vformat(fmt.str, vargs<T...>{{args...}});
+}
+
+/**
+ * Converts `value` to `std::string` using the default format for type `T`.
+ *
+ * **Example**:
+ *
+ *     std::string answer = fmt::to_string(42);
+ */
+template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+FMT_NODISCARD FMT_CONSTEXPR_STRING auto to_string(T value) -> std::string {
+  // The buffer should be large enough to store the number including the sign
+  // or "false" for bool.
+  char buffer[max_of(detail::digits10<T>() + 2, 5)];
+  return {buffer, detail::write<char>(buffer, value)};
+}
+
+template <typename T, FMT_ENABLE_IF(detail::use_format_as<T>::value)>
+FMT_NODISCARD FMT_CONSTEXPR_STRING auto to_string(const T& value)
+    -> std::string {
+  return to_string(format_as(value));
+}
+
+template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value &&
+                                    !detail::use_format_as<T>::value)>
+FMT_NODISCARD FMT_CONSTEXPR_STRING auto to_string(const T& value)
+    -> std::string {
+  auto buffer = memory_buffer();
+  detail::write<char>(appender(buffer), value);
+  return {buffer.data(), buffer.size()};
+}
+
+FMT_END_EXPORT
+FMT_END_NAMESPACE
+
+#ifdef FMT_HEADER_ONLY
+#  define FMT_FUNC inline
+#  include "format-inl.h"
+#endif
+
+// Restore _LIBCPP_REMOVE_TRANSITIVE_INCLUDES.
+#ifdef FMT_REMOVE_TRANSITIVE_INCLUDES
+#  undef _LIBCPP_REMOVE_TRANSITIVE_INCLUDES
+#endif
+
+#endif  // FMT_FORMAT_H_

+ 428 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/os.h

@@ -0,0 +1,428 @@
+// Formatting library for C++ - optional OS-specific functionality
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_OS_H_
+#define FMT_OS_H_
+
+#include "format.h"
+
+#ifndef FMT_MODULE
+#  include <cerrno>
+#  include <cstddef>
+#  include <cstdio>
+#  include <system_error>  // std::system_error
+
+#  if FMT_HAS_INCLUDE(<xlocale.h>)
+#    include <xlocale.h>  // LC_NUMERIC_MASK on macOS
+#  endif
+#endif  // FMT_MODULE
+
+#ifndef FMT_USE_FCNTL
+// UWP doesn't provide _pipe.
+#  if FMT_HAS_INCLUDE("winapifamily.h")
+#    include <winapifamily.h>
+#  endif
+#  if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \
+       defined(__linux__)) &&                              \
+      (!defined(WINAPI_FAMILY) ||                          \
+       (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP)) &&    \
+      !defined(__wasm__)
+#    include <fcntl.h>  // for O_RDONLY
+#    define FMT_USE_FCNTL 1
+#  else
+#    define FMT_USE_FCNTL 0
+#  endif
+#endif
+
+#ifndef FMT_POSIX
+#  if defined(_WIN32) && !defined(__MINGW32__)
+// Fix warnings about deprecated symbols.
+#    define FMT_POSIX(call) _##call
+#  else
+#    define FMT_POSIX(call) call
+#  endif
+#endif
+
+// Calls to system functions are wrapped in FMT_SYSTEM for testability.
+#ifdef FMT_SYSTEM
+#  define FMT_HAS_SYSTEM
+#  define FMT_POSIX_CALL(call) FMT_SYSTEM(call)
+#else
+#  define FMT_SYSTEM(call) ::call
+#  ifdef _WIN32
+// Fix warnings about deprecated symbols.
+#    define FMT_POSIX_CALL(call) ::_##call
+#  else
+#    define FMT_POSIX_CALL(call) ::call
+#  endif
+#endif
+
+// Retries the expression while it evaluates to error_result and errno
+// equals to EINTR.
+#ifndef _WIN32
+#  define FMT_RETRY_VAL(result, expression, error_result) \
+    do {                                                  \
+      (result) = (expression);                            \
+    } while ((result) == (error_result) && errno == EINTR)
+#else
+#  define FMT_RETRY_VAL(result, expression, error_result) result = (expression)
+#endif
+
+#define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1)
+
+FMT_BEGIN_NAMESPACE
+FMT_BEGIN_EXPORT
+
+/**
+ * A reference to a null-terminated string. It can be constructed from a C
+ * string or `std::string`.
+ *
+ * You can use one of the following type aliases for common character types:
+ *
+ * +---------------+-----------------------------+
+ * | Type          | Definition                  |
+ * +===============+=============================+
+ * | cstring_view  | basic_cstring_view<char>    |
+ * +---------------+-----------------------------+
+ * | wcstring_view | basic_cstring_view<wchar_t> |
+ * +---------------+-----------------------------+
+ *
+ * This class is most useful as a parameter type for functions that wrap C APIs.
+ */
+template <typename Char> class basic_cstring_view {
+ private:
+  const Char* data_;
+
+ public:
+  /// Constructs a string reference object from a C string.
+  basic_cstring_view(const Char* s) : data_(s) {}
+
+  /// Constructs a string reference from an `std::string` object.
+  basic_cstring_view(const std::basic_string<Char>& s) : data_(s.c_str()) {}
+
+  /// Returns the pointer to a C string.
+  auto c_str() const -> const Char* { return data_; }
+};
+
+using cstring_view = basic_cstring_view<char>;
+using wcstring_view = basic_cstring_view<wchar_t>;
+
+#ifdef _WIN32
+FMT_API const std::error_category& system_category() noexcept;
+
+namespace detail {
+FMT_API void format_windows_error(buffer<char>& out, int error_code,
+                                  const char* message) noexcept;
+}
+
+FMT_API std::system_error vwindows_error(int error_code, string_view fmt,
+                                         format_args args);
+
+/**
+ * Constructs a `std::system_error` object with the description of the form
+ *
+ *     <message>: <system-message>
+ *
+ * where `<message>` is the formatted message and `<system-message>` is the
+ * system message corresponding to the error code.
+ * `error_code` is a Windows error code as given by `GetLastError`.
+ * If `error_code` is not a valid error code such as -1, the system message
+ * will look like "error -1".
+ *
+ * **Example**:
+ *
+ *     // This throws a system_error with the description
+ *     //   cannot open file 'madeup': The system cannot find the file
+ * specified.
+ *     // or similar (system message may vary).
+ *     const char *filename = "madeup";
+ *     LPOFSTRUCT of = LPOFSTRUCT();
+ *     HFILE file = OpenFile(filename, &of, OF_READ);
+ *     if (file == HFILE_ERROR) {
+ *       throw fmt::windows_error(GetLastError(),
+ *                                "cannot open file '{}'", filename);
+ *     }
+ */
+template <typename... T>
+auto windows_error(int error_code, string_view message, const T&... args)
+    -> std::system_error {
+  return vwindows_error(error_code, message, vargs<T...>{{args...}});
+}
+
+// Reports a Windows error without throwing an exception.
+// Can be used to report errors from destructors.
+FMT_API void report_windows_error(int error_code, const char* message) noexcept;
+#else
+inline auto system_category() noexcept -> const std::error_category& {
+  return std::system_category();
+}
+#endif  // _WIN32
+
+// std::system is not available on some platforms such as iOS (#2248).
+#ifdef __OSX__
+template <typename S, typename... Args, typename Char = char_t<S>>
+void say(const S& fmt, Args&&... args) {
+  std::system(format("say \"{}\"", format(fmt, args...)).c_str());
+}
+#endif
+
+// A buffered file.
+class buffered_file {
+ private:
+  FILE* file_;
+
+  friend class file;
+
+  inline explicit buffered_file(FILE* f) : file_(f) {}
+
+ public:
+  buffered_file(const buffered_file&) = delete;
+  void operator=(const buffered_file&) = delete;
+
+  // Constructs a buffered_file object which doesn't represent any file.
+  inline buffered_file() noexcept : file_(nullptr) {}
+
+  // Destroys the object closing the file it represents if any.
+  FMT_API ~buffered_file() noexcept;
+
+ public:
+  inline buffered_file(buffered_file&& other) noexcept : file_(other.file_) {
+    other.file_ = nullptr;
+  }
+
+  inline auto operator=(buffered_file&& other) -> buffered_file& {
+    close();
+    file_ = other.file_;
+    other.file_ = nullptr;
+    return *this;
+  }
+
+  // Opens a file.
+  FMT_API buffered_file(cstring_view filename, cstring_view mode);
+
+  // Closes the file.
+  FMT_API void close();
+
+  // Returns the pointer to a FILE object representing this file.
+  inline auto get() const noexcept -> FILE* { return file_; }
+
+  FMT_API auto descriptor() const -> int;
+
+  template <typename... T>
+  inline void print(string_view fmt, const T&... args) {
+    fmt::vargs<T...> vargs = {{args...}};
+    detail::is_locking<T...>() ? fmt::vprint_buffered(file_, fmt, vargs)
+                               : fmt::vprint(file_, fmt, vargs);
+  }
+};
+
+#if FMT_USE_FCNTL
+
+// A file. Closed file is represented by a file object with descriptor -1.
+// Methods that are not declared with noexcept may throw
+// fmt::system_error in case of failure. Note that some errors such as
+// closing the file multiple times will cause a crash on Windows rather
+// than an exception. You can get standard behavior by overriding the
+// invalid parameter handler with _set_invalid_parameter_handler.
+class FMT_API file {
+ private:
+  int fd_;  // File descriptor.
+
+  // Constructs a file object with a given descriptor.
+  explicit file(int fd) : fd_(fd) {}
+
+  friend struct pipe;
+
+ public:
+  // Possible values for the oflag argument to the constructor.
+  enum {
+    RDONLY = FMT_POSIX(O_RDONLY),  // Open for reading only.
+    WRONLY = FMT_POSIX(O_WRONLY),  // Open for writing only.
+    RDWR = FMT_POSIX(O_RDWR),      // Open for reading and writing.
+    CREATE = FMT_POSIX(O_CREAT),   // Create if the file doesn't exist.
+    APPEND = FMT_POSIX(O_APPEND),  // Open in append mode.
+    TRUNC = FMT_POSIX(O_TRUNC)     // Truncate the content of the file.
+  };
+
+  // Constructs a file object which doesn't represent any file.
+  inline file() noexcept : fd_(-1) {}
+
+  // Opens a file and constructs a file object representing this file.
+  file(cstring_view path, int oflag);
+
+ public:
+  file(const file&) = delete;
+  void operator=(const file&) = delete;
+
+  inline file(file&& other) noexcept : fd_(other.fd_) { other.fd_ = -1; }
+
+  // Move assignment is not noexcept because close may throw.
+  inline auto operator=(file&& other) -> file& {
+    close();
+    fd_ = other.fd_;
+    other.fd_ = -1;
+    return *this;
+  }
+
+  // Destroys the object closing the file it represents if any.
+  ~file() noexcept;
+
+  // Returns the file descriptor.
+  inline auto descriptor() const noexcept -> int { return fd_; }
+
+  // Closes the file.
+  void close();
+
+  // Returns the file size. The size has signed type for consistency with
+  // stat::st_size.
+  auto size() const -> long long;
+
+  // Attempts to read count bytes from the file into the specified buffer.
+  auto read(void* buffer, size_t count) -> size_t;
+
+  // Attempts to write count bytes from the specified buffer to the file.
+  auto write(const void* buffer, size_t count) -> size_t;
+
+  // Duplicates a file descriptor with the dup function and returns
+  // the duplicate as a file object.
+  static auto dup(int fd) -> file;
+
+  // Makes fd be the copy of this file descriptor, closing fd first if
+  // necessary.
+  void dup2(int fd);
+
+  // Makes fd be the copy of this file descriptor, closing fd first if
+  // necessary.
+  void dup2(int fd, std::error_code& ec) noexcept;
+
+  // Creates a buffered_file object associated with this file and detaches
+  // this file object from the file.
+  auto fdopen(const char* mode) -> buffered_file;
+
+#  if defined(_WIN32) && !defined(__MINGW32__)
+  // Opens a file and constructs a file object representing this file by
+  // wcstring_view filename. Windows only.
+  static file open_windows_file(wcstring_view path, int oflag);
+#  endif
+};
+
+struct FMT_API pipe {
+  file read_end;
+  file write_end;
+
+  // Creates a pipe setting up read_end and write_end file objects for reading
+  // and writing respectively.
+  pipe();
+};
+
+// Returns the memory page size.
+auto getpagesize() -> long;
+
+namespace detail {
+
+struct buffer_size {
+  constexpr buffer_size() = default;
+  size_t value = 0;
+  FMT_CONSTEXPR auto operator=(size_t val) const -> buffer_size {
+    auto bs = buffer_size();
+    bs.value = val;
+    return bs;
+  }
+};
+
+struct ostream_params {
+  int oflag = file::WRONLY | file::CREATE | file::TRUNC;
+  size_t buffer_size = BUFSIZ > 32768 ? BUFSIZ : 32768;
+
+  constexpr ostream_params() {}
+
+  template <typename... T>
+  ostream_params(T... params, int new_oflag) : ostream_params(params...) {
+    oflag = new_oflag;
+  }
+
+  template <typename... T>
+  ostream_params(T... params, detail::buffer_size bs)
+      : ostream_params(params...) {
+    this->buffer_size = bs.value;
+  }
+
+// Intel has a bug that results in failure to deduce a constructor
+// for empty parameter packs.
+#  if defined(__INTEL_COMPILER) && __INTEL_COMPILER < 2000
+  ostream_params(int new_oflag) : oflag(new_oflag) {}
+  ostream_params(detail::buffer_size bs) : buffer_size(bs.value) {}
+#  endif
+};
+
+}  // namespace detail
+
+FMT_INLINE_VARIABLE constexpr auto buffer_size = detail::buffer_size();
+
+/// A fast buffered output stream for writing from a single thread. Writing from
+/// multiple threads without external synchronization may result in a data race.
+class FMT_API ostream : private detail::buffer<char> {
+ private:
+  file file_;
+
+  ostream(cstring_view path, const detail::ostream_params& params);
+
+  static void grow(buffer<char>& buf, size_t);
+
+ public:
+  ostream(ostream&& other) noexcept;
+  ~ostream();
+
+  operator writer() {
+    detail::buffer<char>& buf = *this;
+    return buf;
+  }
+
+  inline void flush() {
+    if (size() == 0) return;
+    file_.write(data(), size() * sizeof(data()[0]));
+    clear();
+  }
+
+  template <typename... T>
+  friend auto output_file(cstring_view path, T... params) -> ostream;
+
+  inline void close() {
+    flush();
+    file_.close();
+  }
+
+  /// Formats `args` according to specifications in `fmt` and writes the
+  /// output to the file.
+  template <typename... T> void print(format_string<T...> fmt, T&&... args) {
+    vformat_to(appender(*this), fmt.str, vargs<T...>{{args...}});
+  }
+};
+
+/**
+ * Opens a file for writing. Supported parameters passed in `params`:
+ *
+ * - `<integer>`: Flags passed to [open](
+ *   https://pubs.opengroup.org/onlinepubs/007904875/functions/open.html)
+ *   (`file::WRONLY | file::CREATE | file::TRUNC` by default)
+ * - `buffer_size=<integer>`: Output buffer size
+ *
+ * **Example**:
+ *
+ *     auto out = fmt::output_file("guide.txt");
+ *     out.print("Don't {}", "Panic");
+ */
+template <typename... T>
+inline auto output_file(cstring_view path, T... params) -> ostream {
+  return {path, detail::ostream_params(params...)};
+}
+#endif  // FMT_USE_FCNTL
+
+FMT_END_EXPORT
+FMT_END_NAMESPACE
+
+#endif  // FMT_OS_H_

+ 167 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/ostream.h

@@ -0,0 +1,167 @@
+// Formatting library for C++ - std::ostream support
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_OSTREAM_H_
+#define FMT_OSTREAM_H_
+
+#ifndef FMT_MODULE
+#  include <fstream>  // std::filebuf
+#endif
+
+#ifdef _WIN32
+#  ifdef __GLIBCXX__
+#    include <ext/stdio_filebuf.h>
+#    include <ext/stdio_sync_filebuf.h>
+#  endif
+#  include <io.h>
+#endif
+
+#include "chrono.h"  // formatbuf
+
+#ifdef _MSVC_STL_UPDATE
+#  define FMT_MSVC_STL_UPDATE _MSVC_STL_UPDATE
+#elif defined(_MSC_VER) && _MSC_VER < 1912  // VS 15.5
+#  define FMT_MSVC_STL_UPDATE _MSVC_LANG
+#else
+#  define FMT_MSVC_STL_UPDATE 0
+#endif
+
+FMT_BEGIN_NAMESPACE
+namespace detail {
+
+// Generate a unique explicit instantiation in every translation unit using a
+// tag type in an anonymous namespace.
+namespace {
+struct file_access_tag {};
+}  // namespace
+template <typename Tag, typename BufType, FILE* BufType::*FileMemberPtr>
+class file_access {
+  friend auto get_file(BufType& obj) -> FILE* { return obj.*FileMemberPtr; }
+};
+
+#if FMT_MSVC_STL_UPDATE
+template class file_access<file_access_tag, std::filebuf,
+                           &std::filebuf::_Myfile>;
+auto get_file(std::filebuf&) -> FILE*;
+#endif
+
+// Write the content of buf to os.
+// It is a separate function rather than a part of vprint to simplify testing.
+template <typename Char>
+void write_buffer(std::basic_ostream<Char>& os, buffer<Char>& buf) {
+  const Char* buf_data = buf.data();
+  using unsigned_streamsize = make_unsigned_t<std::streamsize>;
+  unsigned_streamsize size = buf.size();
+  unsigned_streamsize max_size = to_unsigned(max_value<std::streamsize>());
+  do {
+    unsigned_streamsize n = size <= max_size ? size : max_size;
+    os.write(buf_data, static_cast<std::streamsize>(n));
+    buf_data += n;
+    size -= n;
+  } while (size != 0);
+}
+
+template <typename T> struct streamed_view {
+  const T& value;
+};
+}  // namespace detail
+
+// Formats an object of type T that has an overloaded ostream operator<<.
+template <typename Char>
+struct basic_ostream_formatter : formatter<basic_string_view<Char>, Char> {
+  void set_debug_format() = delete;
+
+  template <typename T, typename Context>
+  auto format(const T& value, Context& ctx) const -> decltype(ctx.out()) {
+    auto buffer = basic_memory_buffer<Char>();
+    auto&& formatbuf = detail::formatbuf<std::basic_streambuf<Char>>(buffer);
+    auto&& output = std::basic_ostream<Char>(&formatbuf);
+    output.imbue(std::locale::classic());  // The default is always unlocalized.
+    output << value;
+    output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
+    return formatter<basic_string_view<Char>, Char>::format(
+        {buffer.data(), buffer.size()}, ctx);
+  }
+};
+
+using ostream_formatter = basic_ostream_formatter<char>;
+
+template <typename T, typename Char>
+struct formatter<detail::streamed_view<T>, Char>
+    : basic_ostream_formatter<Char> {
+  template <typename Context>
+  auto format(detail::streamed_view<T> view, Context& ctx) const
+      -> decltype(ctx.out()) {
+    return basic_ostream_formatter<Char>::format(view.value, ctx);
+  }
+};
+
+/**
+ * Returns a view that formats `value` via an ostream `operator<<`.
+ *
+ * **Example**:
+ *
+ *     fmt::print("Current thread id: {}\n",
+ *                fmt::streamed(std::this_thread::get_id()));
+ */
+template <typename T>
+constexpr auto streamed(const T& value) -> detail::streamed_view<T> {
+  return {value};
+}
+
+inline void vprint(std::ostream& os, string_view fmt, format_args args) {
+  auto buffer = memory_buffer();
+  detail::vformat_to(buffer, fmt, args);
+  FILE* f = nullptr;
+#if FMT_MSVC_STL_UPDATE && FMT_USE_RTTI
+  if (auto* buf = dynamic_cast<std::filebuf*>(os.rdbuf()))
+    f = detail::get_file(*buf);
+#elif defined(_WIN32) && defined(__GLIBCXX__) && FMT_USE_RTTI
+  auto* rdbuf = os.rdbuf();
+  if (auto* sfbuf = dynamic_cast<__gnu_cxx::stdio_sync_filebuf<char>*>(rdbuf))
+    f = sfbuf->file();
+  else if (auto* fbuf = dynamic_cast<__gnu_cxx::stdio_filebuf<char>*>(rdbuf))
+    f = fbuf->file();
+#endif
+#ifdef _WIN32
+  if (f) {
+    int fd = _fileno(f);
+    if (_isatty(fd)) {
+      os.flush();
+      if (detail::write_console(fd, {buffer.data(), buffer.size()})) return;
+    }
+  }
+#endif
+  detail::ignore_unused(f);
+  detail::write_buffer(os, buffer);
+}
+
+/**
+ * Prints formatted data to the stream `os`.
+ *
+ * **Example**:
+ *
+ *     fmt::print(cerr, "Don't {}!", "panic");
+ */
+FMT_EXPORT template <typename... T>
+void print(std::ostream& os, format_string<T...> fmt, T&&... args) {
+  fmt::vargs<T...> vargs = {{args...}};
+  if (detail::const_check(detail::use_utf8)) return vprint(os, fmt.str, vargs);
+  auto buffer = memory_buffer();
+  detail::vformat_to(buffer, fmt.str, vargs);
+  detail::write_buffer(os, buffer);
+}
+
+FMT_EXPORT template <typename... T>
+void println(std::ostream& os, format_string<T...> fmt, T&&... args) {
+  fmt::print(os, FMT_STRING("{}\n"),
+             fmt::format(fmt, std::forward<T>(args)...));
+}
+
+FMT_END_NAMESPACE
+
+#endif  // FMT_OSTREAM_H_

+ 624 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/printf.h

@@ -0,0 +1,624 @@
+// Formatting library for C++ - legacy printf implementation
+//
+// Copyright (c) 2012 - 2016, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_PRINTF_H_
+#define FMT_PRINTF_H_
+
+#ifndef FMT_MODULE
+#  include <algorithm>  // std::find
+#  include <limits>     // std::numeric_limits
+#endif
+
+#include "format.h"
+
+FMT_BEGIN_NAMESPACE
+FMT_BEGIN_EXPORT
+
+template <typename Char> class basic_printf_context {
+ private:
+  basic_appender<Char> out_;
+  basic_format_args<basic_printf_context> args_;
+
+  static_assert(std::is_same<Char, char>::value ||
+                    std::is_same<Char, wchar_t>::value,
+                "Unsupported code unit type.");
+
+ public:
+  using char_type = Char;
+  enum { builtin_types = 1 };
+
+  /// Constructs a `printf_context` object. References to the arguments are
+  /// stored in the context object so make sure they have appropriate lifetimes.
+  basic_printf_context(basic_appender<Char> out,
+                       basic_format_args<basic_printf_context> args)
+      : out_(out), args_(args) {}
+
+  auto out() -> basic_appender<Char> { return out_; }
+  void advance_to(basic_appender<Char>) {}
+
+  auto locale() -> locale_ref { return {}; }
+
+  auto arg(int id) const -> basic_format_arg<basic_printf_context> {
+    return args_.get(id);
+  }
+};
+
+namespace detail {
+
+// Return the result via the out param to workaround gcc bug 77539.
+template <bool IS_CONSTEXPR, typename T, typename Ptr = const T*>
+FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr& out) -> bool {
+  for (out = first; out != last; ++out) {
+    if (*out == value) return true;
+  }
+  return false;
+}
+
+template <>
+inline auto find<false, char>(const char* first, const char* last, char value,
+                              const char*& out) -> bool {
+  out =
+      static_cast<const char*>(memchr(first, value, to_unsigned(last - first)));
+  return out != nullptr;
+}
+
+// Checks if a value fits in int - used to avoid warnings about comparing
+// signed and unsigned integers.
+template <bool IS_SIGNED> struct int_checker {
+  template <typename T> static auto fits_in_int(T value) -> bool {
+    return value <= to_unsigned(max_value<int>());
+  }
+  inline static auto fits_in_int(bool) -> bool { return true; }
+};
+
+template <> struct int_checker<true> {
+  template <typename T> static auto fits_in_int(T value) -> bool {
+    return value >= (std::numeric_limits<int>::min)() &&
+           value <= max_value<int>();
+  }
+  inline static auto fits_in_int(int) -> bool { return true; }
+};
+
+struct printf_precision_handler {
+  template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+  auto operator()(T value) -> int {
+    if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value))
+      report_error("number is too big");
+    return max_of(static_cast<int>(value), 0);
+  }
+
+  template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+  auto operator()(T) -> int {
+    report_error("precision is not integer");
+    return 0;
+  }
+};
+
+// An argument visitor that returns true iff arg is a zero integer.
+struct is_zero_int {
+  template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+  auto operator()(T value) -> bool {
+    return value == 0;
+  }
+
+  template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+  auto operator()(T) -> bool {
+    return false;
+  }
+};
+
+template <typename T> struct make_unsigned_or_bool : std::make_unsigned<T> {};
+
+template <> struct make_unsigned_or_bool<bool> {
+  using type = bool;
+};
+
+template <typename T, typename Context> class arg_converter {
+ private:
+  using char_type = typename Context::char_type;
+
+  basic_format_arg<Context>& arg_;
+  char_type type_;
+
+ public:
+  arg_converter(basic_format_arg<Context>& arg, char_type type)
+      : arg_(arg), type_(type) {}
+
+  void operator()(bool value) {
+    if (type_ != 's') operator()<bool>(value);
+  }
+
+  template <typename U, FMT_ENABLE_IF(std::is_integral<U>::value)>
+  void operator()(U value) {
+    bool is_signed = type_ == 'd' || type_ == 'i';
+    using target_type = conditional_t<std::is_same<T, void>::value, U, T>;
+    if (const_check(sizeof(target_type) <= sizeof(int))) {
+      // Extra casts are used to silence warnings.
+      using unsigned_type = typename make_unsigned_or_bool<target_type>::type;
+      if (is_signed)
+        arg_ = static_cast<int>(static_cast<target_type>(value));
+      else
+        arg_ = static_cast<unsigned>(static_cast<unsigned_type>(value));
+    } else {
+      // glibc's printf doesn't sign extend arguments of smaller types:
+      //   std::printf("%lld", -42);  // prints "4294967254"
+      // but we don't have to do the same because it's a UB.
+      if (is_signed)
+        arg_ = static_cast<long long>(value);
+      else
+        arg_ = static_cast<typename make_unsigned_or_bool<U>::type>(value);
+    }
+  }
+
+  template <typename U, FMT_ENABLE_IF(!std::is_integral<U>::value)>
+  void operator()(U) {}  // No conversion needed for non-integral types.
+};
+
+// Converts an integer argument to T for printf, if T is an integral type.
+// If T is void, the argument is converted to corresponding signed or unsigned
+// type depending on the type specifier: 'd' and 'i' - signed, other -
+// unsigned).
+template <typename T, typename Context, typename Char>
+void convert_arg(basic_format_arg<Context>& arg, Char type) {
+  arg.visit(arg_converter<T, Context>(arg, type));
+}
+
+// Converts an integer argument to char for printf.
+template <typename Context> class char_converter {
+ private:
+  basic_format_arg<Context>& arg_;
+
+ public:
+  explicit char_converter(basic_format_arg<Context>& arg) : arg_(arg) {}
+
+  template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+  void operator()(T value) {
+    arg_ = static_cast<typename Context::char_type>(value);
+  }
+
+  template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+  void operator()(T) {}  // No conversion needed for non-integral types.
+};
+
+// An argument visitor that return a pointer to a C string if argument is a
+// string or null otherwise.
+template <typename Char> struct get_cstring {
+  template <typename T> auto operator()(T) -> const Char* { return nullptr; }
+  auto operator()(const Char* s) -> const Char* { return s; }
+};
+
+// Checks if an argument is a valid printf width specifier and sets
+// left alignment if it is negative.
+class printf_width_handler {
+ private:
+  format_specs& specs_;
+
+ public:
+  inline explicit printf_width_handler(format_specs& specs) : specs_(specs) {}
+
+  template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+  auto operator()(T value) -> unsigned {
+    auto width = static_cast<uint32_or_64_or_128_t<T>>(value);
+    if (detail::is_negative(value)) {
+      specs_.set_align(align::left);
+      width = 0 - width;
+    }
+    unsigned int_max = to_unsigned(max_value<int>());
+    if (width > int_max) report_error("number is too big");
+    return static_cast<unsigned>(width);
+  }
+
+  template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+  auto operator()(T) -> unsigned {
+    report_error("width is not integer");
+    return 0;
+  }
+};
+
+// Workaround for a bug with the XL compiler when initializing
+// printf_arg_formatter's base class.
+template <typename Char>
+auto make_arg_formatter(basic_appender<Char> iter, format_specs& s)
+    -> arg_formatter<Char> {
+  return {iter, s, locale_ref()};
+}
+
+// The `printf` argument formatter.
+template <typename Char>
+class printf_arg_formatter : public arg_formatter<Char> {
+ private:
+  using base = arg_formatter<Char>;
+  using context_type = basic_printf_context<Char>;
+
+  context_type& context_;
+
+  void write_null_pointer(bool is_string = false) {
+    auto s = this->specs;
+    s.set_type(presentation_type::none);
+    write_bytes<Char>(this->out, is_string ? "(null)" : "(nil)", s);
+  }
+
+  template <typename T> void write(T value) {
+    detail::write<Char>(this->out, value, this->specs, this->locale);
+  }
+
+ public:
+  printf_arg_formatter(basic_appender<Char> iter, format_specs& s,
+                       context_type& ctx)
+      : base(make_arg_formatter(iter, s)), context_(ctx) {}
+
+  void operator()(monostate value) { write(value); }
+
+  template <typename T, FMT_ENABLE_IF(detail::is_integral<T>::value)>
+  void operator()(T value) {
+    // MSVC2013 fails to compile separate overloads for bool and Char so use
+    // std::is_same instead.
+    if (!std::is_same<T, Char>::value) {
+      write(value);
+      return;
+    }
+    format_specs s = this->specs;
+    if (s.type() != presentation_type::none &&
+        s.type() != presentation_type::chr) {
+      return (*this)(static_cast<int>(value));
+    }
+    s.set_sign(sign::none);
+    s.clear_alt();
+    s.set_fill(' ');  // Ignore '0' flag for char types.
+    // align::numeric needs to be overwritten here since the '0' flag is
+    // ignored for non-numeric types
+    if (s.align() == align::none || s.align() == align::numeric)
+      s.set_align(align::right);
+    detail::write<Char>(this->out, static_cast<Char>(value), s);
+  }
+
+  template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+  void operator()(T value) {
+    write(value);
+  }
+
+  void operator()(const char* value) {
+    if (value)
+      write(value);
+    else
+      write_null_pointer(this->specs.type() != presentation_type::pointer);
+  }
+
+  void operator()(const wchar_t* value) {
+    if (value)
+      write(value);
+    else
+      write_null_pointer(this->specs.type() != presentation_type::pointer);
+  }
+
+  void operator()(basic_string_view<Char> value) { write(value); }
+
+  void operator()(const void* value) {
+    if (value)
+      write(value);
+    else
+      write_null_pointer();
+  }
+
+  void operator()(typename basic_format_arg<context_type>::handle handle) {
+    auto parse_ctx = parse_context<Char>({});
+    handle.format(parse_ctx, context_);
+  }
+};
+
+template <typename Char>
+void parse_flags(format_specs& specs, const Char*& it, const Char* end) {
+  for (; it != end; ++it) {
+    switch (*it) {
+    case '-': specs.set_align(align::left); break;
+    case '+': specs.set_sign(sign::plus); break;
+    case '0': specs.set_fill('0'); break;
+    case ' ':
+      if (specs.sign() != sign::plus) specs.set_sign(sign::space);
+      break;
+    case '#': specs.set_alt(); break;
+    default:  return;
+    }
+  }
+}
+
+template <typename Char, typename GetArg>
+auto parse_header(const Char*& it, const Char* end, format_specs& specs,
+                  GetArg get_arg) -> int {
+  int arg_index = -1;
+  Char c = *it;
+  if (c >= '0' && c <= '9') {
+    // Parse an argument index (if followed by '$') or a width possibly
+    // preceded with '0' flag(s).
+    int value = parse_nonnegative_int(it, end, -1);
+    if (it != end && *it == '$') {  // value is an argument index
+      ++it;
+      arg_index = value != -1 ? value : max_value<int>();
+    } else {
+      if (c == '0') specs.set_fill('0');
+      if (value != 0) {
+        // Nonzero value means that we parsed width and don't need to
+        // parse it or flags again, so return now.
+        if (value == -1) report_error("number is too big");
+        specs.width = value;
+        return arg_index;
+      }
+    }
+  }
+  parse_flags(specs, it, end);
+  // Parse width.
+  if (it != end) {
+    if (*it >= '0' && *it <= '9') {
+      specs.width = parse_nonnegative_int(it, end, -1);
+      if (specs.width == -1) report_error("number is too big");
+    } else if (*it == '*') {
+      ++it;
+      specs.width = static_cast<int>(
+          get_arg(-1).visit(detail::printf_width_handler(specs)));
+    }
+  }
+  return arg_index;
+}
+
+inline auto parse_printf_presentation_type(char c, type t, bool& upper)
+    -> presentation_type {
+  using pt = presentation_type;
+  constexpr auto integral_set = sint_set | uint_set | bool_set | char_set;
+  switch (c) {
+  case 'd': return in(t, integral_set) ? pt::dec : pt::none;
+  case 'o': return in(t, integral_set) ? pt::oct : pt::none;
+  case 'X': upper = true; FMT_FALLTHROUGH;
+  case 'x': return in(t, integral_set) ? pt::hex : pt::none;
+  case 'E': upper = true; FMT_FALLTHROUGH;
+  case 'e': return in(t, float_set) ? pt::exp : pt::none;
+  case 'F': upper = true; FMT_FALLTHROUGH;
+  case 'f': return in(t, float_set) ? pt::fixed : pt::none;
+  case 'G': upper = true; FMT_FALLTHROUGH;
+  case 'g': return in(t, float_set) ? pt::general : pt::none;
+  case 'A': upper = true; FMT_FALLTHROUGH;
+  case 'a': return in(t, float_set) ? pt::hexfloat : pt::none;
+  case 'c': return in(t, integral_set) ? pt::chr : pt::none;
+  case 's': return in(t, string_set | cstring_set) ? pt::string : pt::none;
+  case 'p': return in(t, pointer_set | cstring_set) ? pt::pointer : pt::none;
+  default:  return pt::none;
+  }
+}
+
+template <typename Char, typename Context>
+void vprintf(buffer<Char>& buf, basic_string_view<Char> format,
+             basic_format_args<Context> args) {
+  using iterator = basic_appender<Char>;
+  auto out = iterator(buf);
+  auto context = basic_printf_context<Char>(out, args);
+  auto parse_ctx = parse_context<Char>(format);
+
+  // Returns the argument with specified index or, if arg_index is -1, the next
+  // argument.
+  auto get_arg = [&](int arg_index) {
+    if (arg_index < 0)
+      arg_index = parse_ctx.next_arg_id();
+    else
+      parse_ctx.check_arg_id(--arg_index);
+    auto arg = context.arg(arg_index);
+    if (!arg) report_error("argument not found");
+    return arg;
+  };
+
+  const Char* start = parse_ctx.begin();
+  const Char* end = parse_ctx.end();
+  auto it = start;
+  while (it != end) {
+    if (!find<false, Char>(it, end, '%', it)) {
+      it = end;  // find leaves it == nullptr if it doesn't find '%'.
+      break;
+    }
+    Char c = *it++;
+    if (it != end && *it == c) {
+      write(out, basic_string_view<Char>(start, to_unsigned(it - start)));
+      start = ++it;
+      continue;
+    }
+    write(out, basic_string_view<Char>(start, to_unsigned(it - 1 - start)));
+
+    auto specs = format_specs();
+    specs.set_align(align::right);
+
+    // Parse argument index, flags and width.
+    int arg_index = parse_header(it, end, specs, get_arg);
+    if (arg_index == 0) report_error("argument not found");
+
+    // Parse precision.
+    if (it != end && *it == '.') {
+      ++it;
+      c = it != end ? *it : 0;
+      if ('0' <= c && c <= '9') {
+        specs.precision = parse_nonnegative_int(it, end, 0);
+      } else if (c == '*') {
+        ++it;
+        specs.precision =
+            static_cast<int>(get_arg(-1).visit(printf_precision_handler()));
+      } else {
+        specs.precision = 0;
+      }
+    }
+
+    auto arg = get_arg(arg_index);
+    // For d, i, o, u, x, and X conversion specifiers, if a precision is
+    // specified, the '0' flag is ignored
+    if (specs.precision >= 0 && is_integral_type(arg.type())) {
+      // Ignore '0' for non-numeric types or if '-' present.
+      specs.set_fill(' ');
+    }
+    if (specs.precision >= 0 && arg.type() == type::cstring_type) {
+      auto str = arg.visit(get_cstring<Char>());
+      auto str_end = str + specs.precision;
+      auto nul = std::find(str, str_end, Char());
+      auto sv = basic_string_view<Char>(
+          str, to_unsigned(nul != str_end ? nul - str : specs.precision));
+      arg = sv;
+    }
+    if (specs.alt() && arg.visit(is_zero_int())) specs.clear_alt();
+    if (specs.fill_unit<Char>() == '0') {
+      if (is_arithmetic_type(arg.type()) && specs.align() != align::left) {
+        specs.set_align(align::numeric);
+      } else {
+        // Ignore '0' flag for non-numeric types or if '-' flag is also present.
+        specs.set_fill(' ');
+      }
+    }
+
+    // Parse length and convert the argument to the required type.
+    c = it != end ? *it++ : 0;
+    Char t = it != end ? *it : 0;
+    switch (c) {
+    case 'h':
+      if (t == 'h') {
+        ++it;
+        t = it != end ? *it : 0;
+        convert_arg<signed char>(arg, t);
+      } else {
+        convert_arg<short>(arg, t);
+      }
+      break;
+    case 'l':
+      if (t == 'l') {
+        ++it;
+        t = it != end ? *it : 0;
+        convert_arg<long long>(arg, t);
+      } else {
+        convert_arg<long>(arg, t);
+      }
+      break;
+    case 'j': convert_arg<intmax_t>(arg, t); break;
+    case 'z': convert_arg<size_t>(arg, t); break;
+    case 't': convert_arg<std::ptrdiff_t>(arg, t); break;
+    case 'L':
+      // printf produces garbage when 'L' is omitted for long double, no
+      // need to do the same.
+      break;
+    default: --it; convert_arg<void>(arg, c);
+    }
+
+    // Parse type.
+    if (it == end) report_error("invalid format string");
+    char type = static_cast<char>(*it++);
+    if (is_integral_type(arg.type())) {
+      // Normalize type.
+      switch (type) {
+      case 'i':
+      case 'u': type = 'd'; break;
+      case 'c':
+        arg.visit(char_converter<basic_printf_context<Char>>(arg));
+        break;
+      }
+    }
+    bool upper = false;
+    specs.set_type(parse_printf_presentation_type(type, arg.type(), upper));
+    if (specs.type() == presentation_type::none)
+      report_error("invalid format specifier");
+    if (upper) specs.set_upper();
+
+    start = it;
+
+    // Format argument.
+    arg.visit(printf_arg_formatter<Char>(out, specs, context));
+  }
+  write(out, basic_string_view<Char>(start, to_unsigned(it - start)));
+}
+}  // namespace detail
+
+using printf_context = basic_printf_context<char>;
+using wprintf_context = basic_printf_context<wchar_t>;
+
+using printf_args = basic_format_args<printf_context>;
+using wprintf_args = basic_format_args<wprintf_context>;
+
+/// Constructs an `format_arg_store` object that contains references to
+/// arguments and can be implicitly converted to `printf_args`.
+template <typename Char = char, typename... T>
+inline auto make_printf_args(T&... args)
+    -> decltype(fmt::make_format_args<basic_printf_context<Char>>(args...)) {
+  return fmt::make_format_args<basic_printf_context<Char>>(args...);
+}
+
+template <typename Char> struct vprintf_args {
+  using type = basic_format_args<basic_printf_context<Char>>;
+};
+
+template <typename Char>
+inline auto vsprintf(basic_string_view<Char> fmt,
+                     typename vprintf_args<Char>::type args)
+    -> std::basic_string<Char> {
+  auto buf = basic_memory_buffer<Char>();
+  detail::vprintf(buf, fmt, args);
+  return {buf.data(), buf.size()};
+}
+
+/**
+ * Formats `args` according to specifications in `fmt` and returns the result
+ * as as string.
+ *
+ * **Example**:
+ *
+ *     std::string message = fmt::sprintf("The answer is %d", 42);
+ */
+template <typename... T>
+inline auto sprintf(string_view fmt, const T&... args) -> std::string {
+  return vsprintf(fmt, make_printf_args(args...));
+}
+template <typename... T>
+FMT_DEPRECATED auto sprintf(basic_string_view<wchar_t> fmt, const T&... args)
+    -> std::wstring {
+  return vsprintf(fmt, make_printf_args<wchar_t>(args...));
+}
+
+template <typename Char>
+auto vfprintf(std::FILE* f, basic_string_view<Char> fmt,
+              typename vprintf_args<Char>::type args) -> int {
+  auto buf = basic_memory_buffer<Char>();
+  detail::vprintf(buf, fmt, args);
+  size_t size = buf.size();
+  return std::fwrite(buf.data(), sizeof(Char), size, f) < size
+             ? -1
+             : static_cast<int>(size);
+}
+
+/**
+ * Formats `args` according to specifications in `fmt` and writes the output
+ * to `f`.
+ *
+ * **Example**:
+ *
+ *     fmt::fprintf(stderr, "Don't %s!", "panic");
+ */
+template <typename... T>
+inline auto fprintf(std::FILE* f, string_view fmt, const T&... args) -> int {
+  return vfprintf(f, fmt, make_printf_args(args...));
+}
+template <typename... T>
+FMT_DEPRECATED auto fprintf(std::FILE* f, basic_string_view<wchar_t> fmt,
+                            const T&... args) -> int {
+  return vfprintf(f, fmt, make_printf_args<wchar_t>(args...));
+}
+
+/**
+ * Formats `args` according to specifications in `fmt` and writes the output
+ * to `stdout`.
+ *
+ * **Example**:
+ *
+ *   fmt::printf("Elapsed time: %.2f seconds", 1.23);
+ */
+template <typename... T>
+inline auto printf(string_view fmt, const T&... args) -> int {
+  return vfprintf(stdout, fmt, make_printf_args(args...));
+}
+
+FMT_END_EXPORT
+FMT_END_NAMESPACE
+
+#endif  // FMT_PRINTF_H_

+ 852 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/ranges.h

@@ -0,0 +1,852 @@
+// Formatting library for C++ - range and tuple support
+//
+// Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_RANGES_H_
+#define FMT_RANGES_H_
+
+#ifndef FMT_MODULE
+#  include <initializer_list>
+#  include <iterator>
+#  include <tuple>
+#  include <type_traits>
+#  include <utility>
+#endif
+
+#include "format.h"
+
+FMT_BEGIN_NAMESPACE
+
+FMT_EXPORT
+enum class range_format { disabled, map, set, sequence, string, debug_string };
+
+namespace detail {
+
+template <typename T> class is_map {
+  template <typename U> static auto check(U*) -> typename U::mapped_type;
+  template <typename> static void check(...);
+
+ public:
+  static constexpr bool value =
+      !std::is_void<decltype(check<T>(nullptr))>::value;
+};
+
+template <typename T> class is_set {
+  template <typename U> static auto check(U*) -> typename U::key_type;
+  template <typename> static void check(...);
+
+ public:
+  static constexpr bool value =
+      !std::is_void<decltype(check<T>(nullptr))>::value && !is_map<T>::value;
+};
+
+// C array overload
+template <typename T, size_t N>
+auto range_begin(const T (&arr)[N]) -> const T* {
+  return arr;
+}
+template <typename T, size_t N> auto range_end(const T (&arr)[N]) -> const T* {
+  return arr + N;
+}
+
+template <typename T, typename Enable = void>
+struct has_member_fn_begin_end_t : std::false_type {};
+
+template <typename T>
+struct has_member_fn_begin_end_t<T, void_t<decltype(*std::declval<T>().begin()),
+                                           decltype(std::declval<T>().end())>>
+    : std::true_type {};
+
+// Member function overloads.
+template <typename T>
+auto range_begin(T&& rng) -> decltype(static_cast<T&&>(rng).begin()) {
+  return static_cast<T&&>(rng).begin();
+}
+template <typename T>
+auto range_end(T&& rng) -> decltype(static_cast<T&&>(rng).end()) {
+  return static_cast<T&&>(rng).end();
+}
+
+// ADL overloads. Only participate in overload resolution if member functions
+// are not found.
+template <typename T>
+auto range_begin(T&& rng)
+    -> enable_if_t<!has_member_fn_begin_end_t<T&&>::value,
+                   decltype(begin(static_cast<T&&>(rng)))> {
+  return begin(static_cast<T&&>(rng));
+}
+template <typename T>
+auto range_end(T&& rng) -> enable_if_t<!has_member_fn_begin_end_t<T&&>::value,
+                                       decltype(end(static_cast<T&&>(rng)))> {
+  return end(static_cast<T&&>(rng));
+}
+
+template <typename T, typename Enable = void>
+struct has_const_begin_end : std::false_type {};
+template <typename T, typename Enable = void>
+struct has_mutable_begin_end : std::false_type {};
+
+template <typename T>
+struct has_const_begin_end<
+    T, void_t<decltype(*detail::range_begin(
+                  std::declval<const remove_cvref_t<T>&>())),
+              decltype(detail::range_end(
+                  std::declval<const remove_cvref_t<T>&>()))>>
+    : std::true_type {};
+
+template <typename T>
+struct has_mutable_begin_end<
+    T, void_t<decltype(*detail::range_begin(std::declval<T&>())),
+              decltype(detail::range_end(std::declval<T&>())),
+              // the extra int here is because older versions of MSVC don't
+              // SFINAE properly unless there are distinct types
+              int>> : std::true_type {};
+
+template <typename T, typename _ = void> struct is_range_ : std::false_type {};
+template <typename T>
+struct is_range_<T, void>
+    : std::integral_constant<bool, (has_const_begin_end<T>::value ||
+                                    has_mutable_begin_end<T>::value)> {};
+
+// tuple_size and tuple_element check.
+template <typename T> class is_tuple_like_ {
+  template <typename U, typename V = typename std::remove_cv<U>::type>
+  static auto check(U* p) -> decltype(std::tuple_size<V>::value, 0);
+  template <typename> static void check(...);
+
+ public:
+  static constexpr bool value =
+      !std::is_void<decltype(check<T>(nullptr))>::value;
+};
+
+// Check for integer_sequence
+#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VERSION >= 1900
+template <typename T, T... N>
+using integer_sequence = std::integer_sequence<T, N...>;
+template <size_t... N> using index_sequence = std::index_sequence<N...>;
+template <size_t N> using make_index_sequence = std::make_index_sequence<N>;
+#else
+template <typename T, T... N> struct integer_sequence {
+  using value_type = T;
+
+  static FMT_CONSTEXPR auto size() -> size_t { return sizeof...(N); }
+};
+
+template <size_t... N> using index_sequence = integer_sequence<size_t, N...>;
+
+template <typename T, size_t N, T... Ns>
+struct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> {};
+template <typename T, T... Ns>
+struct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> {};
+
+template <size_t N>
+using make_index_sequence = make_integer_sequence<size_t, N>;
+#endif
+
+template <typename T>
+using tuple_index_sequence = make_index_sequence<std::tuple_size<T>::value>;
+
+template <typename T, typename C, bool = is_tuple_like_<T>::value>
+class is_tuple_formattable_ {
+ public:
+  static constexpr bool value = false;
+};
+template <typename T, typename C> class is_tuple_formattable_<T, C, true> {
+  template <size_t... Is>
+  static auto all_true(index_sequence<Is...>,
+                       integer_sequence<bool, (Is >= 0)...>) -> std::true_type;
+  static auto all_true(...) -> std::false_type;
+
+  template <size_t... Is>
+  static auto check(index_sequence<Is...>) -> decltype(all_true(
+      index_sequence<Is...>{},
+      integer_sequence<bool,
+                       (is_formattable<typename std::tuple_element<Is, T>::type,
+                                       C>::value)...>{}));
+
+ public:
+  static constexpr bool value =
+      decltype(check(tuple_index_sequence<T>{}))::value;
+};
+
+template <typename Tuple, typename F, size_t... Is>
+FMT_CONSTEXPR void for_each(index_sequence<Is...>, Tuple&& t, F&& f) {
+  using std::get;
+  // Using a free function get<Is>(Tuple) now.
+  const int unused[] = {0, ((void)f(get<Is>(t)), 0)...};
+  ignore_unused(unused);
+}
+
+template <typename Tuple, typename F>
+FMT_CONSTEXPR void for_each(Tuple&& t, F&& f) {
+  for_each(tuple_index_sequence<remove_cvref_t<Tuple>>(),
+           std::forward<Tuple>(t), std::forward<F>(f));
+}
+
+template <typename Tuple1, typename Tuple2, typename F, size_t... Is>
+void for_each2(index_sequence<Is...>, Tuple1&& t1, Tuple2&& t2, F&& f) {
+  using std::get;
+  const int unused[] = {0, ((void)f(get<Is>(t1), get<Is>(t2)), 0)...};
+  ignore_unused(unused);
+}
+
+template <typename Tuple1, typename Tuple2, typename F>
+void for_each2(Tuple1&& t1, Tuple2&& t2, F&& f) {
+  for_each2(tuple_index_sequence<remove_cvref_t<Tuple1>>(),
+            std::forward<Tuple1>(t1), std::forward<Tuple2>(t2),
+            std::forward<F>(f));
+}
+
+namespace tuple {
+// Workaround a bug in MSVC 2019 (v140).
+template <typename Char, typename... T>
+using result_t = std::tuple<formatter<remove_cvref_t<T>, Char>...>;
+
+using std::get;
+template <typename Tuple, typename Char, size_t... Is>
+auto get_formatters(index_sequence<Is...>)
+    -> result_t<Char, decltype(get<Is>(std::declval<Tuple>()))...>;
+}  // namespace tuple
+
+#if FMT_MSC_VERSION && FMT_MSC_VERSION < 1920
+// Older MSVC doesn't get the reference type correctly for arrays.
+template <typename R> struct range_reference_type_impl {
+  using type = decltype(*detail::range_begin(std::declval<R&>()));
+};
+
+template <typename T, size_t N> struct range_reference_type_impl<T[N]> {
+  using type = T&;
+};
+
+template <typename T>
+using range_reference_type = typename range_reference_type_impl<T>::type;
+#else
+template <typename Range>
+using range_reference_type =
+    decltype(*detail::range_begin(std::declval<Range&>()));
+#endif
+
+// We don't use the Range's value_type for anything, but we do need the Range's
+// reference type, with cv-ref stripped.
+template <typename Range>
+using uncvref_type = remove_cvref_t<range_reference_type<Range>>;
+
+template <typename Formatter>
+FMT_CONSTEXPR auto maybe_set_debug_format(Formatter& f, bool set)
+    -> decltype(f.set_debug_format(set)) {
+  f.set_debug_format(set);
+}
+template <typename Formatter>
+FMT_CONSTEXPR void maybe_set_debug_format(Formatter&, ...) {}
+
+template <typename T>
+struct range_format_kind_
+    : std::integral_constant<range_format,
+                             std::is_same<uncvref_type<T>, T>::value
+                                 ? range_format::disabled
+                             : is_map<T>::value ? range_format::map
+                             : is_set<T>::value ? range_format::set
+                                                : range_format::sequence> {};
+
+template <range_format K>
+using range_format_constant = std::integral_constant<range_format, K>;
+
+// These are not generic lambdas for compatibility with C++11.
+template <typename Char> struct parse_empty_specs {
+  template <typename Formatter> FMT_CONSTEXPR void operator()(Formatter& f) {
+    f.parse(ctx);
+    detail::maybe_set_debug_format(f, true);
+  }
+  parse_context<Char>& ctx;
+};
+template <typename FormatContext> struct format_tuple_element {
+  using char_type = typename FormatContext::char_type;
+
+  template <typename T>
+  void operator()(const formatter<T, char_type>& f, const T& v) {
+    if (i > 0) ctx.advance_to(detail::copy<char_type>(separator, ctx.out()));
+    ctx.advance_to(f.format(v, ctx));
+    ++i;
+  }
+
+  int i;
+  FormatContext& ctx;
+  basic_string_view<char_type> separator;
+};
+
+}  // namespace detail
+
+FMT_EXPORT
+template <typename T> struct is_tuple_like {
+  static constexpr bool value =
+      detail::is_tuple_like_<T>::value && !detail::is_range_<T>::value;
+};
+
+FMT_EXPORT
+template <typename T, typename C> struct is_tuple_formattable {
+  static constexpr bool value = detail::is_tuple_formattable_<T, C>::value;
+};
+
+template <typename Tuple, typename Char>
+struct formatter<Tuple, Char,
+                 enable_if_t<fmt::is_tuple_like<Tuple>::value &&
+                             fmt::is_tuple_formattable<Tuple, Char>::value>> {
+ private:
+  decltype(detail::tuple::get_formatters<Tuple, Char>(
+      detail::tuple_index_sequence<Tuple>())) formatters_;
+
+  basic_string_view<Char> separator_ = detail::string_literal<Char, ',', ' '>{};
+  basic_string_view<Char> opening_bracket_ =
+      detail::string_literal<Char, '('>{};
+  basic_string_view<Char> closing_bracket_ =
+      detail::string_literal<Char, ')'>{};
+
+ public:
+  FMT_CONSTEXPR formatter() {}
+
+  FMT_CONSTEXPR void set_separator(basic_string_view<Char> sep) {
+    separator_ = sep;
+  }
+
+  FMT_CONSTEXPR void set_brackets(basic_string_view<Char> open,
+                                  basic_string_view<Char> close) {
+    opening_bracket_ = open;
+    closing_bracket_ = close;
+  }
+
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    auto it = ctx.begin();
+    auto end = ctx.end();
+    if (it != end && detail::to_ascii(*it) == 'n') {
+      ++it;
+      set_brackets({}, {});
+      set_separator({});
+    }
+    if (it != end && *it != '}') report_error("invalid format specifier");
+    ctx.advance_to(it);
+    detail::for_each(formatters_, detail::parse_empty_specs<Char>{ctx});
+    return it;
+  }
+
+  template <typename FormatContext>
+  auto format(const Tuple& value, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    ctx.advance_to(detail::copy<Char>(opening_bracket_, ctx.out()));
+    detail::for_each2(
+        formatters_, value,
+        detail::format_tuple_element<FormatContext>{0, ctx, separator_});
+    return detail::copy<Char>(closing_bracket_, ctx.out());
+  }
+};
+
+FMT_EXPORT
+template <typename T, typename Char> struct is_range {
+  static constexpr bool value =
+      detail::is_range_<T>::value && !detail::has_to_string_view<T>::value;
+};
+
+namespace detail {
+
+template <typename Char, typename Element>
+using range_formatter_type = formatter<remove_cvref_t<Element>, Char>;
+
+template <typename R>
+using maybe_const_range =
+    conditional_t<has_const_begin_end<R>::value, const R, R>;
+
+template <typename R, typename Char>
+struct is_formattable_delayed
+    : is_formattable<uncvref_type<maybe_const_range<R>>, Char> {};
+}  // namespace detail
+
+template <typename...> struct conjunction : std::true_type {};
+template <typename P> struct conjunction<P> : P {};
+template <typename P1, typename... Pn>
+struct conjunction<P1, Pn...>
+    : conditional_t<bool(P1::value), conjunction<Pn...>, P1> {};
+
+FMT_EXPORT
+template <typename T, typename Char, typename Enable = void>
+struct range_formatter;
+
+template <typename T, typename Char>
+struct range_formatter<
+    T, Char,
+    enable_if_t<conjunction<std::is_same<T, remove_cvref_t<T>>,
+                            is_formattable<T, Char>>::value>> {
+ private:
+  detail::range_formatter_type<Char, T> underlying_;
+  basic_string_view<Char> separator_ = detail::string_literal<Char, ',', ' '>{};
+  basic_string_view<Char> opening_bracket_ =
+      detail::string_literal<Char, '['>{};
+  basic_string_view<Char> closing_bracket_ =
+      detail::string_literal<Char, ']'>{};
+  bool is_debug = false;
+
+  template <typename Output, typename It, typename Sentinel, typename U = T,
+            FMT_ENABLE_IF(std::is_same<U, Char>::value)>
+  auto write_debug_string(Output& out, It it, Sentinel end) const -> Output {
+    auto buf = basic_memory_buffer<Char>();
+    for (; it != end; ++it) buf.push_back(*it);
+    auto specs = format_specs();
+    specs.set_type(presentation_type::debug);
+    return detail::write<Char>(
+        out, basic_string_view<Char>(buf.data(), buf.size()), specs);
+  }
+
+  template <typename Output, typename It, typename Sentinel, typename U = T,
+            FMT_ENABLE_IF(!std::is_same<U, Char>::value)>
+  auto write_debug_string(Output& out, It, Sentinel) const -> Output {
+    return out;
+  }
+
+ public:
+  FMT_CONSTEXPR range_formatter() {}
+
+  FMT_CONSTEXPR auto underlying() -> detail::range_formatter_type<Char, T>& {
+    return underlying_;
+  }
+
+  FMT_CONSTEXPR void set_separator(basic_string_view<Char> sep) {
+    separator_ = sep;
+  }
+
+  FMT_CONSTEXPR void set_brackets(basic_string_view<Char> open,
+                                  basic_string_view<Char> close) {
+    opening_bracket_ = open;
+    closing_bracket_ = close;
+  }
+
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    auto it = ctx.begin();
+    auto end = ctx.end();
+    detail::maybe_set_debug_format(underlying_, true);
+    if (it == end) return underlying_.parse(ctx);
+
+    switch (detail::to_ascii(*it)) {
+    case 'n':
+      set_brackets({}, {});
+      ++it;
+      break;
+    case '?':
+      is_debug = true;
+      set_brackets({}, {});
+      ++it;
+      if (it == end || *it != 's') report_error("invalid format specifier");
+      FMT_FALLTHROUGH;
+    case 's':
+      if (!std::is_same<T, Char>::value)
+        report_error("invalid format specifier");
+      if (!is_debug) {
+        set_brackets(detail::string_literal<Char, '"'>{},
+                     detail::string_literal<Char, '"'>{});
+        set_separator({});
+        detail::maybe_set_debug_format(underlying_, false);
+      }
+      ++it;
+      return it;
+    }
+
+    if (it != end && *it != '}') {
+      if (*it != ':') report_error("invalid format specifier");
+      detail::maybe_set_debug_format(underlying_, false);
+      ++it;
+    }
+
+    ctx.advance_to(it);
+    return underlying_.parse(ctx);
+  }
+
+  template <typename R, typename FormatContext>
+  auto format(R&& range, FormatContext& ctx) const -> decltype(ctx.out()) {
+    auto out = ctx.out();
+    auto it = detail::range_begin(range);
+    auto end = detail::range_end(range);
+    if (is_debug) return write_debug_string(out, std::move(it), end);
+
+    out = detail::copy<Char>(opening_bracket_, out);
+    int i = 0;
+    for (; it != end; ++it) {
+      if (i > 0) out = detail::copy<Char>(separator_, out);
+      ctx.advance_to(out);
+      auto&& item = *it;  // Need an lvalue
+      out = underlying_.format(item, ctx);
+      ++i;
+    }
+    out = detail::copy<Char>(closing_bracket_, out);
+    return out;
+  }
+};
+
+FMT_EXPORT
+template <typename T, typename Char, typename Enable = void>
+struct range_format_kind
+    : conditional_t<
+          is_range<T, Char>::value, detail::range_format_kind_<T>,
+          std::integral_constant<range_format, range_format::disabled>> {};
+
+template <typename R, typename Char>
+struct formatter<
+    R, Char,
+    enable_if_t<conjunction<
+        bool_constant<
+            range_format_kind<R, Char>::value != range_format::disabled &&
+            range_format_kind<R, Char>::value != range_format::map &&
+            range_format_kind<R, Char>::value != range_format::string &&
+            range_format_kind<R, Char>::value != range_format::debug_string>,
+        detail::is_formattable_delayed<R, Char>>::value>> {
+ private:
+  using range_type = detail::maybe_const_range<R>;
+  range_formatter<detail::uncvref_type<range_type>, Char> range_formatter_;
+
+ public:
+  using nonlocking = void;
+
+  FMT_CONSTEXPR formatter() {
+    if (detail::const_check(range_format_kind<R, Char>::value !=
+                            range_format::set))
+      return;
+    range_formatter_.set_brackets(detail::string_literal<Char, '{'>{},
+                                  detail::string_literal<Char, '}'>{});
+  }
+
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    return range_formatter_.parse(ctx);
+  }
+
+  template <typename FormatContext>
+  auto format(range_type& range, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    return range_formatter_.format(range, ctx);
+  }
+};
+
+// A map formatter.
+template <typename R, typename Char>
+struct formatter<
+    R, Char,
+    enable_if_t<conjunction<
+        bool_constant<range_format_kind<R, Char>::value == range_format::map>,
+        detail::is_formattable_delayed<R, Char>>::value>> {
+ private:
+  using map_type = detail::maybe_const_range<R>;
+  using element_type = detail::uncvref_type<map_type>;
+
+  decltype(detail::tuple::get_formatters<element_type, Char>(
+      detail::tuple_index_sequence<element_type>())) formatters_;
+  bool no_delimiters_ = false;
+
+ public:
+  FMT_CONSTEXPR formatter() {}
+
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    auto it = ctx.begin();
+    auto end = ctx.end();
+    if (it != end) {
+      if (detail::to_ascii(*it) == 'n') {
+        no_delimiters_ = true;
+        ++it;
+      }
+      if (it != end && *it != '}') {
+        if (*it != ':') report_error("invalid format specifier");
+        ++it;
+      }
+      ctx.advance_to(it);
+    }
+    detail::for_each(formatters_, detail::parse_empty_specs<Char>{ctx});
+    return it;
+  }
+
+  template <typename FormatContext>
+  auto format(map_type& map, FormatContext& ctx) const -> decltype(ctx.out()) {
+    auto out = ctx.out();
+    basic_string_view<Char> open = detail::string_literal<Char, '{'>{};
+    if (!no_delimiters_) out = detail::copy<Char>(open, out);
+    int i = 0;
+    basic_string_view<Char> sep = detail::string_literal<Char, ',', ' '>{};
+    for (auto&& value : map) {
+      if (i > 0) out = detail::copy<Char>(sep, out);
+      ctx.advance_to(out);
+      detail::for_each2(formatters_, value,
+                        detail::format_tuple_element<FormatContext>{
+                            0, ctx, detail::string_literal<Char, ':', ' '>{}});
+      ++i;
+    }
+    basic_string_view<Char> close = detail::string_literal<Char, '}'>{};
+    if (!no_delimiters_) out = detail::copy<Char>(close, out);
+    return out;
+  }
+};
+
+// A (debug_)string formatter.
+template <typename R, typename Char>
+struct formatter<
+    R, Char,
+    enable_if_t<range_format_kind<R, Char>::value == range_format::string ||
+                range_format_kind<R, Char>::value ==
+                    range_format::debug_string>> {
+ private:
+  using range_type = detail::maybe_const_range<R>;
+  using string_type =
+      conditional_t<std::is_constructible<
+                        detail::std_string_view<Char>,
+                        decltype(detail::range_begin(std::declval<R>())),
+                        decltype(detail::range_end(std::declval<R>()))>::value,
+                    detail::std_string_view<Char>, std::basic_string<Char>>;
+
+  formatter<string_type, Char> underlying_;
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    return underlying_.parse(ctx);
+  }
+
+  template <typename FormatContext>
+  auto format(range_type& range, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    auto out = ctx.out();
+    if (detail::const_check(range_format_kind<R, Char>::value ==
+                            range_format::debug_string))
+      *out++ = '"';
+    out = underlying_.format(
+        string_type{detail::range_begin(range), detail::range_end(range)}, ctx);
+    if (detail::const_check(range_format_kind<R, Char>::value ==
+                            range_format::debug_string))
+      *out++ = '"';
+    return out;
+  }
+};
+
+template <typename It, typename Sentinel, typename Char = char>
+struct join_view : detail::view {
+  It begin;
+  Sentinel end;
+  basic_string_view<Char> sep;
+
+  join_view(It b, Sentinel e, basic_string_view<Char> s)
+      : begin(std::move(b)), end(e), sep(s) {}
+};
+
+template <typename It, typename Sentinel, typename Char>
+struct formatter<join_view<It, Sentinel, Char>, Char> {
+ private:
+  using value_type =
+#ifdef __cpp_lib_ranges
+      std::iter_value_t<It>;
+#else
+      typename std::iterator_traits<It>::value_type;
+#endif
+  formatter<remove_cvref_t<value_type>, Char> value_formatter_;
+
+  using view = conditional_t<std::is_copy_constructible<It>::value,
+                             const join_view<It, Sentinel, Char>,
+                             join_view<It, Sentinel, Char>>;
+
+ public:
+  using nonlocking = void;
+
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    return value_formatter_.parse(ctx);
+  }
+
+  template <typename FormatContext>
+  auto format(view& value, FormatContext& ctx) const -> decltype(ctx.out()) {
+    using iter =
+        conditional_t<std::is_copy_constructible<view>::value, It, It&>;
+    iter it = value.begin;
+    auto out = ctx.out();
+    if (it == value.end) return out;
+    out = value_formatter_.format(*it, ctx);
+    ++it;
+    while (it != value.end) {
+      out = detail::copy<Char>(value.sep.begin(), value.sep.end(), out);
+      ctx.advance_to(out);
+      out = value_formatter_.format(*it, ctx);
+      ++it;
+    }
+    return out;
+  }
+};
+
+FMT_EXPORT
+template <typename Tuple, typename Char> struct tuple_join_view : detail::view {
+  const Tuple& tuple;
+  basic_string_view<Char> sep;
+
+  tuple_join_view(const Tuple& t, basic_string_view<Char> s)
+      : tuple(t), sep{s} {}
+};
+
+// Define FMT_TUPLE_JOIN_SPECIFIERS to enable experimental format specifiers
+// support in tuple_join. It is disabled by default because of issues with
+// the dynamic width and precision.
+#ifndef FMT_TUPLE_JOIN_SPECIFIERS
+#  define FMT_TUPLE_JOIN_SPECIFIERS 0
+#endif
+
+template <typename Tuple, typename Char>
+struct formatter<tuple_join_view<Tuple, Char>, Char,
+                 enable_if_t<is_tuple_like<Tuple>::value>> {
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    return do_parse(ctx, std::tuple_size<Tuple>());
+  }
+
+  template <typename FormatContext>
+  auto format(const tuple_join_view<Tuple, Char>& value,
+              FormatContext& ctx) const -> typename FormatContext::iterator {
+    return do_format(value, ctx, std::tuple_size<Tuple>());
+  }
+
+ private:
+  decltype(detail::tuple::get_formatters<Tuple, Char>(
+      detail::tuple_index_sequence<Tuple>())) formatters_;
+
+  FMT_CONSTEXPR auto do_parse(parse_context<Char>& ctx,
+                              std::integral_constant<size_t, 0>)
+      -> const Char* {
+    return ctx.begin();
+  }
+
+  template <size_t N>
+  FMT_CONSTEXPR auto do_parse(parse_context<Char>& ctx,
+                              std::integral_constant<size_t, N>)
+      -> const Char* {
+    auto end = ctx.begin();
+#if FMT_TUPLE_JOIN_SPECIFIERS
+    end = std::get<std::tuple_size<Tuple>::value - N>(formatters_).parse(ctx);
+    if (N > 1) {
+      auto end1 = do_parse(ctx, std::integral_constant<size_t, N - 1>());
+      if (end != end1)
+        report_error("incompatible format specs for tuple elements");
+    }
+#endif
+    return end;
+  }
+
+  template <typename FormatContext>
+  auto do_format(const tuple_join_view<Tuple, Char>&, FormatContext& ctx,
+                 std::integral_constant<size_t, 0>) const ->
+      typename FormatContext::iterator {
+    return ctx.out();
+  }
+
+  template <typename FormatContext, size_t N>
+  auto do_format(const tuple_join_view<Tuple, Char>& value, FormatContext& ctx,
+                 std::integral_constant<size_t, N>) const ->
+      typename FormatContext::iterator {
+    using std::get;
+    auto out =
+        std::get<std::tuple_size<Tuple>::value - N>(formatters_)
+            .format(get<std::tuple_size<Tuple>::value - N>(value.tuple), ctx);
+    if (N <= 1) return out;
+    out = detail::copy<Char>(value.sep, out);
+    ctx.advance_to(out);
+    return do_format(value, ctx, std::integral_constant<size_t, N - 1>());
+  }
+};
+
+namespace detail {
+// Check if T has an interface like a container adaptor (e.g. std::stack,
+// std::queue, std::priority_queue).
+template <typename T> class is_container_adaptor_like {
+  template <typename U> static auto check(U* p) -> typename U::container_type;
+  template <typename> static void check(...);
+
+ public:
+  static constexpr bool value =
+      !std::is_void<decltype(check<T>(nullptr))>::value;
+};
+
+template <typename Container> struct all {
+  const Container& c;
+  auto begin() const -> typename Container::const_iterator { return c.begin(); }
+  auto end() const -> typename Container::const_iterator { return c.end(); }
+};
+}  // namespace detail
+
+template <typename T, typename Char>
+struct formatter<
+    T, Char,
+    enable_if_t<conjunction<detail::is_container_adaptor_like<T>,
+                            bool_constant<range_format_kind<T, Char>::value ==
+                                          range_format::disabled>>::value>>
+    : formatter<detail::all<typename T::container_type>, Char> {
+  using all = detail::all<typename T::container_type>;
+  template <typename FormatContext>
+  auto format(const T& value, FormatContext& ctx) const -> decltype(ctx.out()) {
+    struct getter : T {
+      static auto get(const T& v) -> all {
+        return {v.*(&getter::c)};  // Access c through the derived class.
+      }
+    };
+    return formatter<all>::format(getter::get(value), ctx);
+  }
+};
+
+FMT_BEGIN_EXPORT
+
+/// Returns a view that formats the iterator range `[begin, end)` with elements
+/// separated by `sep`.
+template <typename It, typename Sentinel>
+auto join(It begin, Sentinel end, string_view sep) -> join_view<It, Sentinel> {
+  return {std::move(begin), end, sep};
+}
+
+/**
+ * Returns a view that formats `range` with elements separated by `sep`.
+ *
+ * **Example**:
+ *
+ *     auto v = std::vector<int>{1, 2, 3};
+ *     fmt::print("{}", fmt::join(v, ", "));
+ *     // Output: 1, 2, 3
+ *
+ * `fmt::join` applies passed format specifiers to the range elements:
+ *
+ *     fmt::print("{:02}", fmt::join(v, ", "));
+ *     // Output: 01, 02, 03
+ */
+template <typename Range, FMT_ENABLE_IF(!is_tuple_like<Range>::value)>
+auto join(Range&& r, string_view sep)
+    -> join_view<decltype(detail::range_begin(r)),
+                 decltype(detail::range_end(r))> {
+  return {detail::range_begin(r), detail::range_end(r), sep};
+}
+
+/**
+ * Returns an object that formats `std::tuple` with elements separated by `sep`.
+ *
+ * **Example**:
+ *
+ *     auto t = std::tuple<int, char>{1, 'a'};
+ *     fmt::print("{}", fmt::join(t, ", "));
+ *     // Output: 1, a
+ */
+template <typename Tuple, FMT_ENABLE_IF(is_tuple_like<Tuple>::value)>
+FMT_CONSTEXPR auto join(const Tuple& tuple, string_view sep)
+    -> tuple_join_view<Tuple, char> {
+  return {tuple, sep};
+}
+
+/**
+ * Returns an object that formats `std::initializer_list` with elements
+ * separated by `sep`.
+ *
+ * **Example**:
+ *
+ *     fmt::print("{}", fmt::join({1, 2, 3}, ", "));
+ *     // Output: "1, 2, 3"
+ */
+template <typename T>
+auto join(std::initializer_list<T> list, string_view sep)
+    -> join_view<const T*, const T*> {
+  return join(std::begin(list), std::end(list), sep);
+}
+
+FMT_END_EXPORT
+FMT_END_NAMESPACE
+
+#endif  // FMT_RANGES_H_

+ 707 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/std.h

@@ -0,0 +1,707 @@
+// Formatting library for C++ - formatters for standard library types
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_STD_H_
+#define FMT_STD_H_
+
+#include "format.h"
+#include "ostream.h"
+
+#ifndef FMT_MODULE
+#  include <atomic>
+#  include <bitset>
+#  include <complex>
+#  include <exception>
+#  include <functional>  // std::reference_wrapper
+#  include <memory>
+#  include <thread>
+#  include <type_traits>
+#  include <typeinfo>  // std::type_info
+#  include <utility>   // std::make_index_sequence
+
+// Check FMT_CPLUSPLUS to suppress a bogus warning in MSVC.
+#  if FMT_CPLUSPLUS >= 201703L
+#    if FMT_HAS_INCLUDE(<filesystem>) && \
+        (!defined(FMT_CPP_LIB_FILESYSTEM) || FMT_CPP_LIB_FILESYSTEM != 0)
+#      include <filesystem>
+#    endif
+#    if FMT_HAS_INCLUDE(<variant>)
+#      include <variant>
+#    endif
+#    if FMT_HAS_INCLUDE(<optional>)
+#      include <optional>
+#    endif
+#  endif
+// Use > instead of >= in the version check because <source_location> may be
+// available after C++17 but before C++20 is marked as implemented.
+#  if FMT_CPLUSPLUS > 201703L && FMT_HAS_INCLUDE(<source_location>)
+#    include <source_location>
+#  endif
+#  if FMT_CPLUSPLUS > 202002L && FMT_HAS_INCLUDE(<expected>)
+#    include <expected>
+#  endif
+#endif  // FMT_MODULE
+
+#if FMT_HAS_INCLUDE(<version>)
+#  include <version>
+#endif
+
+// GCC 4 does not support FMT_HAS_INCLUDE.
+#if FMT_HAS_INCLUDE(<cxxabi.h>) || defined(__GLIBCXX__)
+#  include <cxxabi.h>
+// Android NDK with gabi++ library on some architectures does not implement
+// abi::__cxa_demangle().
+#  ifndef __GABIXX_CXXABI_H__
+#    define FMT_HAS_ABI_CXA_DEMANGLE
+#  endif
+#endif
+
+#ifdef FMT_CPP_LIB_FILESYSTEM
+// Use the provided definition.
+#elif defined(__cpp_lib_filesystem)
+#  define FMT_CPP_LIB_FILESYSTEM __cpp_lib_filesystem
+#else
+#  define FMT_CPP_LIB_FILESYSTEM 0
+#endif
+
+#ifdef FMT_CPP_LIB_VARIANT
+// Use the provided definition.
+#elif defined(__cpp_lib_variant)
+#  define FMT_CPP_LIB_VARIANT __cpp_lib_variant
+#else
+#  define FMT_CPP_LIB_VARIANT 0
+#endif
+
+FMT_BEGIN_NAMESPACE
+namespace detail {
+
+#if FMT_CPP_LIB_FILESYSTEM
+
+template <typename Char, typename PathChar>
+auto get_path_string(const std::filesystem::path& p,
+                     const std::basic_string<PathChar>& native) {
+  if constexpr (std::is_same_v<Char, char> && std::is_same_v<PathChar, wchar_t>)
+    return to_utf8<wchar_t>(native, to_utf8_error_policy::replace);
+  else
+    return p.string<Char>();
+}
+
+template <typename Char, typename PathChar>
+void write_escaped_path(basic_memory_buffer<Char>& quoted,
+                        const std::filesystem::path& p,
+                        const std::basic_string<PathChar>& native) {
+  if constexpr (std::is_same_v<Char, char> &&
+                std::is_same_v<PathChar, wchar_t>) {
+    auto buf = basic_memory_buffer<wchar_t>();
+    write_escaped_string<wchar_t>(std::back_inserter(buf), native);
+    bool valid = to_utf8<wchar_t>::convert(quoted, {buf.data(), buf.size()});
+    FMT_ASSERT(valid, "invalid utf16");
+  } else if constexpr (std::is_same_v<Char, PathChar>) {
+    write_escaped_string<std::filesystem::path::value_type>(
+        std::back_inserter(quoted), native);
+  } else {
+    write_escaped_string<Char>(std::back_inserter(quoted), p.string<Char>());
+  }
+}
+
+#endif  // FMT_CPP_LIB_FILESYSTEM
+
+#if defined(__cpp_lib_expected) || FMT_CPP_LIB_VARIANT
+template <typename Char, typename OutputIt, typename T>
+auto write_escaped_alternative(OutputIt out, const T& v) -> OutputIt {
+  if constexpr (has_to_string_view<T>::value)
+    return write_escaped_string<Char>(out, detail::to_string_view(v));
+  if constexpr (std::is_same_v<T, Char>) return write_escaped_char(out, v);
+  return write<Char>(out, v);
+}
+#endif
+
+#if FMT_CPP_LIB_VARIANT
+
+template <typename> struct is_variant_like_ : std::false_type {};
+template <typename... Types>
+struct is_variant_like_<std::variant<Types...>> : std::true_type {};
+
+template <typename Variant, typename Char> class is_variant_formattable {
+  template <size_t... Is>
+  static auto check(std::index_sequence<Is...>) -> std::conjunction<
+      is_formattable<std::variant_alternative_t<Is, Variant>, Char>...>;
+
+ public:
+  static constexpr bool value = decltype(check(
+      std::make_index_sequence<std::variant_size<Variant>::value>()))::value;
+};
+
+#endif  // FMT_CPP_LIB_VARIANT
+
+#if FMT_USE_RTTI
+
+template <typename OutputIt>
+auto write_demangled_name(OutputIt out, const std::type_info& ti) -> OutputIt {
+#  ifdef FMT_HAS_ABI_CXA_DEMANGLE
+  int status = 0;
+  size_t size = 0;
+  std::unique_ptr<char, void (*)(void*)> demangled_name_ptr(
+      abi::__cxa_demangle(ti.name(), nullptr, &size, &status), &std::free);
+
+  string_view demangled_name_view;
+  if (demangled_name_ptr) {
+    demangled_name_view = demangled_name_ptr.get();
+
+    // Normalization of stdlib inline namespace names.
+    // libc++ inline namespaces.
+    //  std::__1::*       -> std::*
+    //  std::__1::__fs::* -> std::*
+    // libstdc++ inline namespaces.
+    //  std::__cxx11::*             -> std::*
+    //  std::filesystem::__cxx11::* -> std::filesystem::*
+    if (demangled_name_view.starts_with("std::")) {
+      char* begin = demangled_name_ptr.get();
+      char* to = begin + 5;  // std::
+      for (char *from = to, *end = begin + demangled_name_view.size();
+           from < end;) {
+        // This is safe, because demangled_name is NUL-terminated.
+        if (from[0] == '_' && from[1] == '_') {
+          char* next = from + 1;
+          while (next < end && *next != ':') next++;
+          if (next[0] == ':' && next[1] == ':') {
+            from = next + 2;
+            continue;
+          }
+        }
+        *to++ = *from++;
+      }
+      demangled_name_view = {begin, detail::to_unsigned(to - begin)};
+    }
+  } else {
+    demangled_name_view = string_view(ti.name());
+  }
+  return detail::write_bytes<char>(out, demangled_name_view);
+#  elif FMT_MSC_VERSION
+  const string_view demangled_name(ti.name());
+  for (size_t i = 0; i < demangled_name.size(); ++i) {
+    auto sub = demangled_name;
+    sub.remove_prefix(i);
+    if (sub.starts_with("enum ")) {
+      i += 4;
+      continue;
+    }
+    if (sub.starts_with("class ") || sub.starts_with("union ")) {
+      i += 5;
+      continue;
+    }
+    if (sub.starts_with("struct ")) {
+      i += 6;
+      continue;
+    }
+    if (*sub.begin() != ' ') *out++ = *sub.begin();
+  }
+  return out;
+#  else
+  return detail::write_bytes<char>(out, string_view(ti.name()));
+#  endif
+}
+
+#endif  // FMT_USE_RTTI
+
+template <typename T, typename Enable = void>
+struct has_flip : std::false_type {};
+
+template <typename T>
+struct has_flip<T, void_t<decltype(std::declval<T>().flip())>>
+    : std::true_type {};
+
+template <typename T> struct is_bit_reference_like {
+  static constexpr bool value = std::is_convertible<T, bool>::value &&
+                                std::is_nothrow_assignable<T, bool>::value &&
+                                has_flip<T>::value;
+};
+
+// Workaround for libc++ incompatibility with C++ standard.
+// According to the Standard, `bitset::operator[] const` returns bool.
+#if defined(_LIBCPP_VERSION) && !defined(FMT_IMPORT_STD)
+template <typename C>
+struct is_bit_reference_like<std::__bit_const_reference<C>> {
+  static constexpr bool value = true;
+};
+#endif
+
+template <typename T, typename Enable = void>
+struct has_format_as : std::false_type {};
+template <typename T>
+struct has_format_as<T, void_t<decltype(format_as(std::declval<const T&>()))>>
+    : std::true_type {};
+
+template <typename T, typename Enable = void>
+struct has_format_as_member : std::false_type {};
+template <typename T>
+struct has_format_as_member<
+    T, void_t<decltype(formatter<T>::format_as(std::declval<const T&>()))>>
+    : std::true_type {};
+
+}  // namespace detail
+
+template <typename T, typename Deleter>
+auto ptr(const std::unique_ptr<T, Deleter>& p) -> const void* {
+  return p.get();
+}
+template <typename T> auto ptr(const std::shared_ptr<T>& p) -> const void* {
+  return p.get();
+}
+
+#if FMT_CPP_LIB_FILESYSTEM
+
+class path : public std::filesystem::path {
+ public:
+  auto display_string() const -> std::string {
+    const std::filesystem::path& base = *this;
+    return fmt::format(FMT_STRING("{}"), base);
+  }
+  auto system_string() const -> std::string { return string(); }
+
+  auto generic_display_string() const -> std::string {
+    const std::filesystem::path& base = *this;
+    return fmt::format(FMT_STRING("{:g}"), base);
+  }
+  auto generic_system_string() const -> std::string { return generic_string(); }
+};
+
+template <typename Char> struct formatter<std::filesystem::path, Char> {
+ private:
+  format_specs specs_;
+  detail::arg_ref<Char> width_ref_;
+  bool debug_ = false;
+  char path_type_ = 0;
+
+ public:
+  FMT_CONSTEXPR void set_debug_format(bool set = true) { debug_ = set; }
+
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) {
+    auto it = ctx.begin(), end = ctx.end();
+    if (it == end) return it;
+
+    it = detail::parse_align(it, end, specs_);
+    if (it == end) return it;
+
+    Char c = *it;
+    if ((c >= '0' && c <= '9') || c == '{')
+      it = detail::parse_width(it, end, specs_, width_ref_, ctx);
+    if (it != end && *it == '?') {
+      debug_ = true;
+      ++it;
+    }
+    if (it != end && (*it == 'g')) path_type_ = detail::to_ascii(*it++);
+    return it;
+  }
+
+  template <typename FormatContext>
+  auto format(const std::filesystem::path& p, FormatContext& ctx) const {
+    auto specs = specs_;
+    auto path_string =
+        !path_type_ ? p.native()
+                    : p.generic_string<std::filesystem::path::value_type>();
+
+    detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,
+                                ctx);
+    if (!debug_) {
+      auto s = detail::get_path_string<Char>(p, path_string);
+      return detail::write(ctx.out(), basic_string_view<Char>(s), specs);
+    }
+    auto quoted = basic_memory_buffer<Char>();
+    detail::write_escaped_path(quoted, p, path_string);
+    return detail::write(ctx.out(),
+                         basic_string_view<Char>(quoted.data(), quoted.size()),
+                         specs);
+  }
+};
+
+#endif  // FMT_CPP_LIB_FILESYSTEM
+
+template <size_t N, typename Char>
+struct formatter<std::bitset<N>, Char>
+    : nested_formatter<basic_string_view<Char>, Char> {
+ private:
+  // This is a functor because C++11 doesn't support generic lambdas.
+  struct writer {
+    const std::bitset<N>& bs;
+
+    template <typename OutputIt>
+    FMT_CONSTEXPR auto operator()(OutputIt out) -> OutputIt {
+      for (auto pos = N; pos > 0; --pos)
+        out = detail::write<Char>(out, bs[pos - 1] ? Char('1') : Char('0'));
+      return out;
+    }
+  };
+
+ public:
+  template <typename FormatContext>
+  auto format(const std::bitset<N>& bs, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    return this->write_padded(ctx, writer{bs});
+  }
+};
+
+template <typename Char>
+struct formatter<std::thread::id, Char> : basic_ostream_formatter<Char> {};
+
+#ifdef __cpp_lib_optional
+template <typename T, typename Char>
+struct formatter<std::optional<T>, Char,
+                 std::enable_if_t<is_formattable<T, Char>::value>> {
+ private:
+  formatter<T, Char> underlying_;
+  static constexpr basic_string_view<Char> optional =
+      detail::string_literal<Char, 'o', 'p', 't', 'i', 'o', 'n', 'a', 'l',
+                             '('>{};
+  static constexpr basic_string_view<Char> none =
+      detail::string_literal<Char, 'n', 'o', 'n', 'e'>{};
+
+  template <class U>
+  FMT_CONSTEXPR static auto maybe_set_debug_format(U& u, bool set)
+      -> decltype(u.set_debug_format(set)) {
+    u.set_debug_format(set);
+  }
+
+  template <class U>
+  FMT_CONSTEXPR static void maybe_set_debug_format(U&, ...) {}
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) {
+    maybe_set_debug_format(underlying_, true);
+    return underlying_.parse(ctx);
+  }
+
+  template <typename FormatContext>
+  auto format(const std::optional<T>& opt, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    if (!opt) return detail::write<Char>(ctx.out(), none);
+
+    auto out = ctx.out();
+    out = detail::write<Char>(out, optional);
+    ctx.advance_to(out);
+    out = underlying_.format(*opt, ctx);
+    return detail::write(out, ')');
+  }
+};
+#endif  // __cpp_lib_optional
+
+#ifdef __cpp_lib_expected
+template <typename T, typename E, typename Char>
+struct formatter<std::expected<T, E>, Char,
+                 std::enable_if_t<(std::is_void<T>::value ||
+                                   is_formattable<T, Char>::value) &&
+                                  is_formattable<E, Char>::value>> {
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    return ctx.begin();
+  }
+
+  template <typename FormatContext>
+  auto format(const std::expected<T, E>& value, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    auto out = ctx.out();
+
+    if (value.has_value()) {
+      out = detail::write<Char>(out, "expected(");
+      if constexpr (!std::is_void<T>::value)
+        out = detail::write_escaped_alternative<Char>(out, *value);
+    } else {
+      out = detail::write<Char>(out, "unexpected(");
+      out = detail::write_escaped_alternative<Char>(out, value.error());
+    }
+    *out++ = ')';
+    return out;
+  }
+};
+#endif  // __cpp_lib_expected
+
+#ifdef __cpp_lib_source_location
+template <> struct formatter<std::source_location> {
+  FMT_CONSTEXPR auto parse(parse_context<>& ctx) { return ctx.begin(); }
+
+  template <typename FormatContext>
+  auto format(const std::source_location& loc, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    auto out = ctx.out();
+    out = detail::write(out, loc.file_name());
+    out = detail::write(out, ':');
+    out = detail::write<char>(out, loc.line());
+    out = detail::write(out, ':');
+    out = detail::write<char>(out, loc.column());
+    out = detail::write(out, ": ");
+    out = detail::write(out, loc.function_name());
+    return out;
+  }
+};
+#endif
+
+#if FMT_CPP_LIB_VARIANT
+
+template <typename T> struct is_variant_like {
+  static constexpr bool value = detail::is_variant_like_<T>::value;
+};
+
+template <typename Char> struct formatter<std::monostate, Char> {
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    return ctx.begin();
+  }
+
+  template <typename FormatContext>
+  auto format(const std::monostate&, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    return detail::write<Char>(ctx.out(), "monostate");
+  }
+};
+
+template <typename Variant, typename Char>
+struct formatter<Variant, Char,
+                 std::enable_if_t<std::conjunction_v<
+                     is_variant_like<Variant>,
+                     detail::is_variant_formattable<Variant, Char>>>> {
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    return ctx.begin();
+  }
+
+  template <typename FormatContext>
+  auto format(const Variant& value, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    auto out = ctx.out();
+
+    out = detail::write<Char>(out, "variant(");
+    FMT_TRY {
+      std::visit(
+          [&](const auto& v) {
+            out = detail::write_escaped_alternative<Char>(out, v);
+          },
+          value);
+    }
+    FMT_CATCH(const std::bad_variant_access&) {
+      detail::write<Char>(out, "valueless by exception");
+    }
+    *out++ = ')';
+    return out;
+  }
+};
+
+#endif  // FMT_CPP_LIB_VARIANT
+
+template <> struct formatter<std::error_code> {
+ private:
+  format_specs specs_;
+  detail::arg_ref<char> width_ref_;
+  bool debug_ = false;
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* {
+    auto it = ctx.begin(), end = ctx.end();
+    if (it == end) return it;
+
+    it = detail::parse_align(it, end, specs_);
+
+    char c = *it;
+    if (it != end && ((c >= '0' && c <= '9') || c == '{'))
+      it = detail::parse_width(it, end, specs_, width_ref_, ctx);
+
+    if (it != end && *it == '?') {
+      debug_ = true;
+      ++it;
+    }
+    if (it != end && *it == 's') {
+      specs_.set_type(presentation_type::string);
+      ++it;
+    }
+    return it;
+  }
+
+  template <typename FormatContext>
+  FMT_CONSTEXPR20 auto format(const std::error_code& ec,
+                              FormatContext& ctx) const -> decltype(ctx.out()) {
+    auto specs = specs_;
+    detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, width_ref_,
+                                ctx);
+    auto buf = memory_buffer();
+    if (specs_.type() == presentation_type::string) {
+      buf.append(ec.message());
+    } else {
+      buf.append(string_view(ec.category().name()));
+      buf.push_back(':');
+      detail::write<char>(appender(buf), ec.value());
+    }
+    auto quoted = memory_buffer();
+    auto str = string_view(buf.data(), buf.size());
+    if (debug_) {
+      detail::write_escaped_string<char>(std::back_inserter(quoted), str);
+      str = string_view(quoted.data(), quoted.size());
+    }
+    return detail::write<char>(ctx.out(), str, specs);
+  }
+};
+
+#if FMT_USE_RTTI
+template <> struct formatter<std::type_info> {
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* {
+    return ctx.begin();
+  }
+
+  template <typename Context>
+  auto format(const std::type_info& ti, Context& ctx) const
+      -> decltype(ctx.out()) {
+    return detail::write_demangled_name(ctx.out(), ti);
+  }
+};
+#endif  // FMT_USE_RTTI
+
+template <typename T>
+struct formatter<
+    T, char,
+    typename std::enable_if<std::is_base_of<std::exception, T>::value>::type> {
+ private:
+  bool with_typename_ = false;
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* {
+    auto it = ctx.begin();
+    auto end = ctx.end();
+    if (it == end || *it == '}') return it;
+    if (*it == 't') {
+      ++it;
+      with_typename_ = FMT_USE_RTTI != 0;
+    }
+    return it;
+  }
+
+  template <typename Context>
+  auto format(const std::exception& ex, Context& ctx) const
+      -> decltype(ctx.out()) {
+    auto out = ctx.out();
+#if FMT_USE_RTTI
+    if (with_typename_) {
+      out = detail::write_demangled_name(out, typeid(ex));
+      *out++ = ':';
+      *out++ = ' ';
+    }
+#endif
+    return detail::write_bytes<char>(out, string_view(ex.what()));
+  }
+};
+
+// We can't use std::vector<bool, Allocator>::reference and
+// std::bitset<N>::reference because the compiler can't deduce Allocator and N
+// in partial specialization.
+template <typename BitRef, typename Char>
+struct formatter<BitRef, Char,
+                 enable_if_t<detail::is_bit_reference_like<BitRef>::value>>
+    : formatter<bool, Char> {
+  template <typename FormatContext>
+  FMT_CONSTEXPR auto format(const BitRef& v, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    return formatter<bool, Char>::format(v, ctx);
+  }
+};
+
+template <typename T, typename Char>
+struct formatter<std::atomic<T>, Char,
+                 enable_if_t<is_formattable<T, Char>::value>>
+    : formatter<T, Char> {
+  template <typename FormatContext>
+  auto format(const std::atomic<T>& v, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    return formatter<T, Char>::format(v.load(), ctx);
+  }
+};
+
+#ifdef __cpp_lib_atomic_flag_test
+template <typename Char>
+struct formatter<std::atomic_flag, Char> : formatter<bool, Char> {
+  template <typename FormatContext>
+  auto format(const std::atomic_flag& v, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    return formatter<bool, Char>::format(v.test(), ctx);
+  }
+};
+#endif  // __cpp_lib_atomic_flag_test
+
+template <typename T, typename Char> struct formatter<std::complex<T>, Char> {
+ private:
+  detail::dynamic_format_specs<Char> specs_;
+
+  template <typename FormatContext, typename OutputIt>
+  FMT_CONSTEXPR auto do_format(const std::complex<T>& c,
+                               detail::dynamic_format_specs<Char>& specs,
+                               FormatContext& ctx, OutputIt out) const
+      -> OutputIt {
+    if (c.real() != 0) {
+      *out++ = Char('(');
+      out = detail::write<Char>(out, c.real(), specs, ctx.locale());
+      specs.set_sign(sign::plus);
+      out = detail::write<Char>(out, c.imag(), specs, ctx.locale());
+      if (!detail::isfinite(c.imag())) *out++ = Char(' ');
+      *out++ = Char('i');
+      *out++ = Char(')');
+      return out;
+    }
+    out = detail::write<Char>(out, c.imag(), specs, ctx.locale());
+    if (!detail::isfinite(c.imag())) *out++ = Char(' ');
+    *out++ = Char('i');
+    return out;
+  }
+
+ public:
+  FMT_CONSTEXPR auto parse(parse_context<Char>& ctx) -> const Char* {
+    if (ctx.begin() == ctx.end() || *ctx.begin() == '}') return ctx.begin();
+    return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx,
+                              detail::type_constant<T, Char>::value);
+  }
+
+  template <typename FormatContext>
+  auto format(const std::complex<T>& c, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    auto specs = specs_;
+    if (specs.dynamic()) {
+      detail::handle_dynamic_spec(specs.dynamic_width(), specs.width,
+                                  specs.width_ref, ctx);
+      detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision,
+                                  specs.precision_ref, ctx);
+    }
+
+    if (specs.width == 0) return do_format(c, specs, ctx, ctx.out());
+    auto buf = basic_memory_buffer<Char>();
+
+    auto outer_specs = format_specs();
+    outer_specs.width = specs.width;
+    outer_specs.copy_fill_from(specs);
+    outer_specs.set_align(specs.align());
+
+    specs.width = 0;
+    specs.set_fill({});
+    specs.set_align(align::none);
+
+    do_format(c, specs, ctx, basic_appender<Char>(buf));
+    return detail::write<Char>(ctx.out(),
+                               basic_string_view<Char>(buf.data(), buf.size()),
+                               outer_specs);
+  }
+};
+
+template <typename T, typename Char>
+struct formatter<std::reference_wrapper<T>, Char,
+                 // Guard against format_as because reference_wrapper is
+                 // implicitly convertible to T&.
+                 enable_if_t<is_formattable<remove_cvref_t<T>, Char>::value &&
+                             !detail::has_format_as<T>::value &&
+                             !detail::has_format_as_member<T>::value>>
+    : formatter<remove_cvref_t<T>, Char> {
+  template <typename FormatContext>
+  auto format(std::reference_wrapper<T> ref, FormatContext& ctx) const
+      -> decltype(ctx.out()) {
+    return formatter<remove_cvref_t<T>, Char>::format(ref.get(), ctx);
+  }
+};
+
+FMT_END_NAMESPACE
+
+#endif  // FMT_STD_H_

+ 356 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/fmt/xchar.h

@@ -0,0 +1,356 @@
+// Formatting library for C++ - optional wchar_t and exotic character support
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_XCHAR_H_
+#define FMT_XCHAR_H_
+
+#include "color.h"
+#include "format.h"
+#include "ostream.h"
+#include "ranges.h"
+
+#ifndef FMT_MODULE
+#  include <cwchar>
+#  if FMT_USE_LOCALE
+#    include <locale>
+#  endif
+#endif
+
+FMT_BEGIN_NAMESPACE
+namespace detail {
+
+template <typename T>
+using is_exotic_char = bool_constant<!std::is_same<T, char>::value>;
+
+template <typename S, typename = void> struct format_string_char {};
+
+template <typename S>
+struct format_string_char<
+    S, void_t<decltype(sizeof(detail::to_string_view(std::declval<S>())))>> {
+  using type = char_t<S>;
+};
+
+template <typename S>
+struct format_string_char<
+    S, enable_if_t<std::is_base_of<detail::compile_string, S>::value>> {
+  using type = typename S::char_type;
+};
+
+template <typename S>
+using format_string_char_t = typename format_string_char<S>::type;
+
+inline auto write_loc(basic_appender<wchar_t> out, loc_value value,
+                      const format_specs& specs, locale_ref loc) -> bool {
+#if FMT_USE_LOCALE
+  auto& numpunct =
+      std::use_facet<std::numpunct<wchar_t>>(loc.get<std::locale>());
+  auto separator = std::wstring();
+  auto grouping = numpunct.grouping();
+  if (!grouping.empty()) separator = std::wstring(1, numpunct.thousands_sep());
+  return value.visit(loc_writer<wchar_t>{out, specs, separator, grouping, {}});
+#endif
+  return false;
+}
+
+template <typename Char>
+void vformat_to(buffer<Char>& buf, basic_string_view<Char> fmt,
+                basic_format_args<buffered_context<Char>> args,
+                locale_ref loc = {}) {
+  static_assert(!std::is_same<Char, char>::value, "");
+  auto out = basic_appender<Char>(buf);
+  parse_format_string(
+      fmt, format_handler<Char>{parse_context<Char>(fmt), {out, args, loc}});
+}
+}  // namespace detail
+
+FMT_BEGIN_EXPORT
+
+using wstring_view = basic_string_view<wchar_t>;
+using wformat_parse_context = parse_context<wchar_t>;
+using wformat_context = buffered_context<wchar_t>;
+using wformat_args = basic_format_args<wformat_context>;
+using wmemory_buffer = basic_memory_buffer<wchar_t>;
+
+template <typename Char, typename... T> struct basic_fstring {
+ private:
+  basic_string_view<Char> str_;
+
+  static constexpr int num_static_named_args =
+      detail::count_static_named_args<T...>();
+
+  using checker = detail::format_string_checker<
+      Char, static_cast<int>(sizeof...(T)), num_static_named_args,
+      num_static_named_args != detail::count_named_args<T...>()>;
+
+  using arg_pack = detail::arg_pack<T...>;
+
+ public:
+  using t = basic_fstring;
+
+  template <typename S,
+            FMT_ENABLE_IF(
+                std::is_convertible<const S&, basic_string_view<Char>>::value)>
+  FMT_CONSTEVAL FMT_ALWAYS_INLINE basic_fstring(const S& s) : str_(s) {
+    if (FMT_USE_CONSTEVAL)
+      detail::parse_format_string<Char>(s, checker(s, arg_pack()));
+  }
+  template <typename S,
+            FMT_ENABLE_IF(std::is_base_of<detail::compile_string, S>::value&&
+                              std::is_same<typename S::char_type, Char>::value)>
+  FMT_ALWAYS_INLINE basic_fstring(const S&) : str_(S()) {
+    FMT_CONSTEXPR auto sv = basic_string_view<Char>(S());
+    FMT_CONSTEXPR int ignore =
+        (parse_format_string(sv, checker(sv, arg_pack())), 0);
+    detail::ignore_unused(ignore);
+  }
+  basic_fstring(runtime_format_string<Char> fmt) : str_(fmt.str) {}
+
+  operator basic_string_view<Char>() const { return str_; }
+  auto get() const -> basic_string_view<Char> { return str_; }
+};
+
+template <typename Char, typename... T>
+using basic_format_string = basic_fstring<Char, T...>;
+
+template <typename... T>
+using wformat_string = typename basic_format_string<wchar_t, T...>::t;
+inline auto runtime(wstring_view s) -> runtime_format_string<wchar_t> {
+  return {{s}};
+}
+
+template <typename... T>
+constexpr auto make_wformat_args(T&... args)
+    -> decltype(fmt::make_format_args<wformat_context>(args...)) {
+  return fmt::make_format_args<wformat_context>(args...);
+}
+
+#if !FMT_USE_NONTYPE_TEMPLATE_ARGS
+inline namespace literals {
+inline auto operator""_a(const wchar_t* s, size_t) -> detail::udl_arg<wchar_t> {
+  return {s};
+}
+}  // namespace literals
+#endif
+
+template <typename It, typename Sentinel>
+auto join(It begin, Sentinel end, wstring_view sep)
+    -> join_view<It, Sentinel, wchar_t> {
+  return {begin, end, sep};
+}
+
+template <typename Range, FMT_ENABLE_IF(!is_tuple_like<Range>::value)>
+auto join(Range&& range, wstring_view sep)
+    -> join_view<decltype(std::begin(range)), decltype(std::end(range)),
+                 wchar_t> {
+  return join(std::begin(range), std::end(range), sep);
+}
+
+template <typename T>
+auto join(std::initializer_list<T> list, wstring_view sep)
+    -> join_view<const T*, const T*, wchar_t> {
+  return join(std::begin(list), std::end(list), sep);
+}
+
+template <typename Tuple, FMT_ENABLE_IF(is_tuple_like<Tuple>::value)>
+auto join(const Tuple& tuple, basic_string_view<wchar_t> sep)
+    -> tuple_join_view<Tuple, wchar_t> {
+  return {tuple, sep};
+}
+
+template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
+auto vformat(basic_string_view<Char> fmt,
+             basic_format_args<buffered_context<Char>> args)
+    -> std::basic_string<Char> {
+  auto buf = basic_memory_buffer<Char>();
+  detail::vformat_to(buf, fmt, args);
+  return {buf.data(), buf.size()};
+}
+
+template <typename... T>
+auto format(wformat_string<T...> fmt, T&&... args) -> std::wstring {
+  return vformat(fmt::wstring_view(fmt), fmt::make_wformat_args(args...));
+}
+
+template <typename OutputIt, typename... T>
+auto format_to(OutputIt out, wformat_string<T...> fmt, T&&... args)
+    -> OutputIt {
+  return vformat_to(out, fmt::wstring_view(fmt),
+                    fmt::make_wformat_args(args...));
+}
+
+// Pass char_t as a default template parameter instead of using
+// std::basic_string<char_t<S>> to reduce the symbol size.
+template <typename S, typename... T,
+          typename Char = detail::format_string_char_t<S>,
+          FMT_ENABLE_IF(!std::is_same<Char, char>::value &&
+                        !std::is_same<Char, wchar_t>::value)>
+auto format(const S& fmt, T&&... args) -> std::basic_string<Char> {
+  return vformat(detail::to_string_view(fmt),
+                 fmt::make_format_args<buffered_context<Char>>(args...));
+}
+
+template <typename S, typename Char = detail::format_string_char_t<S>,
+          FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>
+inline auto vformat(locale_ref loc, const S& fmt,
+                    basic_format_args<buffered_context<Char>> args)
+    -> std::basic_string<Char> {
+  auto buf = basic_memory_buffer<Char>();
+  detail::vformat_to(buf, detail::to_string_view(fmt), args, loc);
+  return {buf.data(), buf.size()};
+}
+
+template <typename S, typename... T,
+          typename Char = detail::format_string_char_t<S>,
+          FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>
+inline auto format(locale_ref loc, const S& fmt, T&&... args)
+    -> std::basic_string<Char> {
+  return vformat(loc, detail::to_string_view(fmt),
+                 fmt::make_format_args<buffered_context<Char>>(args...));
+}
+
+template <typename OutputIt, typename S,
+          typename Char = detail::format_string_char_t<S>,
+          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
+                            detail::is_exotic_char<Char>::value)>
+auto vformat_to(OutputIt out, const S& fmt,
+                basic_format_args<buffered_context<Char>> args) -> OutputIt {
+  auto&& buf = detail::get_buffer<Char>(out);
+  detail::vformat_to(buf, detail::to_string_view(fmt), args);
+  return detail::get_iterator(buf, out);
+}
+
+template <typename OutputIt, typename S, typename... T,
+          typename Char = detail::format_string_char_t<S>,
+          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value &&
+                        !std::is_same<Char, char>::value &&
+                        !std::is_same<Char, wchar_t>::value)>
+inline auto format_to(OutputIt out, const S& fmt, T&&... args) -> OutputIt {
+  return vformat_to(out, detail::to_string_view(fmt),
+                    fmt::make_format_args<buffered_context<Char>>(args...));
+}
+
+template <typename S, typename OutputIt, typename... Args,
+          typename Char = detail::format_string_char_t<S>,
+          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
+                            detail::is_exotic_char<Char>::value)>
+inline auto vformat_to(OutputIt out, locale_ref loc, const S& fmt,
+                       basic_format_args<buffered_context<Char>> args)
+    -> OutputIt {
+  auto&& buf = detail::get_buffer<Char>(out);
+  vformat_to(buf, detail::to_string_view(fmt), args, loc);
+  return detail::get_iterator(buf, out);
+}
+
+template <typename OutputIt, typename S, typename... T,
+          typename Char = detail::format_string_char_t<S>,
+          bool enable = detail::is_output_iterator<OutputIt, Char>::value &&
+                        detail::is_exotic_char<Char>::value>
+inline auto format_to(OutputIt out, locale_ref loc, const S& fmt, T&&... args)
+    -> typename std::enable_if<enable, OutputIt>::type {
+  return vformat_to(out, loc, detail::to_string_view(fmt),
+                    fmt::make_format_args<buffered_context<Char>>(args...));
+}
+
+template <typename OutputIt, typename Char, typename... Args,
+          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
+                            detail::is_exotic_char<Char>::value)>
+inline auto vformat_to_n(OutputIt out, size_t n, basic_string_view<Char> fmt,
+                         basic_format_args<buffered_context<Char>> args)
+    -> format_to_n_result<OutputIt> {
+  using traits = detail::fixed_buffer_traits;
+  auto buf = detail::iterator_buffer<OutputIt, Char, traits>(out, n);
+  detail::vformat_to(buf, fmt, args);
+  return {buf.out(), buf.count()};
+}
+
+template <typename OutputIt, typename S, typename... T,
+          typename Char = detail::format_string_char_t<S>,
+          FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value&&
+                            detail::is_exotic_char<Char>::value)>
+inline auto format_to_n(OutputIt out, size_t n, const S& fmt, T&&... args)
+    -> format_to_n_result<OutputIt> {
+  return vformat_to_n(out, n, fmt::basic_string_view<Char>(fmt),
+                      fmt::make_format_args<buffered_context<Char>>(args...));
+}
+
+template <typename S, typename... T,
+          typename Char = detail::format_string_char_t<S>,
+          FMT_ENABLE_IF(detail::is_exotic_char<Char>::value)>
+inline auto formatted_size(const S& fmt, T&&... args) -> size_t {
+  auto buf = detail::counting_buffer<Char>();
+  detail::vformat_to(buf, detail::to_string_view(fmt),
+                     fmt::make_format_args<buffered_context<Char>>(args...));
+  return buf.count();
+}
+
+inline void vprint(std::FILE* f, wstring_view fmt, wformat_args args) {
+  auto buf = wmemory_buffer();
+  detail::vformat_to(buf, fmt, args);
+  buf.push_back(L'\0');
+  if (std::fputws(buf.data(), f) == -1)
+    FMT_THROW(system_error(errno, FMT_STRING("cannot write to file")));
+}
+
+inline void vprint(wstring_view fmt, wformat_args args) {
+  vprint(stdout, fmt, args);
+}
+
+template <typename... T>
+void print(std::FILE* f, wformat_string<T...> fmt, T&&... args) {
+  return vprint(f, wstring_view(fmt), fmt::make_wformat_args(args...));
+}
+
+template <typename... T> void print(wformat_string<T...> fmt, T&&... args) {
+  return vprint(wstring_view(fmt), fmt::make_wformat_args(args...));
+}
+
+template <typename... T>
+void println(std::FILE* f, wformat_string<T...> fmt, T&&... args) {
+  return print(f, L"{}\n", fmt::format(fmt, std::forward<T>(args)...));
+}
+
+template <typename... T> void println(wformat_string<T...> fmt, T&&... args) {
+  return print(L"{}\n", fmt::format(fmt, std::forward<T>(args)...));
+}
+
+inline auto vformat(text_style ts, wstring_view fmt, wformat_args args)
+    -> std::wstring {
+  auto buf = wmemory_buffer();
+  detail::vformat_to(buf, ts, fmt, args);
+  return {buf.data(), buf.size()};
+}
+
+template <typename... T>
+inline auto format(text_style ts, wformat_string<T...> fmt, T&&... args)
+    -> std::wstring {
+  return fmt::vformat(ts, fmt, fmt::make_wformat_args(args...));
+}
+
+inline void vprint(std::wostream& os, wstring_view fmt, wformat_args args) {
+  auto buffer = basic_memory_buffer<wchar_t>();
+  detail::vformat_to(buffer, fmt, args);
+  detail::write_buffer(os, buffer);
+}
+
+template <typename... T>
+void print(std::wostream& os, wformat_string<T...> fmt, T&&... args) {
+  vprint(os, fmt, fmt::make_format_args<buffered_context<wchar_t>>(args...));
+}
+
+template <typename... T>
+void println(std::wostream& os, wformat_string<T...> fmt, T&&... args) {
+  print(os, L"{}\n", fmt::format(fmt, std::forward<T>(args)...));
+}
+
+/// Converts `value` to `std::wstring` using the default format for type `T`.
+template <typename T> inline auto to_wstring(const T& value) -> std::wstring {
+  return format(FMT_STRING(L"{}"), value);
+}
+FMT_END_EXPORT
+FMT_END_NAMESPACE
+
+#endif  // FMT_XCHAR_H_

+ 1491 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/include/widechar_width.hpp

@@ -0,0 +1,1491 @@
+/**
+ * widechar_width.h, generated on 2022-02-11.
+ * See https://github.com/ridiculousfish/widecharwidth/
+ *
+ * SHA1 file hashes:
+ *  UnicodeData.txt:     8a5c26bfb27df8cfab23cf2c34c62d8d3075ae4d
+ *  EastAsianWidth.txt:  8ec36ccac3852bf0c2f02e37c6151551cd14db72
+ *  emoji-data.txt:      3f0ec08c001c4bc6df0b07d01068fc73808bfb4c
+ */
+
+#ifndef WIDECHAR_WIDTH_H
+#define WIDECHAR_WIDTH_H
+
+#include <algorithm>
+#include <iterator>
+#include <cstddef>
+#include <cstdint>
+
+namespace utf8 {
+
+/* Special width values */
+enum {
+  widechar_nonprint = 0,     // The character is not printable.
+  widechar_combining = 0,    // The character is a zero-width combiner.
+  widechar_ambiguous = 1,    // The character is East-Asian ambiguous width.
+  widechar_private_use = 1,  // The character is for private use.
+  widechar_unassigned = 0,   // The character is unassigned.
+  widechar_widened_in_9 = 2, // Width is 1 in Unicode 8, 2 in Unicode 9+.
+  widechar_non_character = 0 // The character is a noncharacter.
+};
+
+/* An inclusive range of characters. */
+struct widechar_range {
+  uint32_t lo;
+  uint32_t hi;
+};
+
+/* Simple ASCII characters - used a lot, so we check them first. */
+static const struct widechar_range widechar_ascii_table[] = {
+    {0x00020, 0x0007E}
+};
+
+/* Private usage range. */
+static const struct widechar_range widechar_private_table[] = {
+    {0x0E000, 0x0F8FF},
+    {0xF0000, 0xFFFFD},
+    {0x100000, 0x10FFFD}
+};
+
+/* Nonprinting characters. */
+static const struct widechar_range widechar_nonprint_table[] = {
+    {0x00000, 0x0001F},
+    {0x0007F, 0x0009F},
+    {0x000AD, 0x000AD},
+    {0x00600, 0x00605},
+    {0x0061C, 0x0061C},
+    {0x006DD, 0x006DD},
+    {0x0070F, 0x0070F},
+    {0x00890, 0x00891},
+    {0x008E2, 0x008E2},
+    {0x0180E, 0x0180E},
+    {0x0200B, 0x0200F},
+    {0x02028, 0x0202E},
+    {0x02060, 0x02064},
+    {0x02066, 0x0206F},
+    {0x0D800, 0x0DFFF},
+    {0x0FEFF, 0x0FEFF},
+    {0x0FFF9, 0x0FFFB},
+    {0x110BD, 0x110BD},
+    {0x110CD, 0x110CD},
+    {0x13430, 0x13438},
+    {0x1BCA0, 0x1BCA3},
+    {0x1D173, 0x1D17A},
+    {0xE0001, 0xE0001},
+    {0xE0020, 0xE007F}
+};
+
+/* Width 0 combining marks. */
+static const struct widechar_range widechar_combining_table[] = {
+    {0x00300, 0x0036F},
+    {0x00483, 0x00489},
+    {0x00591, 0x005BD},
+    {0x005BF, 0x005BF},
+    {0x005C1, 0x005C2},
+    {0x005C4, 0x005C5},
+    {0x005C7, 0x005C7},
+    {0x00610, 0x0061A},
+    {0x0064B, 0x0065F},
+    {0x00670, 0x00670},
+    {0x006D6, 0x006DC},
+    {0x006DF, 0x006E4},
+    {0x006E7, 0x006E8},
+    {0x006EA, 0x006ED},
+    {0x00711, 0x00711},
+    {0x00730, 0x0074A},
+    {0x007A6, 0x007B0},
+    {0x007EB, 0x007F3},
+    {0x007FD, 0x007FD},
+    {0x00816, 0x00819},
+    {0x0081B, 0x00823},
+    {0x00825, 0x00827},
+    {0x00829, 0x0082D},
+    {0x00859, 0x0085B},
+    {0x00898, 0x0089F},
+    {0x008CA, 0x008E1},
+    {0x008E3, 0x00903},
+    {0x0093A, 0x0093C},
+    {0x0093E, 0x0094F},
+    {0x00951, 0x00957},
+    {0x00962, 0x00963},
+    {0x00981, 0x00983},
+    {0x009BC, 0x009BC},
+    {0x009BE, 0x009C4},
+    {0x009C7, 0x009C8},
+    {0x009CB, 0x009CD},
+    {0x009D7, 0x009D7},
+    {0x009E2, 0x009E3},
+    {0x009FE, 0x009FE},
+    {0x00A01, 0x00A03},
+    {0x00A3C, 0x00A3C},
+    {0x00A3E, 0x00A42},
+    {0x00A47, 0x00A48},
+    {0x00A4B, 0x00A4D},
+    {0x00A51, 0x00A51},
+    {0x00A70, 0x00A71},
+    {0x00A75, 0x00A75},
+    {0x00A81, 0x00A83},
+    {0x00ABC, 0x00ABC},
+    {0x00ABE, 0x00AC5},
+    {0x00AC7, 0x00AC9},
+    {0x00ACB, 0x00ACD},
+    {0x00AE2, 0x00AE3},
+    {0x00AFA, 0x00AFF},
+    {0x00B01, 0x00B03},
+    {0x00B3C, 0x00B3C},
+    {0x00B3E, 0x00B44},
+    {0x00B47, 0x00B48},
+    {0x00B4B, 0x00B4D},
+    {0x00B55, 0x00B57},
+    {0x00B62, 0x00B63},
+    {0x00B82, 0x00B82},
+    {0x00BBE, 0x00BC2},
+    {0x00BC6, 0x00BC8},
+    {0x00BCA, 0x00BCD},
+    {0x00BD7, 0x00BD7},
+    {0x00C00, 0x00C04},
+    {0x00C3C, 0x00C3C},
+    {0x00C3E, 0x00C44},
+    {0x00C46, 0x00C48},
+    {0x00C4A, 0x00C4D},
+    {0x00C55, 0x00C56},
+    {0x00C62, 0x00C63},
+    {0x00C81, 0x00C83},
+    {0x00CBC, 0x00CBC},
+    {0x00CBE, 0x00CC4},
+    {0x00CC6, 0x00CC8},
+    {0x00CCA, 0x00CCD},
+    {0x00CD5, 0x00CD6},
+    {0x00CE2, 0x00CE3},
+    {0x00D00, 0x00D03},
+    {0x00D3B, 0x00D3C},
+    {0x00D3E, 0x00D44},
+    {0x00D46, 0x00D48},
+    {0x00D4A, 0x00D4D},
+    {0x00D57, 0x00D57},
+    {0x00D62, 0x00D63},
+    {0x00D81, 0x00D83},
+    {0x00DCA, 0x00DCA},
+    {0x00DCF, 0x00DD4},
+    {0x00DD6, 0x00DD6},
+    {0x00DD8, 0x00DDF},
+    {0x00DF2, 0x00DF3},
+    {0x00E31, 0x00E31},
+    {0x00E34, 0x00E3A},
+    {0x00E47, 0x00E4E},
+    {0x00EB1, 0x00EB1},
+    {0x00EB4, 0x00EBC},
+    {0x00EC8, 0x00ECD},
+    {0x00F18, 0x00F19},
+    {0x00F35, 0x00F35},
+    {0x00F37, 0x00F37},
+    {0x00F39, 0x00F39},
+    {0x00F3E, 0x00F3F},
+    {0x00F71, 0x00F84},
+    {0x00F86, 0x00F87},
+    {0x00F8D, 0x00F97},
+    {0x00F99, 0x00FBC},
+    {0x00FC6, 0x00FC6},
+    {0x0102B, 0x0103E},
+    {0x01056, 0x01059},
+    {0x0105E, 0x01060},
+    {0x01062, 0x01064},
+    {0x01067, 0x0106D},
+    {0x01071, 0x01074},
+    {0x01082, 0x0108D},
+    {0x0108F, 0x0108F},
+    {0x0109A, 0x0109D},
+    {0x0135D, 0x0135F},
+    {0x01712, 0x01715},
+    {0x01732, 0x01734},
+    {0x01752, 0x01753},
+    {0x01772, 0x01773},
+    {0x017B4, 0x017D3},
+    {0x017DD, 0x017DD},
+    {0x0180B, 0x0180D},
+    {0x0180F, 0x0180F},
+    {0x01885, 0x01886},
+    {0x018A9, 0x018A9},
+    {0x01920, 0x0192B},
+    {0x01930, 0x0193B},
+    {0x01A17, 0x01A1B},
+    {0x01A55, 0x01A5E},
+    {0x01A60, 0x01A7C},
+    {0x01A7F, 0x01A7F},
+    {0x01AB0, 0x01ACE},
+    {0x01B00, 0x01B04},
+    {0x01B34, 0x01B44},
+    {0x01B6B, 0x01B73},
+    {0x01B80, 0x01B82},
+    {0x01BA1, 0x01BAD},
+    {0x01BE6, 0x01BF3},
+    {0x01C24, 0x01C37},
+    {0x01CD0, 0x01CD2},
+    {0x01CD4, 0x01CE8},
+    {0x01CED, 0x01CED},
+    {0x01CF4, 0x01CF4},
+    {0x01CF7, 0x01CF9},
+    {0x01DC0, 0x01DFF},
+    {0x020D0, 0x020F0},
+    {0x02CEF, 0x02CF1},
+    {0x02D7F, 0x02D7F},
+    {0x02DE0, 0x02DFF},
+    {0x0302A, 0x0302F},
+    {0x03099, 0x0309A},
+    {0x0A66F, 0x0A672},
+    {0x0A674, 0x0A67D},
+    {0x0A69E, 0x0A69F},
+    {0x0A6F0, 0x0A6F1},
+    {0x0A802, 0x0A802},
+    {0x0A806, 0x0A806},
+    {0x0A80B, 0x0A80B},
+    {0x0A823, 0x0A827},
+    {0x0A82C, 0x0A82C},
+    {0x0A880, 0x0A881},
+    {0x0A8B4, 0x0A8C5},
+    {0x0A8E0, 0x0A8F1},
+    {0x0A8FF, 0x0A8FF},
+    {0x0A926, 0x0A92D},
+    {0x0A947, 0x0A953},
+    {0x0A980, 0x0A983},
+    {0x0A9B3, 0x0A9C0},
+    {0x0A9E5, 0x0A9E5},
+    {0x0AA29, 0x0AA36},
+    {0x0AA43, 0x0AA43},
+    {0x0AA4C, 0x0AA4D},
+    {0x0AA7B, 0x0AA7D},
+    {0x0AAB0, 0x0AAB0},
+    {0x0AAB2, 0x0AAB4},
+    {0x0AAB7, 0x0AAB8},
+    {0x0AABE, 0x0AABF},
+    {0x0AAC1, 0x0AAC1},
+    {0x0AAEB, 0x0AAEF},
+    {0x0AAF5, 0x0AAF6},
+    {0x0ABE3, 0x0ABEA},
+    {0x0ABEC, 0x0ABED},
+    {0x0FB1E, 0x0FB1E},
+    {0x0FE00, 0x0FE0F},
+    {0x0FE20, 0x0FE2F},
+    {0x101FD, 0x101FD},
+    {0x102E0, 0x102E0},
+    {0x10376, 0x1037A},
+    {0x10A01, 0x10A03},
+    {0x10A05, 0x10A06},
+    {0x10A0C, 0x10A0F},
+    {0x10A38, 0x10A3A},
+    {0x10A3F, 0x10A3F},
+    {0x10AE5, 0x10AE6},
+    {0x10D24, 0x10D27},
+    {0x10EAB, 0x10EAC},
+    {0x10F46, 0x10F50},
+    {0x10F82, 0x10F85},
+    {0x11000, 0x11002},
+    {0x11038, 0x11046},
+    {0x11070, 0x11070},
+    {0x11073, 0x11074},
+    {0x1107F, 0x11082},
+    {0x110B0, 0x110BA},
+    {0x110C2, 0x110C2},
+    {0x11100, 0x11102},
+    {0x11127, 0x11134},
+    {0x11145, 0x11146},
+    {0x11173, 0x11173},
+    {0x11180, 0x11182},
+    {0x111B3, 0x111C0},
+    {0x111C9, 0x111CC},
+    {0x111CE, 0x111CF},
+    {0x1122C, 0x11237},
+    {0x1123E, 0x1123E},
+    {0x112DF, 0x112EA},
+    {0x11300, 0x11303},
+    {0x1133B, 0x1133C},
+    {0x1133E, 0x11344},
+    {0x11347, 0x11348},
+    {0x1134B, 0x1134D},
+    {0x11357, 0x11357},
+    {0x11362, 0x11363},
+    {0x11366, 0x1136C},
+    {0x11370, 0x11374},
+    {0x11435, 0x11446},
+    {0x1145E, 0x1145E},
+    {0x114B0, 0x114C3},
+    {0x115AF, 0x115B5},
+    {0x115B8, 0x115C0},
+    {0x115DC, 0x115DD},
+    {0x11630, 0x11640},
+    {0x116AB, 0x116B7},
+    {0x1171D, 0x1172B},
+    {0x1182C, 0x1183A},
+    {0x11930, 0x11935},
+    {0x11937, 0x11938},
+    {0x1193B, 0x1193E},
+    {0x11940, 0x11940},
+    {0x11942, 0x11943},
+    {0x119D1, 0x119D7},
+    {0x119DA, 0x119E0},
+    {0x119E4, 0x119E4},
+    {0x11A01, 0x11A0A},
+    {0x11A33, 0x11A39},
+    {0x11A3B, 0x11A3E},
+    {0x11A47, 0x11A47},
+    {0x11A51, 0x11A5B},
+    {0x11A8A, 0x11A99},
+    {0x11C2F, 0x11C36},
+    {0x11C38, 0x11C3F},
+    {0x11C92, 0x11CA7},
+    {0x11CA9, 0x11CB6},
+    {0x11D31, 0x11D36},
+    {0x11D3A, 0x11D3A},
+    {0x11D3C, 0x11D3D},
+    {0x11D3F, 0x11D45},
+    {0x11D47, 0x11D47},
+    {0x11D8A, 0x11D8E},
+    {0x11D90, 0x11D91},
+    {0x11D93, 0x11D97},
+    {0x11EF3, 0x11EF6},
+    {0x16AF0, 0x16AF4},
+    {0x16B30, 0x16B36},
+    {0x16F4F, 0x16F4F},
+    {0x16F51, 0x16F87},
+    {0x16F8F, 0x16F92},
+    {0x16FE4, 0x16FE4},
+    {0x16FF0, 0x16FF1},
+    {0x1BC9D, 0x1BC9E},
+    {0x1CF00, 0x1CF2D},
+    {0x1CF30, 0x1CF46},
+    {0x1D165, 0x1D169},
+    {0x1D16D, 0x1D172},
+    {0x1D17B, 0x1D182},
+    {0x1D185, 0x1D18B},
+    {0x1D1AA, 0x1D1AD},
+    {0x1D242, 0x1D244},
+    {0x1DA00, 0x1DA36},
+    {0x1DA3B, 0x1DA6C},
+    {0x1DA75, 0x1DA75},
+    {0x1DA84, 0x1DA84},
+    {0x1DA9B, 0x1DA9F},
+    {0x1DAA1, 0x1DAAF},
+    {0x1E000, 0x1E006},
+    {0x1E008, 0x1E018},
+    {0x1E01B, 0x1E021},
+    {0x1E023, 0x1E024},
+    {0x1E026, 0x1E02A},
+    {0x1E130, 0x1E136},
+    {0x1E2AE, 0x1E2AE},
+    {0x1E2EC, 0x1E2EF},
+    {0x1E8D0, 0x1E8D6},
+    {0x1E944, 0x1E94A},
+    {0xE0100, 0xE01EF}
+};
+
+/* Width 0 combining letters. */
+static const struct widechar_range widechar_combiningletters_table[] = {
+    {0x01160, 0x011FF},
+    {0x0D7B0, 0x0D7FF}
+};
+
+/* Width 2 characters. */
+static const struct widechar_range widechar_doublewide_table[] = {
+    {0x01100, 0x0115F},
+    {0x02329, 0x0232A},
+    {0x02E80, 0x02E99},
+    {0x02E9B, 0x02EF3},
+    {0x02F00, 0x02FD5},
+    {0x02FF0, 0x02FFB},
+    {0x03000, 0x0303E},
+    {0x03041, 0x03096},
+    {0x03099, 0x030FF},
+    {0x03105, 0x0312F},
+    {0x03131, 0x0318E},
+    {0x03190, 0x031E3},
+    {0x031F0, 0x0321E},
+    {0x03220, 0x03247},
+    {0x03250, 0x04DBF},
+    {0x04E00, 0x0A48C},
+    {0x0A490, 0x0A4C6},
+    {0x0A960, 0x0A97C},
+    {0x0AC00, 0x0D7A3},
+    {0x0F900, 0x0FAFF},
+    {0x0FE10, 0x0FE19},
+    {0x0FE30, 0x0FE52},
+    {0x0FE54, 0x0FE66},
+    {0x0FE68, 0x0FE6B},
+    {0x0FF01, 0x0FF60},
+    {0x0FFE0, 0x0FFE6},
+    {0x16FE0, 0x16FE4},
+    {0x16FF0, 0x16FF1},
+    {0x17000, 0x187F7},
+    {0x18800, 0x18CD5},
+    {0x18D00, 0x18D08},
+    {0x1AFF0, 0x1AFF3},
+    {0x1AFF5, 0x1AFFB},
+    {0x1AFFD, 0x1AFFE},
+    {0x1B000, 0x1B122},
+    {0x1B150, 0x1B152},
+    {0x1B164, 0x1B167},
+    {0x1B170, 0x1B2FB},
+    {0x1F200, 0x1F200},
+    {0x1F202, 0x1F202},
+    {0x1F210, 0x1F219},
+    {0x1F21B, 0x1F22E},
+    {0x1F230, 0x1F231},
+    {0x1F237, 0x1F237},
+    {0x1F23B, 0x1F23B},
+    {0x1F240, 0x1F248},
+    {0x1F260, 0x1F265},
+    {0x1F57A, 0x1F57A},
+    {0x1F5A4, 0x1F5A4},
+    {0x1F6D1, 0x1F6D2},
+    {0x1F6D5, 0x1F6D7},
+    {0x1F6DD, 0x1F6DF},
+    {0x1F6F4, 0x1F6FC},
+    {0x1F7E0, 0x1F7EB},
+    {0x1F7F0, 0x1F7F0},
+    {0x1F90C, 0x1F90F},
+    {0x1F919, 0x1F93A},
+    {0x1F93C, 0x1F945},
+    {0x1F947, 0x1F97F},
+    {0x1F985, 0x1F9BF},
+    {0x1F9C1, 0x1F9FF},
+    {0x1FA70, 0x1FA74},
+    {0x1FA78, 0x1FA7C},
+    {0x1FA80, 0x1FA86},
+    {0x1FA90, 0x1FAAC},
+    {0x1FAB0, 0x1FABA},
+    {0x1FAC0, 0x1FAC5},
+    {0x1FAD0, 0x1FAD9},
+    {0x1FAE0, 0x1FAE7},
+    {0x1FAF0, 0x1FAF6},
+    {0x20000, 0x2FFFD},
+    {0x30000, 0x3FFFD}
+};
+
+/* Ambiguous-width characters. */
+static const struct widechar_range widechar_ambiguous_table[] = {
+    {0x000A1, 0x000A1},
+    {0x000A4, 0x000A4},
+    {0x000A7, 0x000A8},
+    {0x000AA, 0x000AA},
+    {0x000AD, 0x000AE},
+    {0x000B0, 0x000B4},
+    {0x000B6, 0x000BA},
+    {0x000BC, 0x000BF},
+    {0x000C6, 0x000C6},
+    {0x000D0, 0x000D0},
+    {0x000D7, 0x000D8},
+    {0x000DE, 0x000E1},
+    {0x000E6, 0x000E6},
+    {0x000E8, 0x000EA},
+    {0x000EC, 0x000ED},
+    {0x000F0, 0x000F0},
+    {0x000F2, 0x000F3},
+    {0x000F7, 0x000FA},
+    {0x000FC, 0x000FC},
+    {0x000FE, 0x000FE},
+    {0x00101, 0x00101},
+    {0x00111, 0x00111},
+    {0x00113, 0x00113},
+    {0x0011B, 0x0011B},
+    {0x00126, 0x00127},
+    {0x0012B, 0x0012B},
+    {0x00131, 0x00133},
+    {0x00138, 0x00138},
+    {0x0013F, 0x00142},
+    {0x00144, 0x00144},
+    {0x00148, 0x0014B},
+    {0x0014D, 0x0014D},
+    {0x00152, 0x00153},
+    {0x00166, 0x00167},
+    {0x0016B, 0x0016B},
+    {0x001CE, 0x001CE},
+    {0x001D0, 0x001D0},
+    {0x001D2, 0x001D2},
+    {0x001D4, 0x001D4},
+    {0x001D6, 0x001D6},
+    {0x001D8, 0x001D8},
+    {0x001DA, 0x001DA},
+    {0x001DC, 0x001DC},
+    {0x00251, 0x00251},
+    {0x00261, 0x00261},
+    {0x002C4, 0x002C4},
+    {0x002C7, 0x002C7},
+    {0x002C9, 0x002CB},
+    {0x002CD, 0x002CD},
+    {0x002D0, 0x002D0},
+    {0x002D8, 0x002DB},
+    {0x002DD, 0x002DD},
+    {0x002DF, 0x002DF},
+    {0x00300, 0x0036F},
+    {0x00391, 0x003A1},
+    {0x003A3, 0x003A9},
+    {0x003B1, 0x003C1},
+    {0x003C3, 0x003C9},
+    {0x00401, 0x00401},
+    {0x00410, 0x0044F},
+    {0x00451, 0x00451},
+    {0x02010, 0x02010},
+    {0x02013, 0x02016},
+    {0x02018, 0x02019},
+    {0x0201C, 0x0201D},
+    {0x02020, 0x02022},
+    {0x02024, 0x02027},
+    {0x02030, 0x02030},
+    {0x02032, 0x02033},
+    {0x02035, 0x02035},
+    {0x0203B, 0x0203B},
+    {0x0203E, 0x0203E},
+    {0x02074, 0x02074},
+    {0x0207F, 0x0207F},
+    {0x02081, 0x02084},
+    {0x020AC, 0x020AC},
+    {0x02103, 0x02103},
+    {0x02105, 0x02105},
+    {0x02109, 0x02109},
+    {0x02113, 0x02113},
+    {0x02116, 0x02116},
+    {0x02121, 0x02122},
+    {0x02126, 0x02126},
+    {0x0212B, 0x0212B},
+    {0x02153, 0x02154},
+    {0x0215B, 0x0215E},
+    {0x02160, 0x0216B},
+    {0x02170, 0x02179},
+    {0x02189, 0x02189},
+    {0x02190, 0x02199},
+    {0x021B8, 0x021B9},
+    {0x021D2, 0x021D2},
+    {0x021D4, 0x021D4},
+    {0x021E7, 0x021E7},
+    {0x02200, 0x02200},
+    {0x02202, 0x02203},
+    {0x02207, 0x02208},
+    {0x0220B, 0x0220B},
+    {0x0220F, 0x0220F},
+    {0x02211, 0x02211},
+    {0x02215, 0x02215},
+    {0x0221A, 0x0221A},
+    {0x0221D, 0x02220},
+    {0x02223, 0x02223},
+    {0x02225, 0x02225},
+    {0x02227, 0x0222C},
+    {0x0222E, 0x0222E},
+    {0x02234, 0x02237},
+    {0x0223C, 0x0223D},
+    {0x02248, 0x02248},
+    {0x0224C, 0x0224C},
+    {0x02252, 0x02252},
+    {0x02260, 0x02261},
+    {0x02264, 0x02267},
+    {0x0226A, 0x0226B},
+    {0x0226E, 0x0226F},
+    {0x02282, 0x02283},
+    {0x02286, 0x02287},
+    {0x02295, 0x02295},
+    {0x02299, 0x02299},
+    {0x022A5, 0x022A5},
+    {0x022BF, 0x022BF},
+    {0x02312, 0x02312},
+    {0x02460, 0x024E9},
+    {0x024EB, 0x0254B},
+    {0x02550, 0x02573},
+    {0x02580, 0x0258F},
+    {0x02592, 0x02595},
+    {0x025A0, 0x025A1},
+    {0x025A3, 0x025A9},
+    {0x025B2, 0x025B3},
+    {0x025B6, 0x025B7},
+    {0x025BC, 0x025BD},
+    {0x025C0, 0x025C1},
+    {0x025C6, 0x025C8},
+    {0x025CB, 0x025CB},
+    {0x025CE, 0x025D1},
+    {0x025E2, 0x025E5},
+    {0x025EF, 0x025EF},
+    {0x02605, 0x02606},
+    {0x02609, 0x02609},
+    {0x0260E, 0x0260F},
+    {0x0261C, 0x0261C},
+    {0x0261E, 0x0261E},
+    {0x02640, 0x02640},
+    {0x02642, 0x02642},
+    {0x02660, 0x02661},
+    {0x02663, 0x02665},
+    {0x02667, 0x0266A},
+    {0x0266C, 0x0266D},
+    {0x0266F, 0x0266F},
+    {0x0269E, 0x0269F},
+    {0x026BF, 0x026BF},
+    {0x026C6, 0x026CD},
+    {0x026CF, 0x026D3},
+    {0x026D5, 0x026E1},
+    {0x026E3, 0x026E3},
+    {0x026E8, 0x026E9},
+    {0x026EB, 0x026F1},
+    {0x026F4, 0x026F4},
+    {0x026F6, 0x026F9},
+    {0x026FB, 0x026FC},
+    {0x026FE, 0x026FF},
+    {0x0273D, 0x0273D},
+    {0x02776, 0x0277F},
+    {0x02B56, 0x02B59},
+    {0x03248, 0x0324F},
+    {0x0E000, 0x0F8FF},
+    {0x0FE00, 0x0FE0F},
+    {0x0FFFD, 0x0FFFD},
+    {0x1F100, 0x1F10A},
+    {0x1F110, 0x1F12D},
+    {0x1F130, 0x1F169},
+    {0x1F170, 0x1F18D},
+    {0x1F18F, 0x1F190},
+    {0x1F19B, 0x1F1AC},
+    {0xE0100, 0xE01EF},
+    {0xF0000, 0xFFFFD},
+    {0x100000, 0x10FFFD}
+};
+
+/* Unassigned characters. */
+static const struct widechar_range widechar_unassigned_table[] = {
+    {0x00378, 0x00379},
+    {0x00380, 0x00383},
+    {0x0038B, 0x0038B},
+    {0x0038D, 0x0038D},
+    {0x003A2, 0x003A2},
+    {0x00530, 0x00530},
+    {0x00557, 0x00558},
+    {0x0058B, 0x0058C},
+    {0x00590, 0x00590},
+    {0x005C8, 0x005CF},
+    {0x005EB, 0x005EE},
+    {0x005F5, 0x005FF},
+    {0x0070E, 0x0070E},
+    {0x0074B, 0x0074C},
+    {0x007B2, 0x007BF},
+    {0x007FB, 0x007FC},
+    {0x0082E, 0x0082F},
+    {0x0083F, 0x0083F},
+    {0x0085C, 0x0085D},
+    {0x0085F, 0x0085F},
+    {0x0086B, 0x0086F},
+    {0x0088F, 0x0088F},
+    {0x00892, 0x00897},
+    {0x00984, 0x00984},
+    {0x0098D, 0x0098E},
+    {0x00991, 0x00992},
+    {0x009A9, 0x009A9},
+    {0x009B1, 0x009B1},
+    {0x009B3, 0x009B5},
+    {0x009BA, 0x009BB},
+    {0x009C5, 0x009C6},
+    {0x009C9, 0x009CA},
+    {0x009CF, 0x009D6},
+    {0x009D8, 0x009DB},
+    {0x009DE, 0x009DE},
+    {0x009E4, 0x009E5},
+    {0x009FF, 0x00A00},
+    {0x00A04, 0x00A04},
+    {0x00A0B, 0x00A0E},
+    {0x00A11, 0x00A12},
+    {0x00A29, 0x00A29},
+    {0x00A31, 0x00A31},
+    {0x00A34, 0x00A34},
+    {0x00A37, 0x00A37},
+    {0x00A3A, 0x00A3B},
+    {0x00A3D, 0x00A3D},
+    {0x00A43, 0x00A46},
+    {0x00A49, 0x00A4A},
+    {0x00A4E, 0x00A50},
+    {0x00A52, 0x00A58},
+    {0x00A5D, 0x00A5D},
+    {0x00A5F, 0x00A65},
+    {0x00A77, 0x00A80},
+    {0x00A84, 0x00A84},
+    {0x00A8E, 0x00A8E},
+    {0x00A92, 0x00A92},
+    {0x00AA9, 0x00AA9},
+    {0x00AB1, 0x00AB1},
+    {0x00AB4, 0x00AB4},
+    {0x00ABA, 0x00ABB},
+    {0x00AC6, 0x00AC6},
+    {0x00ACA, 0x00ACA},
+    {0x00ACE, 0x00ACF},
+    {0x00AD1, 0x00ADF},
+    {0x00AE4, 0x00AE5},
+    {0x00AF2, 0x00AF8},
+    {0x00B00, 0x00B00},
+    {0x00B04, 0x00B04},
+    {0x00B0D, 0x00B0E},
+    {0x00B11, 0x00B12},
+    {0x00B29, 0x00B29},
+    {0x00B31, 0x00B31},
+    {0x00B34, 0x00B34},
+    {0x00B3A, 0x00B3B},
+    {0x00B45, 0x00B46},
+    {0x00B49, 0x00B4A},
+    {0x00B4E, 0x00B54},
+    {0x00B58, 0x00B5B},
+    {0x00B5E, 0x00B5E},
+    {0x00B64, 0x00B65},
+    {0x00B78, 0x00B81},
+    {0x00B84, 0x00B84},
+    {0x00B8B, 0x00B8D},
+    {0x00B91, 0x00B91},
+    {0x00B96, 0x00B98},
+    {0x00B9B, 0x00B9B},
+    {0x00B9D, 0x00B9D},
+    {0x00BA0, 0x00BA2},
+    {0x00BA5, 0x00BA7},
+    {0x00BAB, 0x00BAD},
+    {0x00BBA, 0x00BBD},
+    {0x00BC3, 0x00BC5},
+    {0x00BC9, 0x00BC9},
+    {0x00BCE, 0x00BCF},
+    {0x00BD1, 0x00BD6},
+    {0x00BD8, 0x00BE5},
+    {0x00BFB, 0x00BFF},
+    {0x00C0D, 0x00C0D},
+    {0x00C11, 0x00C11},
+    {0x00C29, 0x00C29},
+    {0x00C3A, 0x00C3B},
+    {0x00C45, 0x00C45},
+    {0x00C49, 0x00C49},
+    {0x00C4E, 0x00C54},
+    {0x00C57, 0x00C57},
+    {0x00C5B, 0x00C5C},
+    {0x00C5E, 0x00C5F},
+    {0x00C64, 0x00C65},
+    {0x00C70, 0x00C76},
+    {0x00C8D, 0x00C8D},
+    {0x00C91, 0x00C91},
+    {0x00CA9, 0x00CA9},
+    {0x00CB4, 0x00CB4},
+    {0x00CBA, 0x00CBB},
+    {0x00CC5, 0x00CC5},
+    {0x00CC9, 0x00CC9},
+    {0x00CCE, 0x00CD4},
+    {0x00CD7, 0x00CDC},
+    {0x00CDF, 0x00CDF},
+    {0x00CE4, 0x00CE5},
+    {0x00CF0, 0x00CF0},
+    {0x00CF3, 0x00CFF},
+    {0x00D0D, 0x00D0D},
+    {0x00D11, 0x00D11},
+    {0x00D45, 0x00D45},
+    {0x00D49, 0x00D49},
+    {0x00D50, 0x00D53},
+    {0x00D64, 0x00D65},
+    {0x00D80, 0x00D80},
+    {0x00D84, 0x00D84},
+    {0x00D97, 0x00D99},
+    {0x00DB2, 0x00DB2},
+    {0x00DBC, 0x00DBC},
+    {0x00DBE, 0x00DBF},
+    {0x00DC7, 0x00DC9},
+    {0x00DCB, 0x00DCE},
+    {0x00DD5, 0x00DD5},
+    {0x00DD7, 0x00DD7},
+    {0x00DE0, 0x00DE5},
+    {0x00DF0, 0x00DF1},
+    {0x00DF5, 0x00E00},
+    {0x00E3B, 0x00E3E},
+    {0x00E5C, 0x00E80},
+    {0x00E83, 0x00E83},
+    {0x00E85, 0x00E85},
+    {0x00E8B, 0x00E8B},
+    {0x00EA4, 0x00EA4},
+    {0x00EA6, 0x00EA6},
+    {0x00EBE, 0x00EBF},
+    {0x00EC5, 0x00EC5},
+    {0x00EC7, 0x00EC7},
+    {0x00ECE, 0x00ECF},
+    {0x00EDA, 0x00EDB},
+    {0x00EE0, 0x00EFF},
+    {0x00F48, 0x00F48},
+    {0x00F6D, 0x00F70},
+    {0x00F98, 0x00F98},
+    {0x00FBD, 0x00FBD},
+    {0x00FCD, 0x00FCD},
+    {0x00FDB, 0x00FFF},
+    {0x010C6, 0x010C6},
+    {0x010C8, 0x010CC},
+    {0x010CE, 0x010CF},
+    {0x01249, 0x01249},
+    {0x0124E, 0x0124F},
+    {0x01257, 0x01257},
+    {0x01259, 0x01259},
+    {0x0125E, 0x0125F},
+    {0x01289, 0x01289},
+    {0x0128E, 0x0128F},
+    {0x012B1, 0x012B1},
+    {0x012B6, 0x012B7},
+    {0x012BF, 0x012BF},
+    {0x012C1, 0x012C1},
+    {0x012C6, 0x012C7},
+    {0x012D7, 0x012D7},
+    {0x01311, 0x01311},
+    {0x01316, 0x01317},
+    {0x0135B, 0x0135C},
+    {0x0137D, 0x0137F},
+    {0x0139A, 0x0139F},
+    {0x013F6, 0x013F7},
+    {0x013FE, 0x013FF},
+    {0x0169D, 0x0169F},
+    {0x016F9, 0x016FF},
+    {0x01716, 0x0171E},
+    {0x01737, 0x0173F},
+    {0x01754, 0x0175F},
+    {0x0176D, 0x0176D},
+    {0x01771, 0x01771},
+    {0x01774, 0x0177F},
+    {0x017DE, 0x017DF},
+    {0x017EA, 0x017EF},
+    {0x017FA, 0x017FF},
+    {0x0181A, 0x0181F},
+    {0x01879, 0x0187F},
+    {0x018AB, 0x018AF},
+    {0x018F6, 0x018FF},
+    {0x0191F, 0x0191F},
+    {0x0192C, 0x0192F},
+    {0x0193C, 0x0193F},
+    {0x01941, 0x01943},
+    {0x0196E, 0x0196F},
+    {0x01975, 0x0197F},
+    {0x019AC, 0x019AF},
+    {0x019CA, 0x019CF},
+    {0x019DB, 0x019DD},
+    {0x01A1C, 0x01A1D},
+    {0x01A5F, 0x01A5F},
+    {0x01A7D, 0x01A7E},
+    {0x01A8A, 0x01A8F},
+    {0x01A9A, 0x01A9F},
+    {0x01AAE, 0x01AAF},
+    {0x01ACF, 0x01AFF},
+    {0x01B4D, 0x01B4F},
+    {0x01B7F, 0x01B7F},
+    {0x01BF4, 0x01BFB},
+    {0x01C38, 0x01C3A},
+    {0x01C4A, 0x01C4C},
+    {0x01C89, 0x01C8F},
+    {0x01CBB, 0x01CBC},
+    {0x01CC8, 0x01CCF},
+    {0x01CFB, 0x01CFF},
+    {0x01F16, 0x01F17},
+    {0x01F1E, 0x01F1F},
+    {0x01F46, 0x01F47},
+    {0x01F4E, 0x01F4F},
+    {0x01F58, 0x01F58},
+    {0x01F5A, 0x01F5A},
+    {0x01F5C, 0x01F5C},
+    {0x01F5E, 0x01F5E},
+    {0x01F7E, 0x01F7F},
+    {0x01FB5, 0x01FB5},
+    {0x01FC5, 0x01FC5},
+    {0x01FD4, 0x01FD5},
+    {0x01FDC, 0x01FDC},
+    {0x01FF0, 0x01FF1},
+    {0x01FF5, 0x01FF5},
+    {0x01FFF, 0x01FFF},
+    {0x02065, 0x02065},
+    {0x02072, 0x02073},
+    {0x0208F, 0x0208F},
+    {0x0209D, 0x0209F},
+    {0x020C1, 0x020CF},
+    {0x020F1, 0x020FF},
+    {0x0218C, 0x0218F},
+    {0x02427, 0x0243F},
+    {0x0244B, 0x0245F},
+    {0x02B74, 0x02B75},
+    {0x02B96, 0x02B96},
+    {0x02CF4, 0x02CF8},
+    {0x02D26, 0x02D26},
+    {0x02D28, 0x02D2C},
+    {0x02D2E, 0x02D2F},
+    {0x02D68, 0x02D6E},
+    {0x02D71, 0x02D7E},
+    {0x02D97, 0x02D9F},
+    {0x02DA7, 0x02DA7},
+    {0x02DAF, 0x02DAF},
+    {0x02DB7, 0x02DB7},
+    {0x02DBF, 0x02DBF},
+    {0x02DC7, 0x02DC7},
+    {0x02DCF, 0x02DCF},
+    {0x02DD7, 0x02DD7},
+    {0x02DDF, 0x02DDF},
+    {0x02E5E, 0x02E7F},
+    {0x02E9A, 0x02E9A},
+    {0x02EF4, 0x02EFF},
+    {0x02FD6, 0x02FEF},
+    {0x02FFC, 0x02FFF},
+    {0x03040, 0x03040},
+    {0x03097, 0x03098},
+    {0x03100, 0x03104},
+    {0x03130, 0x03130},
+    {0x0318F, 0x0318F},
+    {0x031E4, 0x031EF},
+    {0x0321F, 0x0321F},
+    {0x03401, 0x04DBE},
+    {0x04E01, 0x09FFE},
+    {0x0A48D, 0x0A48F},
+    {0x0A4C7, 0x0A4CF},
+    {0x0A62C, 0x0A63F},
+    {0x0A6F8, 0x0A6FF},
+    {0x0A7CB, 0x0A7CF},
+    {0x0A7D2, 0x0A7D2},
+    {0x0A7D4, 0x0A7D4},
+    {0x0A7DA, 0x0A7F1},
+    {0x0A82D, 0x0A82F},
+    {0x0A83A, 0x0A83F},
+    {0x0A878, 0x0A87F},
+    {0x0A8C6, 0x0A8CD},
+    {0x0A8DA, 0x0A8DF},
+    {0x0A954, 0x0A95E},
+    {0x0A97D, 0x0A97F},
+    {0x0A9CE, 0x0A9CE},
+    {0x0A9DA, 0x0A9DD},
+    {0x0A9FF, 0x0A9FF},
+    {0x0AA37, 0x0AA3F},
+    {0x0AA4E, 0x0AA4F},
+    {0x0AA5A, 0x0AA5B},
+    {0x0AAC3, 0x0AADA},
+    {0x0AAF7, 0x0AB00},
+    {0x0AB07, 0x0AB08},
+    {0x0AB0F, 0x0AB10},
+    {0x0AB17, 0x0AB1F},
+    {0x0AB27, 0x0AB27},
+    {0x0AB2F, 0x0AB2F},
+    {0x0AB6C, 0x0AB6F},
+    {0x0ABEE, 0x0ABEF},
+    {0x0ABFA, 0x0ABFF},
+    {0x0AC01, 0x0D7A2},
+    {0x0D7A4, 0x0D7AF},
+    {0x0D7C7, 0x0D7CA},
+    {0x0D7FC, 0x0D7FF},
+    {0x0FA6E, 0x0FA6F},
+    {0x0FADA, 0x0FAFF},
+    {0x0FB07, 0x0FB12},
+    {0x0FB18, 0x0FB1C},
+    {0x0FB37, 0x0FB37},
+    {0x0FB3D, 0x0FB3D},
+    {0x0FB3F, 0x0FB3F},
+    {0x0FB42, 0x0FB42},
+    {0x0FB45, 0x0FB45},
+    {0x0FBC3, 0x0FBD2},
+    {0x0FD90, 0x0FD91},
+    {0x0FDC8, 0x0FDCE},
+    {0x0FE1A, 0x0FE1F},
+    {0x0FE53, 0x0FE53},
+    {0x0FE67, 0x0FE67},
+    {0x0FE6C, 0x0FE6F},
+    {0x0FE75, 0x0FE75},
+    {0x0FEFD, 0x0FEFE},
+    {0x0FF00, 0x0FF00},
+    {0x0FFBF, 0x0FFC1},
+    {0x0FFC8, 0x0FFC9},
+    {0x0FFD0, 0x0FFD1},
+    {0x0FFD8, 0x0FFD9},
+    {0x0FFDD, 0x0FFDF},
+    {0x0FFE7, 0x0FFE7},
+    {0x0FFEF, 0x0FFF8},
+    {0x1000C, 0x1000C},
+    {0x10027, 0x10027},
+    {0x1003B, 0x1003B},
+    {0x1003E, 0x1003E},
+    {0x1004E, 0x1004F},
+    {0x1005E, 0x1007F},
+    {0x100FB, 0x100FF},
+    {0x10103, 0x10106},
+    {0x10134, 0x10136},
+    {0x1018F, 0x1018F},
+    {0x1019D, 0x1019F},
+    {0x101A1, 0x101CF},
+    {0x101FE, 0x1027F},
+    {0x1029D, 0x1029F},
+    {0x102D1, 0x102DF},
+    {0x102FC, 0x102FF},
+    {0x10324, 0x1032C},
+    {0x1034B, 0x1034F},
+    {0x1037B, 0x1037F},
+    {0x1039E, 0x1039E},
+    {0x103C4, 0x103C7},
+    {0x103D6, 0x103FF},
+    {0x1049E, 0x1049F},
+    {0x104AA, 0x104AF},
+    {0x104D4, 0x104D7},
+    {0x104FC, 0x104FF},
+    {0x10528, 0x1052F},
+    {0x10564, 0x1056E},
+    {0x1057B, 0x1057B},
+    {0x1058B, 0x1058B},
+    {0x10593, 0x10593},
+    {0x10596, 0x10596},
+    {0x105A2, 0x105A2},
+    {0x105B2, 0x105B2},
+    {0x105BA, 0x105BA},
+    {0x105BD, 0x105FF},
+    {0x10737, 0x1073F},
+    {0x10756, 0x1075F},
+    {0x10768, 0x1077F},
+    {0x10786, 0x10786},
+    {0x107B1, 0x107B1},
+    {0x107BB, 0x107FF},
+    {0x10806, 0x10807},
+    {0x10809, 0x10809},
+    {0x10836, 0x10836},
+    {0x10839, 0x1083B},
+    {0x1083D, 0x1083E},
+    {0x10856, 0x10856},
+    {0x1089F, 0x108A6},
+    {0x108B0, 0x108DF},
+    {0x108F3, 0x108F3},
+    {0x108F6, 0x108FA},
+    {0x1091C, 0x1091E},
+    {0x1093A, 0x1093E},
+    {0x10940, 0x1097F},
+    {0x109B8, 0x109BB},
+    {0x109D0, 0x109D1},
+    {0x10A04, 0x10A04},
+    {0x10A07, 0x10A0B},
+    {0x10A14, 0x10A14},
+    {0x10A18, 0x10A18},
+    {0x10A36, 0x10A37},
+    {0x10A3B, 0x10A3E},
+    {0x10A49, 0x10A4F},
+    {0x10A59, 0x10A5F},
+    {0x10AA0, 0x10ABF},
+    {0x10AE7, 0x10AEA},
+    {0x10AF7, 0x10AFF},
+    {0x10B36, 0x10B38},
+    {0x10B56, 0x10B57},
+    {0x10B73, 0x10B77},
+    {0x10B92, 0x10B98},
+    {0x10B9D, 0x10BA8},
+    {0x10BB0, 0x10BFF},
+    {0x10C49, 0x10C7F},
+    {0x10CB3, 0x10CBF},
+    {0x10CF3, 0x10CF9},
+    {0x10D28, 0x10D2F},
+    {0x10D3A, 0x10E5F},
+    {0x10E7F, 0x10E7F},
+    {0x10EAA, 0x10EAA},
+    {0x10EAE, 0x10EAF},
+    {0x10EB2, 0x10EFF},
+    {0x10F28, 0x10F2F},
+    {0x10F5A, 0x10F6F},
+    {0x10F8A, 0x10FAF},
+    {0x10FCC, 0x10FDF},
+    {0x10FF7, 0x10FFF},
+    {0x1104E, 0x11051},
+    {0x11076, 0x1107E},
+    {0x110C3, 0x110CC},
+    {0x110CE, 0x110CF},
+    {0x110E9, 0x110EF},
+    {0x110FA, 0x110FF},
+    {0x11135, 0x11135},
+    {0x11148, 0x1114F},
+    {0x11177, 0x1117F},
+    {0x111E0, 0x111E0},
+    {0x111F5, 0x111FF},
+    {0x11212, 0x11212},
+    {0x1123F, 0x1127F},
+    {0x11287, 0x11287},
+    {0x11289, 0x11289},
+    {0x1128E, 0x1128E},
+    {0x1129E, 0x1129E},
+    {0x112AA, 0x112AF},
+    {0x112EB, 0x112EF},
+    {0x112FA, 0x112FF},
+    {0x11304, 0x11304},
+    {0x1130D, 0x1130E},
+    {0x11311, 0x11312},
+    {0x11329, 0x11329},
+    {0x11331, 0x11331},
+    {0x11334, 0x11334},
+    {0x1133A, 0x1133A},
+    {0x11345, 0x11346},
+    {0x11349, 0x1134A},
+    {0x1134E, 0x1134F},
+    {0x11351, 0x11356},
+    {0x11358, 0x1135C},
+    {0x11364, 0x11365},
+    {0x1136D, 0x1136F},
+    {0x11375, 0x113FF},
+    {0x1145C, 0x1145C},
+    {0x11462, 0x1147F},
+    {0x114C8, 0x114CF},
+    {0x114DA, 0x1157F},
+    {0x115B6, 0x115B7},
+    {0x115DE, 0x115FF},
+    {0x11645, 0x1164F},
+    {0x1165A, 0x1165F},
+    {0x1166D, 0x1167F},
+    {0x116BA, 0x116BF},
+    {0x116CA, 0x116FF},
+    {0x1171B, 0x1171C},
+    {0x1172C, 0x1172F},
+    {0x11747, 0x117FF},
+    {0x1183C, 0x1189F},
+    {0x118F3, 0x118FE},
+    {0x11907, 0x11908},
+    {0x1190A, 0x1190B},
+    {0x11914, 0x11914},
+    {0x11917, 0x11917},
+    {0x11936, 0x11936},
+    {0x11939, 0x1193A},
+    {0x11947, 0x1194F},
+    {0x1195A, 0x1199F},
+    {0x119A8, 0x119A9},
+    {0x119D8, 0x119D9},
+    {0x119E5, 0x119FF},
+    {0x11A48, 0x11A4F},
+    {0x11AA3, 0x11AAF},
+    {0x11AF9, 0x11BFF},
+    {0x11C09, 0x11C09},
+    {0x11C37, 0x11C37},
+    {0x11C46, 0x11C4F},
+    {0x11C6D, 0x11C6F},
+    {0x11C90, 0x11C91},
+    {0x11CA8, 0x11CA8},
+    {0x11CB7, 0x11CFF},
+    {0x11D07, 0x11D07},
+    {0x11D0A, 0x11D0A},
+    {0x11D37, 0x11D39},
+    {0x11D3B, 0x11D3B},
+    {0x11D3E, 0x11D3E},
+    {0x11D48, 0x11D4F},
+    {0x11D5A, 0x11D5F},
+    {0x11D66, 0x11D66},
+    {0x11D69, 0x11D69},
+    {0x11D8F, 0x11D8F},
+    {0x11D92, 0x11D92},
+    {0x11D99, 0x11D9F},
+    {0x11DAA, 0x11EDF},
+    {0x11EF9, 0x11FAF},
+    {0x11FB1, 0x11FBF},
+    {0x11FF2, 0x11FFE},
+    {0x1239A, 0x123FF},
+    {0x1246F, 0x1246F},
+    {0x12475, 0x1247F},
+    {0x12544, 0x12F8F},
+    {0x12FF3, 0x12FFF},
+    {0x1342F, 0x1342F},
+    {0x13439, 0x143FF},
+    {0x14647, 0x167FF},
+    {0x16A39, 0x16A3F},
+    {0x16A5F, 0x16A5F},
+    {0x16A6A, 0x16A6D},
+    {0x16ABF, 0x16ABF},
+    {0x16ACA, 0x16ACF},
+    {0x16AEE, 0x16AEF},
+    {0x16AF6, 0x16AFF},
+    {0x16B46, 0x16B4F},
+    {0x16B5A, 0x16B5A},
+    {0x16B62, 0x16B62},
+    {0x16B78, 0x16B7C},
+    {0x16B90, 0x16E3F},
+    {0x16E9B, 0x16EFF},
+    {0x16F4B, 0x16F4E},
+    {0x16F88, 0x16F8E},
+    {0x16FA0, 0x16FDF},
+    {0x16FE5, 0x16FEF},
+    {0x16FF2, 0x16FFF},
+    {0x17001, 0x187F6},
+    {0x187F8, 0x187FF},
+    {0x18CD6, 0x18CFF},
+    {0x18D01, 0x18D07},
+    {0x18D09, 0x1AFEF},
+    {0x1AFF4, 0x1AFF4},
+    {0x1AFFC, 0x1AFFC},
+    {0x1AFFF, 0x1AFFF},
+    {0x1B123, 0x1B14F},
+    {0x1B153, 0x1B163},
+    {0x1B168, 0x1B16F},
+    {0x1B2FC, 0x1BBFF},
+    {0x1BC6B, 0x1BC6F},
+    {0x1BC7D, 0x1BC7F},
+    {0x1BC89, 0x1BC8F},
+    {0x1BC9A, 0x1BC9B},
+    {0x1BCA4, 0x1CEFF},
+    {0x1CF2E, 0x1CF2F},
+    {0x1CF47, 0x1CF4F},
+    {0x1CFC4, 0x1CFFF},
+    {0x1D0F6, 0x1D0FF},
+    {0x1D127, 0x1D128},
+    {0x1D1EB, 0x1D1FF},
+    {0x1D246, 0x1D2DF},
+    {0x1D2F4, 0x1D2FF},
+    {0x1D357, 0x1D35F},
+    {0x1D379, 0x1D3FF},
+    {0x1D455, 0x1D455},
+    {0x1D49D, 0x1D49D},
+    {0x1D4A0, 0x1D4A1},
+    {0x1D4A3, 0x1D4A4},
+    {0x1D4A7, 0x1D4A8},
+    {0x1D4AD, 0x1D4AD},
+    {0x1D4BA, 0x1D4BA},
+    {0x1D4BC, 0x1D4BC},
+    {0x1D4C4, 0x1D4C4},
+    {0x1D506, 0x1D506},
+    {0x1D50B, 0x1D50C},
+    {0x1D515, 0x1D515},
+    {0x1D51D, 0x1D51D},
+    {0x1D53A, 0x1D53A},
+    {0x1D53F, 0x1D53F},
+    {0x1D545, 0x1D545},
+    {0x1D547, 0x1D549},
+    {0x1D551, 0x1D551},
+    {0x1D6A6, 0x1D6A7},
+    {0x1D7CC, 0x1D7CD},
+    {0x1DA8C, 0x1DA9A},
+    {0x1DAA0, 0x1DAA0},
+    {0x1DAB0, 0x1DEFF},
+    {0x1DF1F, 0x1DFFF},
+    {0x1E007, 0x1E007},
+    {0x1E019, 0x1E01A},
+    {0x1E022, 0x1E022},
+    {0x1E025, 0x1E025},
+    {0x1E02B, 0x1E0FF},
+    {0x1E12D, 0x1E12F},
+    {0x1E13E, 0x1E13F},
+    {0x1E14A, 0x1E14D},
+    {0x1E150, 0x1E28F},
+    {0x1E2AF, 0x1E2BF},
+    {0x1E2FA, 0x1E2FE},
+    {0x1E300, 0x1E7DF},
+    {0x1E7E7, 0x1E7E7},
+    {0x1E7EC, 0x1E7EC},
+    {0x1E7EF, 0x1E7EF},
+    {0x1E7FF, 0x1E7FF},
+    {0x1E8C5, 0x1E8C6},
+    {0x1E8D7, 0x1E8FF},
+    {0x1E94C, 0x1E94F},
+    {0x1E95A, 0x1E95D},
+    {0x1E960, 0x1EC70},
+    {0x1ECB5, 0x1ED00},
+    {0x1ED3E, 0x1EDFF},
+    {0x1EE04, 0x1EE04},
+    {0x1EE20, 0x1EE20},
+    {0x1EE23, 0x1EE23},
+    {0x1EE25, 0x1EE26},
+    {0x1EE28, 0x1EE28},
+    {0x1EE33, 0x1EE33},
+    {0x1EE38, 0x1EE38},
+    {0x1EE3A, 0x1EE3A},
+    {0x1EE3C, 0x1EE41},
+    {0x1EE43, 0x1EE46},
+    {0x1EE48, 0x1EE48},
+    {0x1EE4A, 0x1EE4A},
+    {0x1EE4C, 0x1EE4C},
+    {0x1EE50, 0x1EE50},
+    {0x1EE53, 0x1EE53},
+    {0x1EE55, 0x1EE56},
+    {0x1EE58, 0x1EE58},
+    {0x1EE5A, 0x1EE5A},
+    {0x1EE5C, 0x1EE5C},
+    {0x1EE5E, 0x1EE5E},
+    {0x1EE60, 0x1EE60},
+    {0x1EE63, 0x1EE63},
+    {0x1EE65, 0x1EE66},
+    {0x1EE6B, 0x1EE6B},
+    {0x1EE73, 0x1EE73},
+    {0x1EE78, 0x1EE78},
+    {0x1EE7D, 0x1EE7D},
+    {0x1EE7F, 0x1EE7F},
+    {0x1EE8A, 0x1EE8A},
+    {0x1EE9C, 0x1EEA0},
+    {0x1EEA4, 0x1EEA4},
+    {0x1EEAA, 0x1EEAA},
+    {0x1EEBC, 0x1EEEF},
+    {0x1EEF2, 0x1EFFF},
+    {0x1F02C, 0x1F02F},
+    {0x1F094, 0x1F09F},
+    {0x1F0AF, 0x1F0B0},
+    {0x1F0C0, 0x1F0C0},
+    {0x1F0D0, 0x1F0D0},
+    {0x1F0F6, 0x1F0FF},
+    {0x1F1AE, 0x1F1E5},
+    {0x1F203, 0x1F20F},
+    {0x1F23C, 0x1F23F},
+    {0x1F249, 0x1F24F},
+    {0x1F252, 0x1F25F},
+    {0x1F266, 0x1F2FF},
+    {0x1F6D8, 0x1F6DC},
+    {0x1F6ED, 0x1F6EF},
+    {0x1F6FD, 0x1F6FF},
+    {0x1F774, 0x1F77F},
+    {0x1F7D9, 0x1F7DF},
+    {0x1F7EC, 0x1F7EF},
+    {0x1F7F1, 0x1F7FF},
+    {0x1F80C, 0x1F80F},
+    {0x1F848, 0x1F84F},
+    {0x1F85A, 0x1F85F},
+    {0x1F888, 0x1F88F},
+    {0x1F8AE, 0x1F8AF},
+    {0x1F8B2, 0x1F8FF},
+    {0x1FA54, 0x1FA5F},
+    {0x1FA6E, 0x1FA6F},
+    {0x1FA75, 0x1FA77},
+    {0x1FA7D, 0x1FA7F},
+    {0x1FA87, 0x1FA8F},
+    {0x1FAAD, 0x1FAAF},
+    {0x1FABB, 0x1FABF},
+    {0x1FAC6, 0x1FACF},
+    {0x1FADA, 0x1FADF},
+    {0x1FAE8, 0x1FAEF},
+    {0x1FAF7, 0x1FAFF},
+    {0x1FB93, 0x1FB93},
+    {0x1FBCB, 0x1FBEF},
+    {0x1FBFA, 0x1FFFD},
+    {0x20001, 0x2A6DE},
+    {0x2A6E0, 0x2A6FF},
+    {0x2A701, 0x2B737},
+    {0x2B739, 0x2B73F},
+    {0x2B741, 0x2B81C},
+    {0x2B81E, 0x2B81F},
+    {0x2B821, 0x2CEA0},
+    {0x2CEA2, 0x2CEAF},
+    {0x2CEB1, 0x2EBDF},
+    {0x2EBE1, 0x2F7FF},
+    {0x2FA1E, 0x2FFFD},
+    {0x30001, 0x31349},
+    {0x3134B, 0x3FFFD},
+    {0x40000, 0x4FFFD},
+    {0x50000, 0x5FFFD},
+    {0x60000, 0x6FFFD},
+    {0x70000, 0x7FFFD},
+    {0x80000, 0x8FFFD},
+    {0x90000, 0x9FFFD},
+    {0xA0000, 0xAFFFD},
+    {0xB0000, 0xBFFFD},
+    {0xC0000, 0xCFFFD},
+    {0xD0000, 0xDFFFD},
+    {0xE0000, 0xE0000},
+    {0xE0002, 0xE001F},
+    {0xE0080, 0xE00FF},
+    {0xE01F0, 0xEFFFD}
+};
+
+/* Non-characters. */
+static const struct widechar_range widechar_nonchar_table[] = {
+    {0x0FDD0, 0x0FDEF},
+    {0x0FFFE, 0x0FFFF},
+    {0x1FFFE, 0x1FFFF},
+    {0x2FFFE, 0x2FFFF},
+    {0x3FFFE, 0x3FFFF},
+    {0x4FFFE, 0x4FFFF},
+    {0x5FFFE, 0x5FFFF},
+    {0x6FFFE, 0x6FFFF},
+    {0x7FFFE, 0x7FFFF},
+    {0x8FFFE, 0x8FFFF},
+    {0x9FFFE, 0x9FFFF},
+    {0xAFFFE, 0xAFFFF},
+    {0xBFFFE, 0xBFFFF},
+    {0xCFFFE, 0xCFFFF},
+    {0xDFFFE, 0xDFFFF},
+    {0xEFFFE, 0xEFFFF},
+    {0xFFFFE, 0xFFFFF},
+    {0x10FFFE, 0x10FFFF}
+};
+
+/* Characters that were widened from width 1 to 2 in Unicode 9. */
+static const struct widechar_range widechar_widened_table[] = {
+    {0x0231A, 0x0231B},
+    {0x023E9, 0x023EC},
+    {0x023F0, 0x023F0},
+    {0x023F3, 0x023F3},
+    {0x025FD, 0x025FE},
+    {0x02614, 0x02615},
+    {0x02648, 0x02653},
+    {0x0267F, 0x0267F},
+    {0x02693, 0x02693},
+    {0x026A1, 0x026A1},
+    {0x026AA, 0x026AB},
+    {0x026BD, 0x026BE},
+    {0x026C4, 0x026C5},
+    {0x026CE, 0x026CE},
+    {0x026D4, 0x026D4},
+    {0x026EA, 0x026EA},
+    {0x026F2, 0x026F3},
+    {0x026F5, 0x026F5},
+    {0x026FA, 0x026FA},
+    {0x026FD, 0x026FD},
+    {0x02705, 0x02705},
+    {0x0270A, 0x0270B},
+    {0x02728, 0x02728},
+    {0x0274C, 0x0274C},
+    {0x0274E, 0x0274E},
+    {0x02753, 0x02755},
+    {0x02757, 0x02757},
+    {0x02795, 0x02797},
+    {0x027B0, 0x027B0},
+    {0x027BF, 0x027BF},
+    {0x02B1B, 0x02B1C},
+    {0x02B50, 0x02B50},
+    {0x02B55, 0x02B55},
+    {0x1F004, 0x1F004},
+    {0x1F0CF, 0x1F0CF},
+    {0x1F18E, 0x1F18E},
+    {0x1F191, 0x1F19A},
+    {0x1F201, 0x1F201},
+    {0x1F21A, 0x1F21A},
+    {0x1F22F, 0x1F22F},
+    {0x1F232, 0x1F236},
+    {0x1F238, 0x1F23A},
+    {0x1F250, 0x1F251},
+    {0x1F300, 0x1F320},
+    {0x1F32D, 0x1F335},
+    {0x1F337, 0x1F37C},
+    {0x1F37E, 0x1F393},
+    {0x1F3A0, 0x1F3CA},
+    {0x1F3CF, 0x1F3D3},
+    {0x1F3E0, 0x1F3F0},
+    {0x1F3F4, 0x1F3F4},
+    {0x1F3F8, 0x1F43E},
+    {0x1F440, 0x1F440},
+    {0x1F442, 0x1F4FC},
+    {0x1F4FF, 0x1F53D},
+    {0x1F54B, 0x1F54E},
+    {0x1F550, 0x1F567},
+    {0x1F595, 0x1F596},
+    {0x1F5FB, 0x1F64F},
+    {0x1F680, 0x1F6C5},
+    {0x1F6CC, 0x1F6CC},
+    {0x1F6D0, 0x1F6D0},
+    {0x1F6EB, 0x1F6EC},
+    {0x1F910, 0x1F918},
+    {0x1F980, 0x1F984},
+    {0x1F9C0, 0x1F9C0}
+};
+
+template<typename Collection>
+bool widechar_in_table(const Collection &arr, uint32_t c) {
+    auto where = std::lower_bound(std::begin(arr), std::end(arr), c,
+        [](widechar_range p, uint32_t c) { return p.hi < c; });
+    return where != std::end(arr) && where->lo <= c;
+}
+
+/* Return the width of character c, or a special negative value. */
+int wcwidth(uint32_t c) {
+    if (widechar_in_table(widechar_ascii_table, c))
+        return 1;
+    if (widechar_in_table(widechar_private_table, c))
+        return widechar_private_use;
+    if (widechar_in_table(widechar_nonprint_table, c))
+        return widechar_nonprint;
+    if (widechar_in_table(widechar_nonchar_table, c))
+        return widechar_non_character;
+    if (widechar_in_table(widechar_combining_table, c))
+        return widechar_combining;
+    if (widechar_in_table(widechar_combiningletters_table, c))
+        return widechar_combining;
+    if (widechar_in_table(widechar_doublewide_table, c))
+        return 2;
+    if (widechar_in_table(widechar_ambiguous_table, c))
+        return widechar_ambiguous;
+    if (widechar_in_table(widechar_unassigned_table, c))
+        return widechar_unassigned;
+    if (widechar_in_table(widechar_widened_table, c))
+        return widechar_widened_in_9;
+    return 1;
+}
+
+} // namespace
+#endif // WIDECHAR_WIDTH_H

+ 70 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/manpage.md

@@ -0,0 +1,70 @@
+% btop(1) | User Commands
+%
+% 2025-05-01
+
+# NAME
+
+btop - Resource monitor that shows usage and stats for processor, memory, disks, network, and processes.
+
+# SYNOPSIS
+
+**btop** [**-c**] [**-d**] [**-l**] [**-t**] [**-p** _id_] [**-u** _ms_] [**\-\-force-utf**] [**\-\-themes-dir** _dir_]
+
+**btop** [{**-h** | **\-\-help**} | {**-V** | **\-\-version**}]
+
+# DESCRIPTION
+
+**btop** is a program that shows usage and stats for processor, memory, disks, network, and processes.
+
+# OPTIONS
+
+The program follows the usual GNU command line syntax, with long options
+starting with two dashes ('-'). A summary of options is included below.
+
+**-c**, **\-\-config _file_**
+:   Path to a config file.
+
+**-d**, **\-\-debug**
+:   Start in debug mode with additional logs and metrics.
+
+**-f**, **\-\-filter _filter_**
+:   Set an initial process filter.
+
+**\-\-force-utf**
+:   Force start even if no UTF-8 locale was detected.
+
+**-l**, **\-\-low-color**
+:   Disable true color, 256 colors only.
+
+**-p**, **\-\-preset _id_**
+:   Start with a preset (0-9).
+
+**-t**, **\-\-tty-on**
+:   Force tty mode with ANSI graph symbols and 16 colors only.
+
+**\-\-tty-off**
+:   Force disable tty mode.
+
+**\-\-themes-dir _dir_**
+:   Path to a custom themes directory. When specified, this directory takes priority over the default theme search paths.
+
+**-u**, **\-\-update _ms_**
+:   Set an initial update rate in milliseconds.
+
+**-h**, **\-\-help**
+:   Show summary of options.
+
+**-V**, **\-\-version**
+:   Show version of program.
+
+# BUGS
+
+The upstream bug tracker can be found at https://github.com/aristocratos/btop/issues.
+
+# SEE ALSO
+
+**top**(1), **htop**(1)
+
+# AUTHOR
+
+**btop** was written by Jakob P. Liljenberg a.k.a. "Aristocratos".

+ 6 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/renovate.json

@@ -0,0 +1,6 @@
+{
+  "$schema": "https://docs.renovatebot.com/renovate-schema.json",
+  "extends": [
+    "config:recommended"
+  ]
+}

+ 10 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/run.sh

@@ -0,0 +1,10 @@
+#!/bin/bash
+DIR="$(cd "$(dirname "$0")" && pwd)"
+if [ -x "$DIR/bin/btop" ]; then
+  exec "$DIR/bin/btop" "$@"
+elif [ -x "$DIR/build/btop" ]; then
+  exec "$DIR/build/btop" "$@"
+else
+  echo "btop binary not found; run make first" >&2
+  exit 1
+fi

+ 64 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/snap/snapcraft.yaml

@@ -0,0 +1,64 @@
+name: btop
+adopt-info: btop
+summary: Resource monitor that shows usage and stats
+description: |
+  Resource monitor that shows usage and stats for processor, memory, disks, network and processes.
+  C++ version and continuation of bashtop and bpytop.
+license: Apache-2.0
+
+base: core24
+grade: stable
+confinement: strict
+compression: lzo
+
+contact: https://github.com/kz6fittycent/btop/issues
+issues: https://github.com/kz6fittycent/btop/issues
+source-code: https://github.com/aristocratos/btop
+
+platforms:
+  amd64:
+    build-on: [amd64]
+    build-for: [amd64]
+  arm64:
+    build-on: [arm64]
+    build-for: [arm64]
+
+apps:
+  btop:
+    command: usr/local/bin/btop
+    environment:
+      LC_ALL: C.UTF-8
+      LANG: C.UTF-8
+    plugs:
+      - mount-observe
+      - process-control
+      - system-observe
+      - hardware-observe
+      - network
+      - network-observe
+      - home
+      - removable-media
+      - opengl
+
+parts:
+  btop:
+    source: https://github.com/aristocratos/btop
+    source-type: git
+    plugin: make
+    make-parameters:
+      - CC=gcc-14
+      - CXX=g++-14
+      - PREFIX=/usr/local
+      - STATIC=true #required
+      - ADDFLAGS="-D SNAPPED" #required
+    build-packages:
+      - coreutils
+      - sed
+      - git
+      - build-essential
+      - gcc-14
+      - g++-14
+    
+    override-pull: |
+      craftctl default
+      craftctl set version="$(git describe --tags | sed 's/^v//' | cut -d "-" -f1)"

+ 1188 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop.cpp

@@ -0,0 +1,1188 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#include "btop.hpp"
+
+#include <algorithm>
+#include <csignal>
+#include <clocale>
+#include <filesystem>
+#include <iterator>
+#include <optional>
+#include <pthread.h>
+#include <span>
+#include <string_view>
+#ifdef __FreeBSD__
+	#include <pthread_np.h>
+#endif
+#include <thread>
+#include <numeric>
+#include <ranges>
+#include <unistd.h>
+#include <cmath>
+#include <iostream>
+#include <exception>
+#include <tuple>
+#include <regex>
+#include <chrono>
+#include <utility>
+#include <semaphore>
+
+#ifdef __APPLE__
+	#include <CoreFoundation/CoreFoundation.h>
+	#include <mach-o/dyld.h>
+	#include <limits.h>
+#endif
+
+#ifdef __NetBSD__
+	#include <sys/param.h>
+	#include <sys/sysctl.h>
+	#include <unistd.h>
+#endif
+
+#include "btop_cli.hpp"
+#include "btop_shared.hpp"
+#include "btop_tools.hpp"
+#include "btop_config.hpp"
+#include "btop_input.hpp"
+#include "btop_theme.hpp"
+#include "btop_draw.hpp"
+#include "btop_menu.hpp"
+#include "fmt/core.h"
+#include "fmt/ostream.h"
+
+using std::atomic;
+using std::cout;
+using std::flush;
+using std::min;
+using std::string;
+using std::string_view;
+using std::to_string;
+using std::vector;
+
+namespace fs = std::filesystem;
+
+using namespace Tools;
+using namespace std::chrono_literals;
+using namespace std::literals;
+
+namespace Global {
+	const vector<array<string, 2>> Banner_src = {
+		{"#E62525", "██████╗ ████████╗ ██████╗ ██████╗"},
+		{"#CD2121", "██╔══██╗╚══██╔══╝██╔═══██╗██╔══██╗   ██╗    ██╗"},
+		{"#B31D1D", "██████╔╝   ██║   ██║   ██║██████╔╝ ██████╗██████╗"},
+		{"#9A1919", "██╔══██╗   ██║   ██║   ██║██╔═══╝  ╚═██╔═╝╚═██╔═╝"},
+		{"#801414", "██████╔╝   ██║   ╚██████╔╝██║        ╚═╝    ╚═╝"},
+		{"#000000", "╚═════╝    ╚═╝    ╚═════╝ ╚═╝"},
+	};
+	const string Version = "1.4.5";
+
+	int coreCount;
+	string overlay;
+	string clock;
+
+	string bg_black = "\x1b[0;40m";
+	string fg_white = "\x1b[1;97m";
+	string fg_green = "\x1b[1;92m";
+	string fg_red = "\x1b[0;91m";
+
+	uid_t real_uid, set_uid;
+
+	fs::path self_path;
+
+	string exit_error_msg;
+	atomic<bool> thread_exception (false);
+
+	bool debug{};
+
+	uint64_t start_time;
+
+	atomic<bool> resized (false);
+	atomic<bool> quitting (false);
+	atomic<bool> should_quit (false);
+	atomic<bool> should_sleep (false);
+	atomic<bool> _runner_started (false);
+	atomic<bool> init_conf (false);
+	atomic<bool> reload_conf (false);
+}
+
+//* Handler for SIGWINCH and general resizing events, does nothing if terminal hasn't been resized unless force=true
+void term_resize(bool force) {
+	static atomic<bool> resizing (false);
+	if (Input::polling) {
+		Global::resized = true;
+		Input::interrupt();
+		return;
+	}
+	atomic_lock lck(resizing, true);
+	if (auto refreshed = Term::refresh(true); refreshed or force) {
+		if (force and refreshed) force = false;
+	}
+	else return;
+#ifdef GPU_SUPPORT
+	static const array<string, 10> all_boxes = {"gpu5", "cpu", "mem", "net", "proc", "gpu0", "gpu1", "gpu2", "gpu3", "gpu4"};
+#else
+	static const array<string, 5> all_boxes = {"", "cpu", "mem", "net", "proc"};
+#endif
+	Global::resized = true;
+	if (Runner::active) Runner::stop();
+	Term::refresh();
+	Config::unlock();
+
+	auto boxes = Config::getS("shown_boxes");
+	auto min_size = Term::get_min_size(boxes);
+	auto minWidth = min_size.at(0), minHeight = min_size.at(1);
+
+	while (not force or (Term::width < minWidth or Term::height < minHeight)) {
+		sleep_ms(100);
+		if (Term::width < minWidth or Term::height < minHeight) {
+			int width = Term::width, height = Term::height;
+			cout << fmt::format("{clear}{bg_black}{fg_white}"
+					"{mv1}Terminal size too small:"
+					"{mv2} Width = {fg_width}{width} {fg_white}Height = {fg_height}{height}"
+					"{mv3}{fg_white}Needed for current config:"
+					"{mv4}Width = {minWidth} Height = {minHeight}",
+					"clear"_a = Term::clear, "bg_black"_a = Global::bg_black, "fg_white"_a = Global::fg_white,
+					"mv1"_a = Mv::to((height / 2) - 2, (width / 2) - 11),
+					"mv2"_a = Mv::to((height / 2) - 1, (width / 2) - 10),
+						"fg_width"_a = (width < minWidth ? Global::fg_red : Global::fg_green),
+						"width"_a = width,
+						"fg_height"_a = (height < minHeight ? Global::fg_red : Global::fg_green),
+						"height"_a = height,
+					"mv3"_a = Mv::to((height / 2) + 1, (width / 2) - 12),
+					"mv4"_a = Mv::to((height / 2) + 2, (width / 2) - 10),
+						"minWidth"_a = minWidth,
+						"minHeight"_a = minHeight
+			) << std::flush;
+
+			bool got_key = false;
+			for (; not Term::refresh() and not got_key; got_key = Input::poll(10));
+			if (got_key) {
+				auto key = Input::get();
+				if (key == "q")
+					clean_quit(0);
+				else if (key.size() == 1 and isint(key)) {
+					auto intKey = stoi(key);
+				#ifdef GPU_SUPPORT
+					if ((intKey == 0 and Gpu::count >= 5) or (intKey >= 5 and intKey - 4 <= Gpu::count)) {
+				#else
+					if (intKey > 0 and intKey < 5) {
+				#endif
+						const auto& box = all_boxes.at(intKey);
+						Config::current_preset = -1;
+						Config::toggle_box(box);
+						boxes = Config::getS("shown_boxes");
+					}
+				}
+			}
+			min_size = Term::get_min_size(boxes);
+			minWidth = min_size.at(0);
+			minHeight = min_size.at(1);
+		}
+		else if (not Term::refresh()) break;
+	}
+
+	Input::interrupt();
+}
+
+//* Exit handler; stops threads, restores terminal and saves config changes
+void clean_quit(int sig) {
+	if (Global::quitting) return;
+	Global::quitting = true;
+	Runner::stop();
+	if (Global::_runner_started) {
+	#if defined __APPLE__ || defined __OpenBSD__ || defined __NetBSD__
+		if (pthread_join(Runner::runner_id, nullptr) != 0) {
+			Logger::warning("Failed to join _runner thread on exit!");
+			pthread_cancel(Runner::runner_id);
+		}
+	#else
+		constexpr struct timespec ts { .tv_sec = 5, .tv_nsec = 0 };
+		if (pthread_timedjoin_np(Runner::runner_id, nullptr, &ts) != 0) {
+			Logger::warning("Failed to join _runner thread on exit!");
+			pthread_cancel(Runner::runner_id);
+		}
+	#endif
+	}
+
+#ifdef GPU_SUPPORT
+	Gpu::Nvml::shutdown();
+	Gpu::Rsmi::shutdown();
+#endif
+
+	Config::write();
+
+	if (Term::initialized) {
+		Input::clear();
+		Term::restore();
+	}
+
+	if (not Global::exit_error_msg.empty()) {
+		sig = 1;
+		Logger::error(Global::exit_error_msg);
+		fmt::println(std::cerr, "{}ERROR: {}{}{}", Global::fg_red, Global::fg_white, Global::exit_error_msg, Fx::reset);
+	}
+	Logger::info("Quitting! Runtime: " + sec_to_dhms(time_s() - Global::start_time));
+
+	const auto excode = (sig != -1 ? sig : 0);
+
+#if defined __APPLE__ || defined __OpenBSD__ || defined __NetBSD__
+	_Exit(excode);
+#else
+	quick_exit(excode);
+#endif
+}
+
+//* Handler for SIGTSTP; stops threads, restores terminal and sends SIGSTOP
+static void _sleep() {
+	Runner::stop();
+	Term::restore();
+	std::raise(SIGSTOP);
+}
+
+//* Handler for SIGCONT; re-initialize terminal and force a resize event
+static void _resume() {
+	Term::init();
+	term_resize(true);
+}
+
+static void _exit_handler() {
+	clean_quit(-1);
+}
+
+static void _crash_handler(const int sig) {
+	// Restore terminal before crashing
+	if (Term::initialized) {
+		Term::restore();
+	}
+	// Re-raise the signal to get default behavior (core dump)
+	std::signal(sig, SIG_DFL);
+	std::raise(sig);
+}
+
+static void _signal_handler(const int sig) {
+	switch (sig) {
+		case SIGINT:
+			if (Runner::active) {
+				Global::should_quit = true;
+				Runner::stopping = true;
+				Input::interrupt();
+			}
+			else {
+				clean_quit(0);
+			}
+			break;
+		case SIGTSTP:
+			if (Runner::active) {
+				Global::should_sleep = true;
+				Runner::stopping = true;
+				Input::interrupt();
+			}
+			else {
+				_sleep();
+			}
+			break;
+		case SIGCONT:
+			_resume();
+			break;
+		case SIGWINCH:
+			term_resize();
+			break;
+		case SIGUSR1:
+			// Input::poll interrupt
+			break;
+		case SIGUSR2:
+			Global::reload_conf = true;
+			Input::interrupt();
+			break;
+	}
+}
+
+//* Config init
+void init_config(bool low_color, std::optional<std::string>& filter) {
+	atomic_lock lck(Global::init_conf);
+	vector<string> load_warnings;
+	Config::load(Config::conf_file, load_warnings);
+	Config::set("lowcolor", (low_color ? true : not Config::getB("truecolor")));
+
+	static bool first_init = true;
+
+	if (Global::debug and first_init) {
+		Logger::set("DEBUG");
+		Logger::debug("Running in DEBUG mode!");
+	}
+	else Logger::set(Config::getS("log_level"));
+
+	if (filter.has_value()) {
+		Config::set("proc_filter", filter.value());
+	}
+
+	static string log_level;
+	if (const string current_level = Config::getS("log_level"); log_level != current_level) {
+		log_level = current_level;
+		Logger::info("Logger set to " + (Global::debug ? "DEBUG" : log_level));
+	}
+
+	for (const auto& err_str : load_warnings) Logger::warning(err_str);
+	first_init = false;
+}
+
+//* Manages secondary thread for collection and drawing of boxes
+namespace Runner {
+	atomic<bool> active (false);
+	atomic<bool> stopping (false);
+	atomic<bool> waiting (false);
+	atomic<bool> redraw (false);
+	atomic<bool> coreNum_reset (false);
+
+	//* Setup semaphore for triggering thread to do work
+	// TODO: This can be made a local without too much effort.
+	std::binary_semaphore do_work { 0 };
+	inline void thread_wait() { do_work.acquire(); }
+	inline void thread_trigger() { do_work.release(); }
+
+	//* RAII wrapper for pthread_mutex locking
+	class thread_lock {
+		pthread_mutex_t& pt_mutex;
+	public:
+		int status;
+		explicit thread_lock(pthread_mutex_t& mtx) : pt_mutex(mtx) {
+			pthread_mutex_init(&pt_mutex, nullptr);
+			status = pthread_mutex_lock(&pt_mutex);
+		}
+		~thread_lock() noexcept {
+			if (status == 0)
+				pthread_mutex_unlock(&pt_mutex);
+		}
+		thread_lock(const thread_lock& other) = delete;
+		thread_lock& operator=(const thread_lock& other) = delete;
+		thread_lock(thread_lock&& other) = delete;
+		thread_lock& operator=(thread_lock&& other) = delete;
+	};
+
+	//* Wrapper for raising privileges when using SUID bit
+	class gain_priv {
+		int status = -1;
+	public:
+		gain_priv() {
+			if (Global::real_uid != Global::set_uid)
+				this->status = seteuid(Global::set_uid);
+		}
+		~gain_priv() noexcept {
+			if (status == 0)
+				status = seteuid(Global::real_uid);
+		}
+		gain_priv(const gain_priv& other) = delete;
+		gain_priv& operator=(const gain_priv& other) = delete;
+		gain_priv(gain_priv&& other) = delete;
+		gain_priv& operator=(gain_priv&& other) = delete;
+	};
+
+	string output;
+	string empty_bg;
+	bool pause_output{};
+	sigset_t mask;
+	pthread_t runner_id;
+	pthread_mutex_t mtx;
+
+	enum debug_actions {
+		collect_begin,
+		collect_done,
+		draw_begin,
+		draw_begin_only,
+		draw_done
+	};
+
+	enum debug_array {
+		collect,
+		draw
+	};
+
+	string debug_bg;
+	std::unordered_map<string, array<uint64_t, 2>> debug_times;
+
+	class MyNumPunct : public std::numpunct<char>
+	{
+	protected:
+		virtual char do_thousands_sep() const override { return '\''; }
+		virtual std::string do_grouping() const override { return "\03"; }
+	};
+
+
+	struct runner_conf {
+		vector<string> boxes;
+		bool no_update;
+		bool force_redraw;
+		bool background_update;
+		string overlay;
+		string clock;
+	};
+
+	struct runner_conf current_conf;
+
+	static void debug_timer(const char* name, const int action) {
+		switch (action) {
+			case collect_begin:
+				debug_times[name].at(collect) = time_micros();
+				return;
+			case collect_done:
+				debug_times[name].at(collect) = time_micros() - debug_times[name].at(collect);
+				debug_times["total"].at(collect) += debug_times[name].at(collect);
+				return;
+			case draw_begin_only:
+				debug_times[name].at(draw) = time_micros();
+				return;
+			case draw_begin:
+				debug_times[name].at(draw) = time_micros();
+				debug_times[name].at(collect) = debug_times[name].at(draw) - debug_times[name].at(collect);
+				debug_times["total"].at(collect) += debug_times[name].at(collect);
+				return;
+			case draw_done:
+				debug_times[name].at(draw) = time_micros() - debug_times[name].at(draw);
+				debug_times["total"].at(draw) += debug_times[name].at(draw);
+				return;
+		}
+	}
+
+	//? ------------------------------- Secondary thread: async launcher and drawing ----------------------------------
+	static void * _runner(void *) {
+		//? Block some signals in this thread to avoid deadlock from any signal handlers trying to stop this thread
+		sigemptyset(&mask);
+		// sigaddset(&mask, SIGINT);
+		// sigaddset(&mask, SIGTSTP);
+		sigaddset(&mask, SIGWINCH);
+		sigaddset(&mask, SIGTERM);
+		pthread_sigmask(SIG_BLOCK, &mask, nullptr);
+
+		//? pthread_mutex_lock to lock thread and monitor health from main thread
+		thread_lock pt_lck(mtx);
+		if (pt_lck.status != 0) {
+			Global::exit_error_msg = "Exception in runner thread -> pthread_mutex_lock error id: " + to_string(pt_lck.status);
+			Global::thread_exception = true;
+			Input::interrupt();
+			stopping = true;
+		}
+
+		//* ----------------------------------------------- THREAD LOOP -----------------------------------------------
+		while (not Global::quitting) {
+			thread_wait();
+			atomic_wait_for(active, true, 5000);
+			if (active) {
+				Global::exit_error_msg = "Runner thread failed to get active lock!";
+				Global::thread_exception = true;
+				Input::interrupt();
+				stopping = true;
+			}
+			if (stopping or Global::resized) {
+				sleep_ms(1);
+				continue;
+			}
+
+			//? Atomic lock used for blocking non thread-safe actions in main thread
+			atomic_lock lck(active);
+
+			//? Set effective user if SUID bit is set
+			gain_priv powers{};
+
+			auto& conf = current_conf;
+
+			//! DEBUG stats
+			if (Global::debug) {
+                if (debug_bg.empty() or redraw)
+                    Runner::debug_bg = Draw::createBox(2, 2, 33,
+					#ifdef GPU_SUPPORT
+						9,
+					#else
+						8,
+					#endif
+					"", true, "μs");
+
+				debug_times.clear();
+				debug_times["total"] = {0, 0};
+			}
+
+			output.clear();
+
+			//* Run collection and draw functions for all boxes
+			try {
+			#ifdef GPU_SUPPORT
+				//? GPU data collection
+				const bool gpu_in_cpu_panel = Gpu::gpu_names.size() > 0 and (
+					Config::getS("cpu_graph_lower").starts_with("gpu-")
+					or (Config::getS("cpu_graph_lower") == "Auto")
+					or Config::getS("cpu_graph_upper").starts_with("gpu-")
+					or (Gpu::shown == 0 and Config::getS("show_gpu_info") != "Off")
+				);
+
+				vector<unsigned int> gpu_panels = {};
+				for (auto& box : conf.boxes)
+					if (box.starts_with("gpu"))
+						gpu_panels.push_back(box.back()-'0');
+
+				vector<Gpu::gpu_info> gpus;
+				if (gpu_in_cpu_panel or not gpu_panels.empty()) {
+					if (Global::debug) debug_timer("gpu", collect_begin);
+					gpus = Gpu::collect(conf.no_update);
+					if (Global::debug) debug_timer("gpu", collect_done);
+				}
+				auto& gpus_ref = gpus;
+			#else
+				vector<Gpu::gpu_info> gpus_ref{};
+			#endif
+
+				//? CPU
+				if (v_contains(conf.boxes, "cpu")) {
+					try {
+						if (Global::debug) debug_timer("cpu", collect_begin);
+
+						//? Start collect
+						auto cpu = Cpu::collect(conf.no_update);
+
+						if (coreNum_reset) {
+							coreNum_reset = false;
+							Cpu::core_mapping = Cpu::get_core_mapping();
+							Global::resized = true;
+							Input::interrupt();
+							continue;
+						}
+
+						if (Global::debug) debug_timer("cpu", draw_begin);
+
+						//? Draw box
+						if (not pause_output) output += Cpu::draw(cpu, gpus_ref, conf.force_redraw, conf.no_update);
+
+						if (Global::debug) debug_timer("cpu", draw_done);
+					}
+					catch (const std::exception& e) {
+						throw std::runtime_error("Cpu:: -> " + string{e.what()});
+					}
+				}
+			#ifdef GPU_SUPPORT
+				//? GPU
+				if (not gpu_panels.empty() and not gpus_ref.empty()) {
+					try {
+						if (Global::debug) debug_timer("gpu", draw_begin_only);
+
+						//? Draw box
+						if (not pause_output)
+							for (unsigned long i = 0; i < gpu_panels.size(); ++i)
+								output += Gpu::draw(gpus_ref[gpu_panels[i]], i, conf.force_redraw, conf.no_update);
+
+						if (Global::debug) debug_timer("gpu", draw_done);
+					}
+					catch (const std::exception& e) {
+                        throw std::runtime_error("Gpu:: -> " + string{e.what()});
+					}
+				}
+			#endif
+				//? MEM
+				if (v_contains(conf.boxes, "mem")) {
+					try {
+						if (Global::debug) debug_timer("mem", collect_begin);
+
+						//? Start collect
+						auto mem = Mem::collect(conf.no_update);
+
+						if (Global::debug) debug_timer("mem", draw_begin);
+
+						//? Draw box
+						if (not pause_output) output += Mem::draw(mem, conf.force_redraw, conf.no_update);
+
+						if (Global::debug) debug_timer("mem", draw_done);
+					}
+					catch (const std::exception& e) {
+						throw std::runtime_error("Mem:: -> " + string{e.what()});
+					}
+				}
+
+				//? NET
+				if (v_contains(conf.boxes, "net")) {
+					try {
+						if (Global::debug) debug_timer("net", collect_begin);
+
+						//? Start collect
+						auto net = Net::collect(conf.no_update);
+
+						if (Global::debug) debug_timer("net", draw_begin);
+
+						//? Draw box
+						if (not pause_output) output += Net::draw(net, conf.force_redraw, conf.no_update);
+
+						if (Global::debug) debug_timer("net", draw_done);
+					}
+					catch (const std::exception& e) {
+						throw std::runtime_error("Net:: -> " + string{e.what()});
+					}
+				}
+
+				//? PROC
+				if (v_contains(conf.boxes, "proc")) {
+					try {
+						if (Global::debug) debug_timer("proc", collect_begin);
+
+						//? Start collect
+						auto proc = Proc::collect(conf.no_update);
+
+						if (Global::debug) debug_timer("proc", draw_begin);
+
+						//? Draw box
+						if (not pause_output) output += Proc::draw(proc, conf.force_redraw, conf.no_update);
+
+						if (Global::debug) debug_timer("proc", draw_done);
+					}
+					catch (const std::exception& e) {
+						throw std::runtime_error("Proc:: -> " + string{e.what()});
+					}
+				}
+
+			}
+			catch (const std::exception& e) {
+				Global::exit_error_msg = "Exception in runner thread -> " + string{e.what()};
+				Global::thread_exception = true;
+				Input::interrupt();
+				stopping = true;
+			}
+
+			if (stopping) {
+				continue;
+			}
+
+			if (redraw or conf.force_redraw) {
+				empty_bg.clear();
+				redraw = false;
+			}
+
+			if (not pause_output) output += conf.clock;
+			if (not conf.overlay.empty() and not conf.background_update) pause_output = true;
+			if (output.empty() and not pause_output) {
+				if (empty_bg.empty()) {
+					const int x = Term::width / 2 - 10, y = Term::height / 2 - 10;
+					output += Term::clear;
+					empty_bg = fmt::format(
+						"{banner}"
+						"{mv1}{titleFg}{b}AltData Monitor"
+						"{mv2}{hiFg}1 {mainFg}| Show NET box"
+						"{mv3}{hiFg}2 {mainFg}| Show PROC box"
+						"{mv4}{hiFg}q {mainFg}| Quit",
+						"banner"_a = Draw::banner_gen(y, 0, true),
+						"titleFg"_a = Theme::c("title"), "b"_a = Fx::b, "hiFg"_a = Theme::c("hi_fg"), "mainFg"_a = Theme::c("main_fg"),
+						"mv1"_a = Mv::to(y+6, x),
+						"mv2"_a = Mv::to(y+8, x),
+						"mv3"_a = Mv::to(y+9, x),
+						"mv4"_a = Mv::to(y+10, x)
+					);
+				}
+				output += empty_bg;
+			}
+
+			//! DEBUG stats -->
+			if (Global::debug and not Menu::active) {
+				output += fmt::format("{pre}{box:5.5} {collect:>12.12} {draw:>12.12}{post}",
+					"pre"_a = debug_bg + Theme::c("title") + Fx::b,
+					"box"_a = "box", "collect"_a = "collect", "draw"_a = "draw",
+					"post"_a = Theme::c("main_fg") + Fx::ub
+				);
+				static auto loc = std::locale(std::locale::classic(), new MyNumPunct);
+			#ifdef GPU_SUPPORT
+				for (const string name : {"cpu", "mem", "net", "proc", "gpu", "total"}) {
+			#else
+				for (const string name : {"cpu", "mem", "net", "proc", "total"}) {
+			#endif
+					if (not debug_times.contains(name)) debug_times[name] = {0,0};
+					const auto& [time_collect, time_draw] = debug_times.at(name);
+					if (name == "total") output += Fx::b;
+					output += fmt::format(loc, "{mvLD}{name:5.5} {collect:12L} {draw:12L}",
+						"mvLD"_a = Mv::l(31) + Mv::d(1),
+						"name"_a = name,
+						"collect"_a = time_collect,
+						"draw"_a = time_draw
+					);
+				}
+			}
+
+			//? If overlay isn't empty, print output without color and then print overlay on top
+			const bool term_sync = Config::getB("terminal_sync");
+			cout << (term_sync ? Term::sync_start : "") << (conf.overlay.empty()
+					? output
+					: (output.empty() ? "" : Fx::ub + Theme::c("inactive_fg") + Fx::uncolor(output)) + conf.overlay)
+				<< (term_sync ? Term::sync_end : "") << flush;
+		}
+		//* ----------------------------------------------- THREAD LOOP -----------------------------------------------
+		return {};
+	}
+	//? ------------------------------------------ Secondary thread end -----------------------------------------------
+
+	//* Runs collect and draw in a secondary thread, unlocks and locks config to update cached values
+	void run(const string& box, bool no_update, bool force_redraw) {
+		atomic_wait_for(active, true, 5000);
+		if (active) {
+			Logger::error("Stall in Runner thread, restarting!");
+			active = false;
+			// exit(1);
+			pthread_cancel(Runner::runner_id);
+
+			// Wait for the thread to actually terminate before creating a new one
+			void* thread_result;
+			int join_result = pthread_join(Runner::runner_id, &thread_result);
+			if (join_result != 0) {
+				Logger::warning("Failed to join cancelled thread: " + string(strerror(join_result)));
+			}
+
+			if (pthread_create(&Runner::runner_id, nullptr, &Runner::_runner, nullptr) != 0) {
+				Global::exit_error_msg = "Failed to re-create _runner thread!";
+				clean_quit(1);
+			}
+		}
+		if (stopping or Global::resized) return;
+
+		if (box == "overlay") {
+			const bool term_sync = Config::getB("terminal_sync");
+			cout << (term_sync ? Term::sync_start : "") << Global::overlay << (term_sync ? Term::sync_end : "") << flush;
+		}
+		else if (box == "clock") {
+			const bool term_sync = Config::getB("terminal_sync");
+			cout << (term_sync ? Term::sync_start : "") << Global::clock << (term_sync ? Term::sync_end : "") << flush;
+		}
+		else {
+			Config::unlock();
+			Config::lock();
+
+			current_conf = {
+				(box == "all" ? Config::current_boxes : vector{box}),
+				no_update, force_redraw,
+				(not Config::getB("tty_mode") and Config::getB("background_update")),
+				Global::overlay,
+				Global::clock
+			};
+
+			if (Menu::active and not current_conf.background_update) Global::overlay.clear();
+
+			thread_trigger();
+			atomic_wait_for(active, false, 10);
+		}
+
+
+	}
+
+	//* Stops any work being done in runner thread and checks for thread errors
+	void stop() {
+		stopping = true;
+		int ret = pthread_mutex_trylock(&mtx);
+		if (ret != EBUSY and not Global::quitting) {
+			if (active) active = false;
+			Global::exit_error_msg = "Runner thread died unexpectedly!";
+			clean_quit(1);
+		}
+		else if (ret == EBUSY) {
+			atomic_wait_for(active, true, 5000);
+			if (active) {
+				active = false;
+				if (Global::quitting) {
+					return;
+				}
+				else {
+					Global::exit_error_msg = "No response from Runner thread, quitting!";
+					clean_quit(1);
+				}
+			}
+			thread_trigger();
+			atomic_wait_for(active, false, 100);
+			atomic_wait_for(active, true, 100);
+		}
+		stopping = false;
+	}
+
+}
+
+static auto configure_tty_mode(std::optional<bool> force_tty) {
+	if (force_tty.has_value()) {
+		Config::set("tty_mode", force_tty.value());
+		Logger::debug("TTY mode set via command line");
+  	}
+
+#if !defined(__APPLE__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
+	else if (Term::current_tty.starts_with("/dev/tty")) {
+		Config::set("tty_mode", true);
+		Logger::debug("Auto detect real TTY");
+  	}
+#endif
+
+	Logger::debug(fmt::format("TTY mode enabled: {}", Config::getB("tty_mode")));
+}
+
+
+//* --------------------------------------------- Main starts here! ---------------------------------------------------
+[[nodiscard]] auto btop_main(const std::span<const std::string_view> args) -> int {
+
+	//? ------------------------------------------------ INIT ---------------------------------------------------------
+
+	Global::start_time = time_s();
+
+	//? Save real and effective userid's and drop privileges until needed if running with SUID bit set
+	Global::real_uid = getuid();
+	Global::set_uid = geteuid();
+	if (Global::real_uid != Global::set_uid) {
+		if (seteuid(Global::real_uid) != 0) {
+			Global::real_uid = Global::set_uid;
+			Global::exit_error_msg = "Failed to change effective user ID. Unset btop SUID bit to ensure security on this system. Quitting!";
+			clean_quit(1);
+		}
+	}
+
+	Cli::Cli cli;
+	{
+		// Get the cli options or return with an exit code
+		auto result = Cli::parse(args);
+		if (result.has_value()) {
+			cli = result.value();
+		} else {
+			auto error = result.error();
+			if (error != 0) {
+				Cli::usage();
+				Cli::help_hint();
+			}
+			return error;
+		}
+	}
+
+	Global::debug = cli.debug;
+
+	{
+		const auto config_dir = Config::get_config_dir();
+		if (config_dir.has_value()) {
+			Config::conf_dir = config_dir.value();
+			if (cli.config_file.has_value()) {
+				Config::conf_file = cli.config_file.value();
+			} else {
+				Config::conf_file = Config::conf_dir / "btop.conf";
+			}
+			Logger::logfile = Config::get_log_file();
+			Theme::user_theme_dir = Config::conf_dir / "themes";
+
+			// If necessary create the user theme directory
+			std::error_code error;
+			if (not fs::exists(Theme::user_theme_dir, error) and not fs::create_directories(Theme::user_theme_dir, error)) {
+				Theme::user_theme_dir.clear();
+				Logger::warning("Failed to create user theme directory: " + error.message());
+			}
+		}
+	}
+
+	//? Try to find global btop theme path relative to binary path
+#ifdef __linux__
+	{ 	std::error_code ec;
+		Global::self_path = fs::read_symlink("/proc/self/exe", ec).remove_filename();
+	}
+#elif __APPLE__
+	{
+		char buf [PATH_MAX];
+		uint32_t bufsize = PATH_MAX;
+		if(!_NSGetExecutablePath(buf, &bufsize))
+			Global::self_path = fs::path(buf).remove_filename();
+	}
+#elif __NetBSD__
+	{
+		int mib[4];
+		char buf[PATH_MAX];
+		size_t bufsize = sizeof buf;
+
+		mib[0] = CTL_KERN;
+		mib[1] = KERN_PROC_ARGS;
+		mib[2] = getpid();
+		mib[3] = KERN_PROC_PATHNAME;
+		if (sysctl(mib, 4, buf, &bufsize, NULL, 0) == 0)
+			Global::self_path = fs::path(buf).remove_filename();
+	}
+#endif
+	if (std::error_code ec; not Global::self_path.empty()) {
+		Theme::theme_dir = fs::canonical(Global::self_path / "../share/btop/themes", ec);
+		if (ec or not fs::is_directory(Theme::theme_dir) or access(Theme::theme_dir.c_str(), R_OK) == -1) Theme::theme_dir.clear();
+	}
+	//? If relative path failed, check two most common absolute paths
+	if (Theme::theme_dir.empty()) {
+		for (auto theme_path : {"/usr/local/share/btop/themes", "/usr/share/btop/themes"}) {
+			if (fs::is_directory(fs::path(theme_path)) and access(theme_path, R_OK) != -1) {
+				Theme::theme_dir = fs::path(theme_path);
+				break;
+			}
+		}
+	}
+
+	//? Set custom themes directory from command line if provided
+	if (cli.themes_dir.has_value()) {
+		Theme::custom_theme_dir = cli.themes_dir.value();
+		Logger::info("Using custom themes directory: " + Theme::custom_theme_dir.string());
+	}
+
+	//? Config init
+	init_config(cli.low_color, cli.filter);
+
+	//? Try to find and set a UTF-8 locale
+	if (std::setlocale(LC_ALL, "") != nullptr and not std::string_view { std::setlocale(LC_ALL, "") }.contains(";")
+	and str_to_upper(s_replace((string)std::setlocale(LC_ALL, ""), "-", "")).ends_with("UTF8")) {
+		Logger::debug("Using locale " + std::locale().name());
+	}
+	else {
+		string found;
+		bool set_failure{};
+		for (const auto loc_env : array{"LANG", "LC_ALL", "LC_CTYPE"}) {
+			if (std::getenv(loc_env) != nullptr and str_to_upper(s_replace((string)std::getenv(loc_env), "-", "")).ends_with("UTF8")) {
+				found = std::getenv(loc_env);
+				if (std::setlocale(LC_ALL, found.c_str()) == nullptr) {
+					set_failure = true;
+					Logger::warning("Failed to set locale " + found + " continuing anyway.");
+				}
+			}
+		}
+		if (found.empty()) {
+			if (setenv("LC_ALL", "", 1) == 0 and setenv("LANG", "", 1) == 0) {
+				try {
+					if (const auto loc = std::locale("").name(); not loc.empty() and loc != "*") {
+						for (auto& l : ssplit(loc, ';')) {
+							if (str_to_upper(s_replace(l, "-", "")).ends_with("UTF8")) {
+								found = l.substr(l.find('=') + 1);
+								if (std::setlocale(LC_ALL, found.c_str()) != nullptr) {
+									break;
+								}
+							}
+						}
+					}
+				}
+				catch (...) { found.clear(); }
+			}
+		}
+	//
+	#ifdef __APPLE__
+		if (found.empty()) {
+			CFLocaleRef cflocale = CFLocaleCopyCurrent();
+			CFStringRef id_value = (CFStringRef)CFLocaleGetValue(cflocale, kCFLocaleIdentifier);
+			auto loc_id = CFStringGetCStringPtr(id_value, kCFStringEncodingUTF8);
+			CFRelease(cflocale);
+			std::string cur_locale = (loc_id != nullptr ? loc_id : "");
+			if (cur_locale.empty()) {
+				Logger::warning("No UTF-8 locale detected! Some symbols might not display correctly.");
+			}
+			else if (std::setlocale(LC_ALL, string(cur_locale + ".UTF-8").c_str()) != nullptr) {
+				Logger::debug("Setting LC_ALL=" + cur_locale + ".UTF-8");
+			}
+			else if(std::setlocale(LC_ALL, "en_US.UTF-8") != nullptr) {
+				Logger::debug("Setting LC_ALL=en_US.UTF-8");
+			}
+			else {
+				Logger::warning("Failed to set macos locale, continuing anyway.");
+			}
+		}
+	#else
+		if (found.empty() and cli.force_utf) {
+			Logger::warning("No UTF-8 locale detected! Forcing start with --force-utf argument.");
+		} else if (found.empty()) {
+			Global::exit_error_msg = "No UTF-8 locale detected!\nUse --force-utf argument to force start if you're sure your terminal can handle it.";
+			clean_quit(1);
+		}
+	#endif
+		else if (not set_failure) {
+			Logger::debug("Setting LC_ALL=" + found);
+		}
+	}
+
+	//? Initialize terminal and set options
+	if (not Term::init()) {
+		Global::exit_error_msg = "No tty detected!\nbtop++ needs an interactive shell to run.";
+		clean_quit(1);
+	}
+
+	if (Term::current_tty != "unknown") {
+		Logger::info("Running on " + Term::current_tty);
+	}
+
+	configure_tty_mode(cli.force_tty);
+
+	//? Check for valid terminal dimensions
+	{
+		int t_count = 0;
+		while (Term::width <= 0 or Term::width > 10000 or Term::height <= 0 or Term::height > 10000) {
+			sleep_ms(10);
+			Term::refresh();
+			if (++t_count == 100) {
+				Global::exit_error_msg = "Failed to get size of terminal!";
+				clean_quit(1);
+			}
+		}
+	}
+
+	//? Platform dependent init and error check
+	try {
+		Shared::init();
+	}
+	catch (const std::exception& e) {
+		Global::exit_error_msg = "Exception in Shared::init() -> " + string{e.what()};
+		clean_quit(1);
+	}
+
+	if (not Config::set_boxes(Config::getS("shown_boxes"))) {
+		Config::set_boxes("cpu mem net proc");
+		Config::set("shown_boxes", "cpu mem net proc"s);
+	}
+
+	//? Update list of available themes and generate the selected theme
+	Theme::updateThemes();
+	Theme::setTheme();
+
+	//? Setup signal handlers for CTRL-C, CTRL-Z, resume and terminal resize
+	std::atexit(_exit_handler);
+	std::signal(SIGINT, _signal_handler);
+	std::signal(SIGTSTP, _signal_handler);
+	std::signal(SIGCONT, _signal_handler);
+	std::signal(SIGWINCH, _signal_handler);
+	std::signal(SIGUSR1, _signal_handler);
+	std::signal(SIGUSR2, _signal_handler);
+	// Add crash handlers to restore terminal on crash
+	std::signal(SIGSEGV, _crash_handler);
+	std::signal(SIGABRT, _crash_handler);
+	std::signal(SIGTRAP, _crash_handler);
+	std::signal(SIGBUS, _crash_handler);
+	std::signal(SIGILL, _crash_handler);
+
+	sigset_t mask;
+	sigemptyset(&mask);
+	sigaddset(&mask, SIGUSR1);
+	pthread_sigmask(SIG_BLOCK, &mask, &Input::signal_mask);
+
+	if (pthread_create(&Runner::runner_id, nullptr, &Runner::_runner, nullptr) != 0) {
+		Global::exit_error_msg = "Failed to create _runner thread!";
+		clean_quit(1);
+	}
+	else {
+		Global::_runner_started = true;
+	}
+
+	//? Calculate sizes of all boxes
+	Config::presetsValid(Config::getS("presets"));
+	if (cli.preset.has_value()) {
+		Config::current_preset = min(static_cast<std::int32_t>(cli.preset.value()), static_cast<std::int32_t>(Config::preset_list.size() - 1));
+		Config::apply_preset(Config::preset_list.at(Config::current_preset));
+	}
+
+	{
+		const auto [x, y] = Term::get_min_size(Config::getS("shown_boxes"));
+		if (Term::height < y or Term::width < x) {
+			pthread_sigmask(SIG_SETMASK, &Input::signal_mask, &mask);
+			term_resize(true);
+			pthread_sigmask(SIG_SETMASK, &mask, nullptr);
+			Global::resized = false;
+		}
+
+	}
+
+	Draw::calcSizes();
+
+	//? Print out box outlines
+	const bool term_sync = Config::getB("terminal_sync");
+	cout << (term_sync ? Term::sync_start : "") << Cpu::box << Mem::box << Net::box << Proc::box << (term_sync ? Term::sync_end : "") << flush;
+
+
+	//? ------------------------------------------------ MAIN LOOP ----------------------------------------------------
+
+	if (cli.updates.has_value()) {
+		Config::set("update_ms", static_cast<int>(cli.updates.value()));
+	}
+	uint64_t update_ms = Config::getI("update_ms");
+	auto future_time = time_ms();
+
+	try {
+		while (not true not_eq not false) {
+			//? Check for exceptions in secondary thread and exit with fail signal if true
+			if (Global::thread_exception) {
+				clean_quit(1);
+			}
+			else if (Global::should_quit) {
+				clean_quit(0);
+			}
+			else if (Global::should_sleep) {
+				Global::should_sleep = false;
+				_sleep();
+			}
+			//? Hot reload config from CTRL + R or SIGUSR2
+			else if (Global::reload_conf) {
+				Global::reload_conf = false;
+				if (Runner::active) Runner::stop();
+				Config::unlock();
+				init_config(cli.low_color, cli.filter);
+				Theme::updateThemes();
+				Theme::setTheme();
+				Draw::banner_gen(0, 0, false, true);
+				Global::resized = true;
+			}
+
+			//? Make sure terminal size hasn't changed (in case of SIGWINCH not working properly)
+			term_resize(Global::resized);
+
+			//? Trigger secondary thread to redraw if terminal has been resized
+			if (Global::resized) {
+				Draw::calcSizes();
+				Draw::update_clock(true);
+				Global::resized = false;
+				if (Menu::active) Menu::process();
+				else Runner::run("all", true, true);
+				atomic_wait_for(Runner::active, true, 1000);
+			}
+
+			//? Update clock if needed
+			if (Draw::update_clock() and not Menu::active) {
+				Runner::run("clock");
+			}
+
+			//? Start secondary collect & draw thread at the interval set by <update_ms> config value
+			if (time_ms() >= future_time and not Global::resized) {
+				Runner::run("all");
+				update_ms = Config::getI("update_ms");
+				future_time = time_ms() + update_ms;
+			}
+
+			//? Loop over input polling and input action processing
+			for (auto current_time = time_ms(); current_time < future_time; current_time = time_ms()) {
+
+				//? Check for external clock changes and for changes to the update timer
+				if (std::cmp_not_equal(update_ms, Config::getI("update_ms"))) {
+					update_ms = Config::getI("update_ms");
+					future_time = time_ms() + update_ms;
+				}
+				else if (future_time - current_time > update_ms) {
+					future_time = current_time;
+				}
+				//? Poll for input and process any input detected
+				else if (Input::poll(min((uint64_t)1000, future_time - current_time))) {
+					if (not Runner::active) Config::unlock();
+
+					if (Menu::active) Menu::process(Input::get());
+					else Input::process(Input::get());
+				}
+
+				//? Break the loop at 1000ms intervals or if input polling was interrupted
+				else break;
+
+			}
+
+		}
+	}
+	catch (const std::exception& e) {
+		Global::exit_error_msg = "Exception in main loop -> " + string{e.what()};
+		clean_quit(1);
+	}
+	return 0;
+}

+ 4 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop.hpp

@@ -0,0 +1,4 @@
+#include <span>
+#include <string_view>
+
+[[nodiscard]] auto btop_main(std::span<const std::string_view> args) -> int;

+ 216 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_cli.cpp

@@ -0,0 +1,216 @@
+// SPDX-License-Identifier: Apache-2.0
+
+#include "btop_cli.hpp"
+
+#include <algorithm>
+#include <expected>
+#include <filesystem>
+#include <optional>
+#include <span>
+#include <stdexcept>
+#include <string>
+#include <string_view>
+
+#include <fmt/base.h>
+#include <fmt/format.h>
+
+#include "btop_shared.hpp"
+#include "config.h"
+
+using namespace std::string_view_literals;
+
+static constexpr auto BOLD = "\033[1m"sv;
+static constexpr auto BOLD_UNDERLINE = "\033[1;4m"sv;
+static constexpr auto BOLD_RED = "\033[1;31m"sv;
+static constexpr auto YELLOW = "\033[33m"sv;
+static constexpr auto RESET = "\033[0m"sv;
+
+static void version() noexcept {
+	if constexpr (GIT_COMMIT.empty()) {
+		fmt::println("btop version: {}{}{}", BOLD, Global::Version, RESET);
+	} else {
+		fmt::println("btop version: {}{}+{}{}", BOLD, Global::Version, GIT_COMMIT, RESET);
+	}
+}
+
+static void build_info() noexcept {
+	fmt::println("Compiled with: {} ({})", COMPILER, COMPILER_VERSION);
+	fmt::println("Configured with: {}", CONFIGURE_COMMAND);
+}
+
+static void error(std::string_view msg) noexcept {
+	fmt::println("{}error:{} {}\n", BOLD_RED, RESET, msg);
+}
+
+namespace Cli {
+	[[nodiscard]] auto parse(const std::span<const std::string_view> args) noexcept -> Result {
+		Cli cli {};
+
+		for (auto it = args.begin(); it != args.end(); ++it) {
+			auto arg = *it;
+
+			if (arg == "-h" || arg == "--help") {
+				usage();
+				help();
+				return std::unexpected { 0 };
+			}
+			if (arg == "-v" || arg == "-V") {
+				version();
+				return std::unexpected { 0 };
+			}
+			if (arg == "--version") {
+				version();
+				build_info();
+				return std::unexpected { 0 };
+			}
+
+			if (arg == "-d" || arg == "--debug") {
+				cli.debug = true;
+				continue;
+			}
+			if (arg == "--force-utf") {
+				cli.force_utf = true;
+				continue;
+			}
+			if (arg == "-l" || arg == "--low-color") {
+				cli.low_color = true;
+				continue;
+			}
+			if (arg == "-t" || arg == "--tty") {
+				if (cli.force_tty.has_value()) {
+					error("tty mode can't be set twice");
+					return std::unexpected { 1 };
+				}
+				cli.force_tty = std::make_optional(true);
+				continue;
+			}
+			if (arg == "--no-tty") {
+				if (cli.force_tty.has_value()) {
+					error("tty mode can't be set twice");
+					return std::unexpected { 1 };
+				}
+				cli.force_tty = std::make_optional(false);
+				continue;
+			}
+
+			if (arg == "-c" || arg == "--config") {
+				// This flag requires an argument.
+				if (++it == args.end()) {
+					error("Config requires an argument");
+					return std::unexpected { 1 };
+				}
+
+				auto arg = *it;
+				auto config_file = stdfs::path { arg };
+
+				if (stdfs::is_directory(config_file)) {
+					error("Config file can't be a directory");
+					return std::unexpected { 1 };
+				}
+
+				cli.config_file = std::make_optional(config_file);
+				continue;
+			}
+			if (arg == "-f" || arg == "--filter") {
+				// This flag requires an argument.
+				if (++it == args.end()) {
+					error("Filter requires an argument");
+					return std::unexpected { 1 };
+				}
+
+				auto arg = *it;
+				cli.filter = std::make_optional(arg);
+				continue;
+			}
+			if (arg == "-p" || arg == "--preset") {
+				// This flag requires an argument.
+				if (++it == args.end()) {
+					error("Preset requires an argument");
+					return std::unexpected { 1 };
+				}
+
+				auto arg = *it;
+				try {
+					auto preset_id = std::clamp(std::stoi(arg.data()), 0, 9);
+					cli.preset = std::make_optional(preset_id);
+				} catch (std::invalid_argument& e) {
+					error("Preset must be a positive number");
+					return std::unexpected { 1 };
+				} catch (std::out_of_range& e) {
+					error(fmt::format("Preset argument is out of range: {}", arg.data()));
+					return std::unexpected { 1 };
+				}
+				continue;
+			}
+			if (arg == "--themes-dir") {
+				// This flag requires an argument.
+				if (++it == args.end()) {
+					error("Themes directory requires an argument");
+					return std::unexpected { 1 };
+				}
+
+				auto arg = *it;
+				auto themes_dir = stdfs::path { arg };
+
+				if (not stdfs::is_directory(themes_dir)) {
+					error("Themes directory does not exist or is not a directory");
+					return std::unexpected { 1 };
+				}
+
+				cli.themes_dir = std::make_optional(themes_dir);
+				continue;
+			}
+			if (arg == "-u" || arg == "--update") {
+				// This flag requires an argument.
+				if (++it == args.end()) {
+					error("Update requires an argument");
+					return std::unexpected { 1 };
+				}
+
+				auto arg = *it;
+				try {
+					auto refresh_rate = std::max(std::stoi(arg.data()), 100);
+					cli.updates = refresh_rate;
+				} catch (std::invalid_argument& e) {
+					error("Update must be a positive number");
+					return std::unexpected { 1 };
+				} catch (std::out_of_range& e) {
+					error(fmt::format("Update argument is out of range: {}", arg.data()));
+					return std::unexpected { 1 };
+				}
+				continue;
+			}
+
+			error(fmt::format("Unknown argument '{}{}{}'", YELLOW, arg, RESET));
+			return std::unexpected { 1 };
+		}
+		return cli;
+	}
+
+	void usage() noexcept {
+		fmt::println("{0}Usage:{1} {2}btop{1} [OPTIONS]\n", BOLD_UNDERLINE, RESET, BOLD);
+	}
+
+	void help() noexcept {
+		fmt::print(
+			"{0}Options:{1}\n"
+			"  {2}-c, --config{1} <file>     Path to a config file\n"
+			"  {2}-d, --debug{1}             Start in debug mode with additional logs and metrics\n"
+			"  {2}-f, --filter{1} <filter>   Set an initial process filter\n"
+			"  {2}    --force-utf{1}         Override automatic UTF locale detection\n"
+			"  {2}-l, --low-color{1}         Disable true color, 256 colors only\n"
+			"  {2}-p, --preset{1} <id>       Start with a preset (0-9)\n"
+			"  {2}-t, --tty{1}               Force tty mode with ANSI graph symbols and 16 colors only\n"
+			"  {2}    --themes-dir{1} <dir>  Path to a custom themes directory\n"
+			"  {2}    --no-tty{1}            Force disable tty mode\n"
+			"  {2}-u, --update{1} <ms>       Set an initial update rate in milliseconds\n"
+			"  {2}-h, --help{1}              Show this help message and exit\n"
+			"  {2}-V, --version{1}           Show a version message and exit (more with --version)\n",
+			BOLD_UNDERLINE, RESET, BOLD
+		);
+	}
+
+	void help_hint() noexcept {
+		fmt::println("For more information, try '{}--help{}'", BOLD, RESET);
+	}
+} // namespace Cli

+ 50 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_cli.hpp

@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: Apache-2.0
+
+#pragma once
+
+#include <cstdint>
+#include <expected>
+#include <filesystem>
+#include <optional>
+#include <span>
+#include <string_view>
+
+namespace Cli {
+	namespace stdfs = std::filesystem;
+
+	// Configuration options set via the command line.
+	struct Cli {
+		// Alternate path to a configuration file
+		std::optional<stdfs::path> config_file;
+		// Enable debug mode with additional logs and metrics
+		bool debug {};
+		// Set an initial process filter.
+		std::optional<std::string> filter;
+		// Only use ANSI supported graph symbols and colors
+		std::optional<bool> force_tty;
+		// Use UTF-8 locale even if not detected
+		bool force_utf {};
+		// Disable true color and only use 256 color mode
+		bool low_color {};
+		// Start with one of the provided presets
+		std::optional<std::uint32_t> preset;
+		// Path to a custom themes directory
+		std::optional<stdfs::path> themes_dir;
+		// The initial refresh rate
+		std::optional<std::uint32_t> updates;
+	};
+
+	using Result = std::expected<Cli, std::int32_t>;
+
+	// Parse the command line arguments
+	[[nodiscard]] auto parse(std::span<const std::string_view> args) noexcept -> Result;
+
+	// Print a usage header
+	void usage() noexcept;
+
+	// Print a help message
+	void help() noexcept;
+
+	// Print a hint on how to show more help
+	void help_hint() noexcept;
+} // namespace Cli

+ 831 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_config.cpp

@@ -0,0 +1,831 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#include <array>
+#include <atomic>
+#include <filesystem>
+#include <fstream>
+#include <locale>
+#include <optional>
+#include <ranges>
+#include <string_view>
+#include <utility>
+
+#include <fmt/core.h>
+#include <sys/statvfs.h>
+
+#include "btop_config.hpp"
+#include "btop_shared.hpp"
+#include "btop_tools.hpp"
+
+using std::array;
+using std::atomic;
+using std::string_view;
+
+namespace fs = std::filesystem;
+namespace rng = std::ranges;
+
+using namespace std::literals;
+using namespace Tools;
+
+//* Functions and variables for reading and writing the btop config file
+namespace Config {
+
+	atomic<bool> locked (false);
+	atomic<bool> writelock (false);
+	bool write_new;
+
+	const vector<array<string, 2>> descriptions = {
+		{"color_theme", 		"#* 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\""},
+
+		{"theme_background", 	"#* If the theme set background should be shown, set to False if you want terminal background transparency."},
+
+		{"truecolor", 			"#* Sets if 24-bit truecolor should be used, will convert 24-bit colors to 256 color (6x6x6 color cube) if false."},
+
+		{"force_tty", 			"#* 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."},
+
+		{"presets",				"#* 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\""},
+
+		{"vim_keys",			"#* 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."},
+
+		{"rounded_corners",		"#* Rounded corners on boxes, is ignored if TTY mode is ON."},
+
+		{"terminal_sync", 		"#* Use terminal synchronized output sequences to reduce flickering on supported terminals."},
+
+		{"graph_symbol", 		"#* 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."},
+
+		{"graph_symbol_cpu", 	"# Graph symbol to use for graphs in cpu box, \"default\", \"braille\", \"block\" or \"tty\"."},
+#ifdef GPU_SUPPORT
+		{"graph_symbol_gpu", 	"# Graph symbol to use for graphs in gpu box, \"default\", \"braille\", \"block\" or \"tty\"."},
+#endif
+		{"graph_symbol_mem", 	"# Graph symbol to use for graphs in cpu box, \"default\", \"braille\", \"block\" or \"tty\"."},
+
+		{"graph_symbol_net", 	"# Graph symbol to use for graphs in cpu box, \"default\", \"braille\", \"block\" or \"tty\"."},
+
+		{"graph_symbol_proc", 	"# Graph symbol to use for graphs in cpu box, \"default\", \"braille\", \"block\" or \"tty\"."},
+
+		{"shown_boxes", 		"#* Manually set which boxes to show. Available values are \"cpu mem net proc\" and \"gpu0\" through \"gpu5\", separate values with whitespace."},
+
+		{"update_ms", 			"#* Update time in milliseconds, recommended 2000 ms or above for better sample times for graphs."},
+
+		{"proc_sorting",		"#* 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."},
+
+		{"proc_reversed",		"#* Reverse sorting order, True or False."},
+
+		{"proc_tree",			"#* Show processes as a tree."},
+
+		{"proc_colors", 		"#* Use the cpu graph colors in the process list."},
+
+		{"proc_gradient", 		"#* Use a darkening gradient in the process list."},
+
+		{"proc_per_core", 		"#* If process cpu usage should be of the core it's running on or usage of the total available cpu power."},
+
+		{"proc_mem_bytes", 		"#* Show process memory as bytes instead of percent."},
+
+		{"proc_cpu_graphs",     "#* Show cpu graph for each process."},
+
+		{"proc_info_smaps",		"#* Use /proc/[pid]/smaps for memory information in the process info box (very slow but more accurate)"},
+
+		{"proc_left",			"#* Show proc box on left side of screen instead of right."},
+
+		{"proc_filter_kernel",  "#* (Linux) Filter processes tied to the Linux kernel(similar behavior to htop)."},
+
+		{"proc_aggregate",		"#* In tree-view, always accumulate child process resources in the parent process."},
+
+		{"keep_dead_proc_usage", "#* Should cpu and memory usage display be preserved for dead processes when paused."},
+
+		{"cpu_graph_upper", 	"#* 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."},
+
+		{"cpu_graph_lower", 	"#* 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."},
+	#ifdef GPU_SUPPORT
+		{"show_gpu_info",		"#* If gpu info should be shown in the cpu box. Available values = \"Auto\", \"On\" and \"Off\"."},
+	#endif
+		{"cpu_invert_lower", 	"#* Toggles if the lower CPU graph should be inverted."},
+
+		{"cpu_single_graph", 	"#* Set to True to completely disable the lower CPU graph."},
+
+		{"cpu_bottom",			"#* Show cpu box at bottom of screen instead of top."},
+
+		{"show_uptime", 		"#* Shows the system uptime in the CPU box."},
+
+		{"show_cpu_watts",		"#* Shows the CPU package current power consumption in watts. Requires running `make setcap` or `make setuid` or running with sudo."},
+
+		{"check_temp", 			"#* Show cpu temperature."},
+
+		{"cpu_sensor", 			"#* Which sensor to use for cpu temperature, use options menu to select from list of available sensors."},
+
+		{"show_coretemp", 		"#* Show temperatures for cpu cores also if check_temp is True and sensors has been found."},
+
+		{"cpu_core_map",		"#* 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\""},
+
+		{"temp_scale", 			"#* Which temperature scale to use, available values: \"celsius\", \"fahrenheit\", \"kelvin\" and \"rankine\"."},
+
+		{"base_10_sizes",		"#* Use base 10 for bits/bytes sizes, KB = 1000 instead of KiB = 1024."},
+
+		{"show_cpu_freq", 		"#* Show CPU frequency."},
+	#ifdef __linux__
+		{"freq_mode",				"#* How to calculate CPU frequency, available values: \"first\", \"range\", \"lowest\", \"highest\" and \"average\"."},
+	#endif
+		{"clock_format", 		"#* 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"},
+
+		{"background_update", 	"#* Update main ui in background when menus are showing, set this to false if the menus is flickering too much for comfort."},
+
+		{"custom_cpu_name", 	"#* Custom cpu model name, empty string to disable."},
+
+		{"disks_filter", 		"#* 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\""},
+
+		{"mem_graphs", 			"#* Show graphs instead of meters for memory values."},
+
+		{"mem_below_net",		"#* Show mem box below net box instead of above."},
+
+		{"zfs_arc_cached",		"#* Count ZFS ARC in cached and available memory."},
+
+		{"show_swap", 			"#* If swap memory should be shown in memory box."},
+
+		{"swap_disk", 			"#* Show swap as a disk, ignores show_swap value above, inserts itself after first disk."},
+
+		{"show_disks", 			"#* If mem box should be split to also show disks info."},
+
+		{"only_physical", 		"#* Filter out non physical disks. Set this to False to include network disks, RAM disks and similar."},
+
+		{"use_fstab", 			"#* Read disks list from /etc/fstab. This also disables only_physical."},
+
+		{"zfs_hide_datasets",		"#* Setting this to True will hide all datasets, and only show ZFS pools. (IO stats will be calculated per-pool)"},
+
+		{"disk_free_priv",		"#* Set to true to show available disk space for privileged users."},
+
+		{"show_io_stat", 		"#* Toggles if io activity % (disk busy time) should be shown in regular disk usage view."},
+
+		{"io_mode", 			"#* Toggles io mode for disks, showing big graphs for disk read/write speeds."},
+
+		{"io_graph_combined", 	"#* Set to True to show combined read/write io graphs in io mode."},
+
+		{"io_graph_speeds", 	"#* 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\"."},
+
+		{"net_download", 		"#* Set fixed values for network graphs in Mebibits. Is only used if net_auto is also set to False."},
+
+		{"net_upload", ""},
+
+		{"net_auto", 			"#* Use network graphs auto rescaling mode, ignores any values set above and rescales down to 10 Kibibytes at the lowest."},
+
+		{"net_sync", 			"#* Sync the auto scaling for download and upload to whichever currently has the highest scale."},
+
+		{"net_iface", 			"#* Starts with the Network Interface specified here."},
+
+	    {"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."},
+
+		{"show_battery", 		"#* Show battery stats in top right if battery is present."},
+
+		{"selected_battery",	"#* Which battery to use if multiple are present. \"Auto\" for auto detection."},
+
+		{"show_battery_watts",	"#* Show power stats of battery next to charge indicator."},
+
+		{"log_level", 			"#* Set loglevel for \"~/.config/btop/btop.log\" levels are: \"ERROR\" \"WARNING\" \"INFO\" \"DEBUG\".\n"
+								"#* The level set includes all lower levels, i.e. \"DEBUG\" will show all logging info."},
+	#ifdef GPU_SUPPORT
+
+		{"nvml_measure_pcie_speeds",
+								"#* Measure PCIe throughput on NVIDIA cards, may impact performance on certain cards."},
+		{"rsmi_measure_pcie_speeds",
+								"#* Measure PCIe throughput on AMD cards, may impact performance on certain cards."},
+		{"gpu_mirror_graph",	"#* Horizontally mirror the GPU graph."},
+		{"shown_gpus",			"#* Set which GPU vendors to show. Available values are \"nvidia amd intel\""},
+		{"custom_gpu_name0",	"#* Custom gpu0 model name, empty string to disable."},
+		{"custom_gpu_name1",	"#* Custom gpu1 model name, empty string to disable."},
+		{"custom_gpu_name2",	"#* Custom gpu2 model name, empty string to disable."},
+		{"custom_gpu_name3",	"#* Custom gpu3 model name, empty string to disable."},
+		{"custom_gpu_name4",	"#* Custom gpu4 model name, empty string to disable."},
+		{"custom_gpu_name5",	"#* Custom gpu5 model name, empty string to disable."},
+	#endif
+	};
+
+	std::unordered_map<std::string_view, string> strings = {
+		{"color_theme", "Default"},
+		{"shown_boxes", "net proc"},
+		{"graph_symbol", "braille"},
+		{"presets", "net:0:default,proc:0:default"},
+		{"graph_symbol_cpu", "default"},
+		{"graph_symbol_gpu", "default"},
+		{"graph_symbol_mem", "default"},
+		{"graph_symbol_net", "default"},
+		{"graph_symbol_proc", "default"},
+		{"proc_sorting", "cpu lazy"},
+		{"cpu_graph_upper", "Auto"},
+		{"cpu_graph_lower", "Auto"},
+		{"cpu_sensor", "Auto"},
+		{"selected_battery", "Auto"},
+		{"cpu_core_map", ""},
+		{"temp_scale", "celsius"},
+	#ifdef __linux__
+		{"freq_mode", "first"},
+	#endif
+		{"clock_format", "%X"},
+		{"custom_cpu_name", ""},
+		{"disks_filter", ""},
+		{"io_graph_speeds", ""},
+		{"net_iface", ""},
+		{"base_10_bitrate", "Auto"},
+		{"log_level", "WARNING"},
+		{"proc_filter", ""},
+		{"proc_command", ""},
+		{"selected_name", ""},
+	#ifdef GPU_SUPPORT
+		{"custom_gpu_name0", ""},
+		{"custom_gpu_name1", ""},
+		{"custom_gpu_name2", ""},
+		{"custom_gpu_name3", ""},
+		{"custom_gpu_name4", ""},
+		{"custom_gpu_name5", ""},
+		{"show_gpu_info", "Auto"},
+		{"shown_gpus", "nvidia amd intel"}
+	#endif
+	};
+	std::unordered_map<std::string_view, string> stringsTmp;
+
+	std::unordered_map<std::string_view, bool> bools = {
+		{"theme_background", true},
+		{"truecolor", true},
+		{"rounded_corners", true},
+		{"proc_reversed", false},
+		{"proc_tree", false},
+		{"proc_colors", true},
+		{"proc_gradient", true},
+		{"proc_per_core", false},
+		{"proc_mem_bytes", true},
+		{"proc_cpu_graphs", true},
+		{"proc_info_smaps", false},
+		{"proc_left", false},
+		{"proc_filter_kernel", false},
+		{"cpu_invert_lower", true},
+		{"cpu_single_graph", false},
+		{"cpu_bottom", false},
+		{"show_uptime", true},
+		{"show_cpu_watts", true},
+		{"check_temp", true},
+		{"show_coretemp", true},
+		{"show_cpu_freq", true},
+		{"background_update", true},
+		{"mem_graphs", true},
+		{"mem_below_net", false},
+		{"zfs_arc_cached", true},
+		{"show_swap", true},
+		{"swap_disk", true},
+		{"show_disks", true},
+		{"only_physical", true},
+		{"use_fstab", true},
+		{"zfs_hide_datasets", false},
+		{"show_io_stat", true},
+		{"io_mode", false},
+		{"base_10_sizes", false},
+		{"io_graph_combined", false},
+		{"net_auto", true},
+		{"net_sync", true},
+		{"show_battery", true},
+		{"show_battery_watts", true},
+		{"vim_keys", false},
+		{"tty_mode", false},
+		{"disk_free_priv", false},
+		{"force_tty", false},
+		{"lowcolor", false},
+		{"show_detailed", false},
+		{"proc_filtering", false},
+		{"proc_aggregate", false},
+		{"pause_proc_list", false},
+		{"keep_dead_proc_usage", false},
+	#ifdef GPU_SUPPORT
+		{"nvml_measure_pcie_speeds", true},
+		{"rsmi_measure_pcie_speeds", true},
+		{"gpu_mirror_graph", true},
+	#endif
+		{"terminal_sync", true}
+	};
+	std::unordered_map<std::string_view, bool> boolsTmp;
+
+	std::unordered_map<std::string_view, int> ints = {
+		{"update_ms", 2000},
+		{"net_download", 100},
+		{"net_upload", 100},
+		{"detailed_pid", 0},
+		{"selected_pid", 0},
+		{"selected_depth", 0},
+		{"proc_start", 0},
+		{"proc_selected", 0},
+		{"proc_last_selected", 0}
+	};
+	std::unordered_map<std::string_view, int> intsTmp;
+
+	// Returns a valid config dir or an empty optional
+	// The config dir might be read only, a warning is printed, but a path is returned anyway
+	[[nodiscard]] std::optional<fs::path> get_config_dir() noexcept {
+		fs::path config_dir;
+		{
+			std::error_code error;
+			if (const auto xdg_config_home = std::getenv("XDG_CONFIG_HOME"); xdg_config_home != nullptr) {
+				if (fs::exists(xdg_config_home, error)) {
+					config_dir = fs::path(xdg_config_home) / "btop";
+				}
+			} else if (const auto home = std::getenv("HOME"); home != nullptr) {
+				error.clear();
+				if (fs::exists(home, error)) {
+					config_dir = fs::path(home) / ".config" / "btop";
+				}
+				if (error) {
+					fmt::print(stderr, "\033[0;31mWarning: \033[0m{} could not be accessed: {}\n", config_dir.string(), error.message());
+					config_dir = "";
+				}
+			}
+		}
+
+		// FIXME: This warnings can be noisy if the user deliberately has a non-writable config dir
+		//  offer an alternative | disable messages by default | disable messages if config dir is not writable | disable messages with a flag
+		// FIXME: Make happy path not branch
+		if (not config_dir.empty()) {
+			std::error_code error;
+			if (fs::exists(config_dir, error)) {
+				if (fs::is_directory(config_dir, error)) {
+					struct statvfs stats {};
+					if ((fs::status(config_dir, error).permissions() & fs::perms::owner_write) == fs::perms::owner_write and
+						statvfs(config_dir.c_str(), &stats) == 0 and (stats.f_flag & ST_RDONLY) == 0) {
+						return config_dir;
+					} else {
+						fmt::print(stderr, "\033[0;31mWarning: \033[0m`{}` is not writable\n", fs::absolute(config_dir).string());
+						// If the config is readable we can still use the provided config, but changes will not be persistent
+						if ((fs::status(config_dir, error).permissions() & fs::perms::owner_read) == fs::perms::owner_read) {
+							fmt::print(stderr, "\033[0;31mWarning: \033[0mLogging is disabled, config changes are not persistent\n");
+							return config_dir;
+						}
+					}
+				} else {
+					fmt::print(stderr, "\033[0;31mWarning: \033[0m`{}` is not a directory\n", fs::absolute(config_dir).string());
+				}
+			} else {
+				// Doesn't exist
+				if (fs::create_directories(config_dir, error)) {
+					return config_dir;
+				} else {
+					fmt::print(stderr, "\033[0;31mWarning: \033[0m`{}` could not be created: {}\n", fs::absolute(config_dir).string(), error.message());
+				}
+			}
+		} else {
+			fmt::print(stderr, "\033[0;31mWarning: \033[0mCould not determine config path: Make sure `$XDG_CONFIG_HOME` or `$HOME` is set\n");
+		}
+		fmt::print(stderr, "\033[0;31mWarning: \033[0mLogging is disabled, config changes are not persistent\n");
+		return {};
+	}
+
+	bool _locked(const std::string_view name) {
+		atomic_wait(writelock, true);
+		if (not write_new and rng::find_if(descriptions, [&name](const auto& a) { return a.at(0) == name; }) != descriptions.end())
+			write_new = true;
+		return locked.load();
+	}
+
+	fs::path conf_dir;
+	fs::path conf_file;
+
+	vector<string> available_batteries = {"Auto"};
+
+	vector<string> current_boxes;
+	vector<string> preset_list = {"cpu:0:default,mem:0:default,net:0:default,proc:0:default"};
+	int current_preset = -1;
+
+	bool presetsValid(const string& presets) {
+		vector<string> new_presets = {preset_list.at(0)};
+
+		for (int x = 0; const auto& preset : ssplit(presets)) {
+			if (++x > 9) {
+				validError = "Too many presets entered!";
+				return false;
+			}
+			for (int y = 0; const auto& box : ssplit(preset, ',')) {
+				if (++y > 4) {
+					validError = "Too many boxes entered for preset!";
+					return false;
+				}
+				const auto& vals = ssplit(box, ':');
+				if (vals.size() != 3) {
+					validError = "Malformatted preset in config value presets!";
+					return false;
+				}
+				if (not is_in(vals.at(0), "cpu", "mem", "net", "proc", "gpu0", "gpu1", "gpu2", "gpu3", "gpu4", "gpu5")) {
+					validError = "Invalid box name in config value presets!";
+					return false;
+				}
+				if (not is_in(vals.at(1), "0", "1")) {
+					validError = "Invalid position value in config value presets!";
+					return false;
+				}
+				if (not v_contains(valid_graph_symbols_def, vals.at(2))) {
+					validError = "Invalid graph name in config value presets!";
+					return false;
+				}
+			}
+			new_presets.push_back(preset);
+		}
+
+		preset_list = std::move(new_presets);
+		return true;
+	}
+
+	//* Apply selected preset
+	bool apply_preset(const string& preset) {
+		string boxes;
+
+		for (const auto& box : ssplit(preset, ',')) {
+			const auto& vals = ssplit(box, ':');
+			boxes += vals.at(0) + ' ';
+		}
+		if (not boxes.empty()) boxes.pop_back();
+
+		auto min_size = Term::get_min_size(boxes);
+		if (Term::width < min_size.at(0) or Term::height < min_size.at(1)) {
+			return false;
+		}
+
+		for (const auto& box : ssplit(preset, ',')) {
+			const auto& vals = ssplit(box, ':');
+			if (vals.at(0) == "cpu") {
+				set("cpu_bottom", (vals.at(1) != "0"));
+			} else if (vals.at(0) == "mem") {
+				set("mem_below_net", (vals.at(1) != "0"));
+			} else if (vals.at(0) == "proc") {
+				set("proc_left", (vals.at(1) != "0"));
+			}
+			if (vals.at(0).starts_with("gpu")) {
+				set("graph_symbol_gpu", vals.at(2));
+			} else {
+				set(strings.find("graph_symbol_" + vals.at(0))->first, vals.at(2));
+			}
+		}
+
+		if (set_boxes(boxes)) {
+			set("shown_boxes", boxes);
+			return true;
+		}
+		return false;
+	}
+
+	void lock() {
+		atomic_wait(writelock);
+		locked = true;
+	}
+
+	string validError;
+
+	bool intValid(const std::string_view name, const string& value) {
+		int i_value;
+		try {
+			i_value = stoi(value);
+		}
+		catch (const std::invalid_argument&) {
+			validError = "Invalid numerical value!";
+			return false;
+		}
+		catch (const std::out_of_range&) {
+			validError = "Value out of range!";
+			return false;
+		}
+		catch (const std::exception& e) {
+			validError = string{e.what()};
+			return false;
+		}
+
+		if (name == "update_ms" and i_value < 100)
+			validError = "Config value update_ms set too low (<100).";
+
+		else if (name == "update_ms" and i_value > ONE_DAY_MILLIS)
+			validError = fmt::format("Config value update_ms set too high (>{}).", ONE_DAY_MILLIS);
+
+		else
+			return true;
+
+		return false;
+	}
+
+	bool validBoxSizes(const string& boxes) {
+		auto min_size = Term::get_min_size(boxes);
+		return (Term::width >= min_size.at(0) and Term::height >= min_size.at(1));
+	}
+
+	bool stringValid(const std::string_view name, const string& value) {
+		if (name == "log_level" and not v_contains(Logger::log_levels, value))
+			validError = "Invalid log_level: " + value;
+
+		else if (name == "graph_symbol" and not v_contains(valid_graph_symbols, value))
+			validError = "Invalid graph symbol identifier: " + value;
+
+		else if (name.starts_with("graph_symbol_") and (value != "default" and not v_contains(valid_graph_symbols, value)))
+			validError = fmt::format("Invalid graph symbol identifier for {}: {}", name, value);
+
+		else if (name == "shown_boxes" and not Global::init_conf) {
+			if (value.empty())
+				validError = "No boxes selected!";
+			else if (not validBoxSizes(value))
+				validError = "Terminal too small to display entered boxes!";
+			else if (not set_boxes(value))
+				validError = "Invalid box name(s) in shown_boxes!";
+			else
+				return true;
+		}
+
+	#ifdef GPU_SUPPORT
+		else if (name == "show_gpu_info" and not v_contains(show_gpu_values, value))
+			validError = "Invalid value for show_gpu_info: " + value;
+	#endif
+
+		else if (name == "presets" and not presetsValid(value))
+			return false;
+
+		else if (name == "cpu_core_map") {
+			const auto maps = ssplit(value);
+			bool all_good = true;
+			for (const auto& map : maps) {
+				const auto map_split = ssplit(map, ':');
+				if (map_split.size() != 2)
+					all_good = false;
+				else if (not isint(map_split.at(0)) or not isint(map_split.at(1)))
+					all_good = false;
+
+				if (not all_good) {
+					validError = "Invalid formatting of cpu_core_map!";
+					return false;
+				}
+			}
+			return true;
+		}
+		else if (name == "io_graph_speeds") {
+			const auto maps = ssplit(value);
+			bool all_good = true;
+			for (const auto& map : maps) {
+				const auto map_split = ssplit(map, ':');
+				if (map_split.size() != 2)
+					all_good = false;
+				else if (map_split.at(0).empty() or not isint(map_split.at(1)))
+					all_good = false;
+
+				if (not all_good) {
+					validError = "Invalid formatting of io_graph_speeds!";
+					return false;
+				}
+			}
+			return true;
+		}
+
+		else
+			return true;
+
+		return false;
+	}
+
+	string getAsString(const std::string_view name) {
+		if (auto it = bools.find(name); it != bools.end())
+			return it->second ? "True" : "False";
+		if (auto it = ints.find(name); it != ints.end())
+			return to_string(it->second);
+		if (auto it = strings.find(name); it != strings.end())
+			return it->second;
+		return "";
+	}
+
+	void flip(const std::string_view name) {
+		if (_locked(name)) {
+			if (boolsTmp.contains(name)) boolsTmp.at(name) = not boolsTmp.at(name);
+			else boolsTmp.insert_or_assign(name, (not bools.at(name)));
+		}
+		else bools.at(name) = not bools.at(name);
+	}
+
+	void unlock() {
+		if (not locked) return;
+		atomic_wait(Runner::active);
+		atomic_lock lck(writelock, true);
+		try {
+			if (Proc::shown) {
+				ints.at("selected_pid") = Proc::selected_pid;
+				strings.at("selected_name") = Proc::selected_name;
+				ints.at("proc_start") = Proc::start;
+				ints.at("proc_selected") = Proc::selected;
+				ints.at("selected_depth") = Proc::selected_depth;
+			}
+
+			for (auto& item : stringsTmp) {
+				strings.at(item.first) = item.second;
+			}
+			stringsTmp.clear();
+
+			for (auto& item : intsTmp) {
+				ints.at(item.first) = item.second;
+			}
+			intsTmp.clear();
+
+			for (auto& item : boolsTmp) {
+				bools.at(item.first) = item.second;
+			}
+			boolsTmp.clear();
+		}
+		catch (const std::exception& e) {
+			Global::exit_error_msg = "Exception during Config::unlock() : " + string{e.what()};
+			clean_quit(1);
+		}
+
+		locked = false;
+	}
+
+	bool set_boxes(const string& boxes) {
+		auto new_boxes = ssplit(boxes);
+		for (auto& box : new_boxes) {
+			if (not v_contains(valid_boxes, box)) return false;
+		#ifdef GPU_SUPPORT
+			if (box.starts_with("gpu")) {
+				int gpu_num = stoi(box.substr(3)) + 1;
+				if (gpu_num > Gpu::count) return false;
+			}
+		#endif
+		}
+		current_boxes = std::move(new_boxes);
+		return true;
+	}
+
+	bool toggle_box(const string& box) {
+		auto old_boxes = current_boxes;
+		auto box_pos = rng::find(current_boxes, box);
+		if (box_pos == current_boxes.end())
+			current_boxes.push_back(box);
+		else
+			current_boxes.erase(box_pos);
+
+		string new_boxes;
+		if (not current_boxes.empty()) {
+			for (const auto& b : current_boxes) new_boxes += b + ' ';
+			new_boxes.pop_back();
+		}
+
+		auto min_size = Term::get_min_size(new_boxes);
+
+		if (Term::width < min_size.at(0) or Term::height < min_size.at(1)) {
+			current_boxes = old_boxes;
+			return false;
+		}
+
+		Config::set("shown_boxes", new_boxes);
+		return true;
+	}
+
+	void load(const fs::path& conf_file, vector<string>& load_warnings) {
+		std::error_code error;
+		if (conf_file.empty())
+			return;
+		else if (not fs::exists(conf_file, error)) {
+			write_new = true;
+			return;
+		}
+		if (error) {
+			return;
+		}
+
+		std::ifstream cread(conf_file);
+		if (cread.good()) {
+			vector<string> valid_names;
+			valid_names.reserve(descriptions.size());
+			for (const auto &n : descriptions)
+				valid_names.push_back(n[0]);
+			if (string v_string; cread.peek() != '#' or (getline(cread, v_string, '\n') and not v_string.contains(Global::Version)))
+				write_new = true;
+			while (not cread.eof()) {
+				cread >> std::ws;
+				if (cread.peek() == '#') {
+					cread.ignore(SSmax, '\n');
+					continue;
+				}
+				string name, value;
+				getline(cread, name, '=');
+				if (name.ends_with(' ')) name = trim(name);
+				if (not v_contains(valid_names, name)) {
+					cread.ignore(SSmax, '\n');
+					continue;
+				}
+				cread >> std::ws;
+
+				if (bools.contains(name)) {
+					cread >> value;
+					if (not isbool(value))
+						load_warnings.push_back("Got an invalid bool value for config name: " + name);
+					else
+						bools.at(name) = stobool(value);
+				}
+				else if (ints.contains(name)) {
+					cread >> value;
+					if (not isint(value))
+						load_warnings.push_back("Got an invalid integer value for config name: " + name);
+					else if (not intValid(name, value)) {
+						load_warnings.push_back(validError);
+					}
+					else
+						ints.at(name) = stoi(value);
+				}
+				else if (strings.contains(name)) {
+					if (cread.peek() == '"') {
+						cread.ignore(1);
+						getline(cread, value, '"');
+					}
+					else cread >> value;
+
+					if (not stringValid(name, value))
+						load_warnings.push_back(validError);
+					else
+						strings.at(name) = value;
+				}
+
+				cread.ignore(SSmax, '\n');
+			}
+
+			if (not load_warnings.empty()) write_new = true;
+		}
+	}
+
+	void write() {
+		if (conf_file.empty() or not write_new) return;
+		Logger::debug("Writing new config file");
+		if (geteuid() != Global::real_uid and seteuid(Global::real_uid) != 0) return;
+		std::ofstream cwrite(conf_file, std::ios::trunc);
+		cwrite.imbue(std::locale::classic());
+		if (cwrite.good()) {
+			cwrite << "#? Config file for btop v. " << Global::Version << "\n";
+			for (const auto& [name, description] : descriptions) {
+				cwrite << "\n" << (description.empty() ? "" : description + "\n")
+						<< name << " = ";
+				if (strings.contains(name))
+					cwrite << "\"" << strings.at(name) << "\"";
+				else if (ints.contains(name))
+					cwrite << ints.at(name);
+				else if (bools.contains(name))
+					cwrite << (bools.at(name) ? "True" : "False");
+				cwrite << "\n";
+			}
+		}
+	}
+
+	static constexpr auto get_xdg_state_dir() -> std::optional<fs::path> {
+		std::optional<fs::path> xdg_state_home;
+
+		{
+			const auto* xdg_state_home_ptr = std::getenv("XDG_STATE_HOME");
+			if (xdg_state_home_ptr != nullptr) {
+				xdg_state_home = std::make_optional(fs::path(xdg_state_home_ptr));
+			} else {
+				const auto* home_ptr = std::getenv("HOME");
+				if (home_ptr != nullptr) {
+					xdg_state_home = std::make_optional(fs::path(home_ptr) / ".local" / "state");
+				}
+			}
+		}
+
+		if (xdg_state_home.has_value()) {
+			std::error_code err;
+			fs::create_directories(xdg_state_home.value(), err);
+			if (err) {
+				return std::nullopt;
+			}
+			return xdg_state_home;
+		}
+		return std::nullopt;
+	}
+
+	auto get_log_file() -> std::optional<fs::path> {
+		return get_xdg_state_dir().transform([](auto&& state_home) -> auto { return state_home / "btop.log"; });
+	}
+}

+ 135 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_config.hpp

@@ -0,0 +1,135 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#pragma once
+
+#include <filesystem>
+#include <optional>
+#include <string>
+#include <vector>
+
+#include <unordered_map>
+
+using std::string;
+using std::vector;
+
+//* Functions and variables for reading and writing the btop config file
+namespace Config {
+
+	extern std::filesystem::path conf_dir;
+	extern std::filesystem::path conf_file;
+
+	extern std::unordered_map<std::string_view, string> strings;
+	extern std::unordered_map<std::string_view, string> stringsTmp;
+	extern std::unordered_map<std::string_view, bool> bools;
+	extern std::unordered_map<std::string_view, bool> boolsTmp;
+	extern std::unordered_map<std::string_view, int> ints;
+	extern std::unordered_map<std::string_view, int> intsTmp;
+
+	const vector<string> valid_graph_symbols = { "braille", "block", "tty" };
+	const vector<string> valid_graph_symbols_def = { "default", "braille", "block", "tty" };
+	const vector<string> valid_boxes = {
+		"cpu", "mem", "net", "proc"
+#ifdef GPU_SUPPORT
+		,"gpu0", "gpu1", "gpu2", "gpu3", "gpu4", "gpu5"
+#endif
+		};
+	const vector<string> temp_scales = { "celsius", "fahrenheit", "kelvin", "rankine" };
+#ifdef __linux__
+	const vector<string> freq_modes = { "first", "range", "lowest", "highest", "average" };
+#endif
+#ifdef GPU_SUPPORT
+	const vector<string> show_gpu_values = { "Auto", "On", "Off" };
+#endif
+    const vector<string> base_10_bitrate_values = { "Auto", "True", "False" };
+	extern vector<string> current_boxes;
+	extern vector<string> preset_list;
+	extern vector<string> available_batteries;
+	extern int current_preset;
+
+	constexpr int ONE_DAY_MILLIS = 1000 * 60 * 60 * 24;
+
+	[[nodiscard]] std::optional<std::filesystem::path> get_config_dir() noexcept;
+
+	//* Check if string only contains space separated valid names for boxes and set current_boxes
+	bool set_boxes(const string& boxes);
+
+	bool validBoxSizes(const string& boxes);
+
+	//* Toggle box and update config string shown_boxes
+	bool toggle_box(const string& box);
+
+	//* Parse and setup config value presets
+	bool presetsValid(const string& presets);
+
+	//* Apply selected preset
+	bool apply_preset(const string& preset);
+
+	bool _locked(const std::string_view name);
+
+	//* Return bool for config key <name>
+	inline bool getB(const std::string_view name) { return bools.at(name); }
+
+	//* Return integer for config key <name>
+	inline const int& getI(const std::string_view name) { return ints.at(name); }
+
+	//* Return string for config key <name>
+	inline const string& getS(const std::string_view name) { return strings.at(name); }
+
+	string getAsString(const std::string_view name);
+
+	extern string validError;
+
+	bool intValid(const std::string_view name, const string& value);
+	bool stringValid(const std::string_view name, const string& value);
+
+	//* Set config key <name> to bool <value>
+	inline void set(const std::string_view name, bool value) {
+		if (_locked(name)) boolsTmp.insert_or_assign(name, value);
+		else bools.at(name) = value;
+	}
+
+	//* Set config key <name> to int <value>
+	inline void set(const std::string_view name, const int value) {
+		if (_locked(name)) intsTmp.insert_or_assign(name, value);
+		else ints.at(name) = value;
+	}
+
+	//* Set config key <name> to string <value>
+	inline void set(const std::string_view name, const string& value) {
+		if (_locked(name)) stringsTmp.insert_or_assign(name, value);
+		else strings.at(name) = value;
+	}
+
+	//* Flip config key bool <name>
+	void flip(const std::string_view name);
+
+	//* Lock config and cache changes until unlocked
+	void lock();
+
+	//* Unlock config and write any cached values to config
+	void unlock();
+
+	//* Load the config file from disk
+	void load(const std::filesystem::path& conf_file, vector<string>& load_warnings);
+
+	//* Write the config file to disk
+	void write();
+
+	auto get_log_file() -> std::optional<std::filesystem::path>;
+}

+ 2299 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_draw.cpp

@@ -0,0 +1,2299 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <iterator>
+#include <ranges>
+#include <stdexcept>
+#include <string>
+#include <string_view>
+#include <utility>
+
+#include "btop_draw.hpp"
+#include "btop_config.hpp"
+#include "btop_theme.hpp"
+#include "btop_shared.hpp"
+#include "btop_tools.hpp"
+#include "btop_input.hpp"
+#include "btop_menu.hpp"
+#include <fmt/format.h>
+
+
+using std::array;
+using std::clamp;
+using std::cmp_equal;
+using std::cmp_greater;
+using std::cmp_less;
+using std::cmp_less_equal;
+using std::floor;
+using std::max;
+using std::min;
+using std::round;
+using std::to_string;
+using std::views::iota;
+
+using namespace Tools;
+using namespace std::literals; // for operator""s
+namespace rng = std::ranges;
+
+namespace Symbols {
+	const string meter = "■";
+
+	const array<string, 10> superscript = { "⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹" };
+
+	const std::unordered_map<string, vector<string>> graph_symbols = {
+		{ "braille_up", {
+			" ", "⢀", "⢠", "⢰", "⢸",
+			"⡀", "⣀", "⣠", "⣰", "⣸",
+			"⡄", "⣄", "⣤", "⣴", "⣼",
+			"⡆", "⣆", "⣦", "⣶", "⣾",
+			"⡇", "⣇", "⣧", "⣷", "⣿"
+		}},
+		{"braille_down", {
+			" ", "⠈", "⠘", "⠸", "⢸",
+			"⠁", "⠉", "⠙", "⠹", "⢹",
+			"⠃", "⠋", "⠛", "⠻", "⢻",
+			"⠇", "⠏", "⠟", "⠿", "⢿",
+			"⡇", "⡏", "⡟", "⡿", "⣿"
+		}},
+		{"block_up", {
+			" ", "▗", "▗", "▐", "▐",
+			"▖", "▄", "▄", "▟", "▟",
+			"▖", "▄", "▄", "▟", "▟",
+			"▌", "▙", "▙", "█", "█",
+			"▌", "▙", "▙", "█", "█"
+		}},
+		{"block_down", {
+			" ", "▝", "▝", "▐", "▐",
+			"▘", "▀", "▀", "▜", "▜",
+			"▘", "▀", "▀", "▜", "▜",
+			"▌", "▛", "▛", "█", "█",
+			"▌", "▛", "▛", "█", "█"
+		}},
+		{"tty_up", {
+			" ", "░", "░", "▒", "▒",
+			"░", "░", "▒", "▒", "█",
+			"░", "▒", "▒", "▒", "█",
+			"▒", "▒", "▒", "█", "█",
+			"▒", "█", "█", "█", "█"
+		}},
+		{"tty_down", {
+			" ", "░", "░", "▒", "▒",
+			"░", "░", "▒", "▒", "█",
+			"░", "▒", "▒", "▒", "█",
+			"▒", "▒", "▒", "█", "█",
+			"▒", "█", "█", "█", "█"
+		}}
+	};
+
+}
+
+namespace Draw {
+
+	string banner_gen(int y, int x, bool centered, bool redraw) {
+		static string banner;
+		static size_t width = 0;
+		if (redraw) banner.clear();
+		if (banner.empty()) {
+			string b_color, bg, fg, oc, letter;
+			auto lowcolor = Config::getB("lowcolor");
+			auto tty_mode = Config::getB("tty_mode");
+			for (size_t z = 0; const auto& line : Global::Banner_src) {
+				if (const auto w = ulen(line[1]); w > width) width = w;
+				if (tty_mode) {
+					fg = (z > 2) ? "\x1b[31m" : "\x1b[91m";
+					bg = (z > 2) ? "\x1b[90m" : "\x1b[37m";
+				}
+				else {
+					fg = Theme::hex_to_color(line[0], lowcolor);
+					int bg_i = 120 - z * 12;
+					bg = Theme::dec_to_color(bg_i, bg_i, bg_i, lowcolor);
+				}
+				for (size_t i = 0; i < line[1].size(); i += 3) {
+					if (line[1][i] == ' ') {
+						letter = Mv::r(1);
+						i -= 2;
+					}
+					else
+						letter = line[1].substr(i, 3);
+
+					b_color = (letter == "█") ? fg : bg;
+					if (b_color != oc) banner += b_color;
+					banner += letter;
+					oc = b_color;
+				}
+				if (++z < Global::Banner_src.size()) banner += Mv::l(ulen(line[1])) + Mv::d(1);
+			}
+			banner += Mv::r(18 - Global::Version.size())
+					+ Theme::c("main_fg") + Fx::b + Fx::i + "v" + Global::Version + Fx::reset;
+		}
+		if (redraw) return "";
+		return (centered ? Mv::to(y, Term::width / 2 - width / 2) : Mv::to(y, x)) + banner;
+	}
+
+	TextEdit::TextEdit() {}
+	TextEdit::TextEdit(string text, bool numeric) : numeric(numeric), text(std::move(text)) {
+		pos = this->text.size();
+		upos = ulen(this->text);
+	}
+
+	bool TextEdit::command(const std::string_view key) {
+		if (key == "left" and upos > 0) {
+			upos--;
+			pos = uresize(text, upos).size();
+		}
+		else if (key == "right" and pos < text.size()) {
+			upos++;
+			pos = uresize(text, upos).size();
+		}
+		else if (key == "home" and not text.empty() and pos > 0) {
+			pos = upos = 0;
+		}
+		else if (key == "end" and not text.empty() and pos < text.size()) {
+			pos = text.size();
+			upos = ulen(text);
+		}
+		else if (key == "backspace" and pos > 0) {
+			if (pos == text.size()) {
+				text = uresize(text, --upos);
+				pos = text.size();
+			}
+			else {
+				const string first = uresize(text, --upos);
+				pos = first.size();
+				text = first + luresize(text.substr(pos), ulen(text) - upos - 1);
+			}
+		}
+		else if (key == "delete" and pos < text.size()) {
+			const string first = uresize(text, upos + 1);
+			text = uresize(first, ulen(first) - 1) + text.substr(first.size());
+		}
+		else if (key == "space" and not numeric) {
+			text.insert(pos++, 1, ' ');
+			upos++;
+		}
+		else if (ulen(key) == 1 and text.size() < text.max_size() - 20) {
+			if (numeric and not isint(key)) return false;
+			if (key.size() == 1) {
+				text.insert(pos++, 1, key.at(0));
+				upos++;
+			}
+			else {
+				const auto first = fmt::format("{}{}", uresize(text, upos), key);
+				text = first + text.substr(pos);
+				upos++;
+				pos = first.size();
+			}
+		}
+		else
+			return false;
+
+		return true;
+	}
+
+	string TextEdit::operator()(const size_t limit) {
+		string out;
+		size_t c_upos = upos;
+		if (text.empty())
+			return Fx::ul + " " + Fx::uul;
+		if (limit > 0 and ulen(text) + 1 > limit) {
+			try {
+				const size_t half = (size_t)round((double)limit / 2);
+				string first;
+
+				if (upos + half > ulen(text))
+					first = luresize(text.substr(0, pos), limit - (ulen(text) - upos));
+				else if (upos - half < 1)
+					first = text.substr(0, pos);
+				else
+					first = luresize(text.substr(0, pos), half);
+
+				out = first + uresize(text.substr(pos), limit - ulen(first));
+				c_upos = ulen(first);
+			}
+			catch (const std::exception& e) {
+				Logger::error("In TextEdit::operator() : " + string{e.what()});
+				return "";
+			}
+		}
+		else
+			out = text;
+
+		if (c_upos == 0)
+			return Fx::ul + uresize(out, 1) + Fx::uul + luresize(out, ulen(out) - 1);
+		else if (c_upos == ulen(out))
+			return out + Fx::ul + " " + Fx::uul;
+		else
+			return uresize(out, c_upos) + Fx::ul + luresize(uresize(out, c_upos + 1), 1) + Fx::uul + luresize(out, ulen(out) - c_upos - 1);
+	}
+
+	void TextEdit::clear() {
+		this->text.clear();
+	}
+
+	string createBox(
+			const int x, const int y, const int width, const int height, string line_color, bool fill, const std::string_view title,
+			const std::string_view title2, const int num
+	) {
+		string out;
+
+		if (line_color.empty())
+			line_color = Theme::c("div_line");
+
+		auto tty_mode = Config::getB("tty_mode");
+		auto rounded = Config::getB("rounded_corners");
+		const string numbering = (num == 0) ? "" : Theme::c("hi_fg") + (tty_mode ? std::to_string(num) : Symbols::superscript.at(clamp(num, 0, 9)));
+		const auto& right_up = (tty_mode or not rounded ? Symbols::right_up : Symbols::round_right_up);
+		const auto& left_up = (tty_mode or not rounded ? Symbols::left_up : Symbols::round_left_up);
+		const auto& right_down = (tty_mode or not rounded ? Symbols::right_down : Symbols::round_right_down);
+		const auto& left_down = (tty_mode or not rounded ? Symbols::left_down : Symbols::round_left_down);
+
+		out = Fx::reset + line_color;
+
+		//? Draw horizontal lines
+		for (const int& hpos : {y, y + height - 1}) {
+			out += Mv::to(hpos, x) + Symbols::h_line * (width - 1);
+		}
+
+		//? Draw vertical lines and fill if enabled
+		for (const int& hpos : iota(y + 1, y + height - 1)) {
+			out += Mv::to(hpos, x) + Symbols::v_line
+				+  ((fill) ? string(width - 2, ' ') : Mv::r(width - 2))
+				+  Symbols::v_line;
+		}
+
+		//? Draw corners
+		out += 	Mv::to(y, x) + left_up
+			+	Mv::to(y, x + width - 1) + right_up
+			+	Mv::to(y + height - 1, x) +left_down
+			+	Mv::to(y + height - 1, x + width - 1) + right_down;
+
+		//? Draw titles if defined
+		if (not title.empty()) {
+			out += fmt::format(
+				"{}{}{}{}{}{}{}{}{}", Mv::to(y, x + 2), Symbols::title_left, Fx::b, numbering, Theme::c("title"), title, Fx::ub,
+				line_color, Symbols::title_right
+			);
+		}
+		if (not title2.empty()) {
+			out += fmt::format(
+				"{}{}{}{}{}{}{}{}{}", Mv::to(y + height - 1, x + 2), Symbols::title_left_down, Fx::b, numbering, Theme::c("title"), title2, Fx::ub,
+				line_color, Symbols::title_right_down
+			);
+		}
+
+		return out + Fx::reset + Mv::to(y + 1, x + 1);
+	}
+
+	bool update_clock(bool force) {
+		const auto& clock_format = Config::getS("clock_format");
+		if (not Cpu::shown or clock_format.empty()) {
+			if (clock_format.empty() and not Global::clock.empty()) Global::clock.clear();
+			return false;
+		}
+
+		static const std::unordered_map<string, string> clock_custom_format = {
+			{"/user", Tools::username()},
+			{"/host", Tools::hostname()},
+			{"/uptime", ""}
+		};
+
+		static time_t c_time{};
+		static size_t clock_len{};
+		static string clock_str;
+
+		if (auto n_time = time(nullptr); not force and n_time == c_time)
+			return false;
+		else {
+			c_time = n_time;
+			const auto new_clock = Tools::strf_time(clock_format);
+			if (not force and new_clock == clock_str) return false;
+			clock_str = new_clock;
+		}
+
+		auto& out = Global::clock;
+		auto cpu_bottom = Config::getB("cpu_bottom");
+		const auto& x = Cpu::x;
+		const auto y = (cpu_bottom ? Cpu::y + Cpu::height - 1 : Cpu::y);
+		const auto& width = Cpu::width;
+		const auto& title_left = (cpu_bottom ? Symbols::title_left_down : Symbols::title_left);
+		const auto& title_right = (cpu_bottom ? Symbols::title_right_down : Symbols::title_right);
+
+
+		for (const auto& [c_format, replacement] : clock_custom_format) {
+			if (clock_str.contains(c_format)) {
+				if (c_format == "/uptime") {
+					string upstr = sec_to_dhms(system_uptime());
+					if (upstr.size() > 8) upstr.resize(upstr.size() - 3);
+					clock_str = s_replace(clock_str, c_format, upstr);
+				}
+				else {
+					clock_str = s_replace(clock_str, c_format, replacement);
+				}
+			}
+
+		}
+
+		clock_str = uresize(clock_str, std::max(10, width - 66 - (Term::width >= 100 and Config::getB("show_battery") and Cpu::has_battery ? 22 : 0)));
+		out.clear();
+
+		if (clock_str.size() != clock_len) {
+			if (not Global::resized and clock_len > 0)
+				out = Mv::to(y, x+(width / 2)-(clock_len / 2)) + Fx::ub + Theme::c("cpu_box") + Symbols::h_line * clock_len;
+			clock_len = clock_str.size();
+		}
+
+		out += Mv::to(y, x+(width / 2)-(clock_len / 2)) + Fx::ub + Theme::c("cpu_box") + title_left
+			+ Theme::c("title") + Fx::b + clock_str + Theme::c("cpu_box") + Fx::ub + title_right;
+
+		return true;
+	}
+
+	//* Meter class ------------------------------------------------------------------------------------------------------------>
+	Meter::Meter() {}
+
+	Meter::Meter(const int width, string color_gradient, bool invert)
+		: width(width), color_gradient(std::move(color_gradient)), invert(invert) {}
+
+	string Meter::operator()(int value) {
+		if (width < 1) return "";
+		value = clamp(value, 0, 100);
+		if (not cache.at(value).empty()) return cache.at(value);
+		auto& out = cache.at(value);
+		for (const int& i : iota(1, width + 1)) {
+			int y = round((double)i * 100.0 / width);
+			if (value >= y)
+				out += Theme::g(color_gradient).at(invert ? 100 - y : y) + Symbols::meter;
+			else {
+				out += Theme::c("meter_bg") + Symbols::meter * (width + 1 - i);
+				break;
+			}
+		}
+		out += Fx::reset;
+		return out;
+	}
+
+	//* Graph class ------------------------------------------------------------------------------------------------------------>
+	void Graph::_create(const deque<long long>& data, int data_offset) {
+		bool mult = (data.size() - data_offset > 1);
+		const auto& graph_symbol = Symbols::graph_symbols.at(symbol + '_' + (invert ? "down" : "up"));
+		array<int, 2> result;
+		const float mod = (height == 1) ? 0.3 : 0.1;
+		long long data_value = 0;
+		if (mult and data_offset > 0) {
+			last = data.at(data_offset - 1);
+			if (max_value > 0) last = clamp((last + offset) * 100 / max_value, 0ll, 100ll);
+		}
+
+		//? Horizontal iteration over values in <data>
+		for (const int& i : iota(data_offset, (int)data.size())) {
+			// if (tty_mode and mult and i % 2 != 0) continue;
+			if (not tty_mode and mult) current = not current;
+			if (i < 0) {
+				data_value = 0;
+				last = 0;
+			}
+			else {
+				data_value = data.at(i);
+				if (max_value > 0) data_value = clamp((data_value + offset) * 100 / max_value, 0ll, 100ll);
+			}
+
+			//? Vertical iteration over height of graph
+			for (const int& horizon : iota(0, height)) {
+				const int cur_high = (height > 1) ? round(100.0 * (height - horizon) / height) : 100;
+				const int cur_low = (height > 1) ? round(100.0 * (height - (horizon + 1)) / height) : 0;
+				//? Calculate previous + current value to fit two values in 1 braille character
+				for (int ai = 0; const auto& value : {last, data_value}) {
+					const int clamp_min = (no_zero and horizon == height - 1 and not (mult and i == data_offset and ai == 0)) ? 1 : 0;
+					if (value >= cur_high)
+						result[ai++] = 4;
+					else if (value <= cur_low)
+						result[ai++] = clamp_min;
+					else {
+						result[ai++] = clamp((int)round((float)(value - cur_low) * 4 / (cur_high - cur_low) + mod), clamp_min, 4);
+					}
+				}
+				//? Generate graph symbol from 5x5 2D vector
+				if (height == 1) {
+					if (result.at(0) + result.at(1) == 0) graphs.at(current).at(horizon) += Mv::r(1);
+					else {
+						if (not color_gradient.empty()) graphs.at(current).at(horizon) += Theme::g(color_gradient).at(clamp(max(last, data_value), 0ll, 100ll));
+						graphs.at(current).at(horizon) += graph_symbol.at((result.at(0) * 5 + result.at(1)));
+					}
+				}
+				else graphs.at(current).at(horizon) += graph_symbol.at((result.at(0) * 5 + result.at(1)));
+			}
+			if (mult and i >= 0) last = data_value;
+		}
+		last = data_value;
+		out.clear();
+		if (height == 1) {
+			//if (not color_gradient.empty())
+			//	out += (last < 1 ? Theme::c("inactive_fg") : Theme::g(color_gradient).at(clamp(last, 0ll, 100ll)));
+			out += graphs.at(current).at(0);
+		}
+		else {
+			for (const int& i : iota(1, height + 1)) {
+				if (i > 1) out += Mv::d(1) + Mv::l(width);
+				if (not color_gradient.empty())
+					out += (invert) ? Theme::g(color_gradient).at(i * 100 / height) : Theme::g(color_gradient).at(100 - ((i - 1) * 100 / height));
+				out += (invert) ? graphs.at(current).at(height - i) : graphs.at(current).at(i-1);
+			}
+		}
+		if (not color_gradient.empty()) out += Fx::reset;
+	}
+
+	Graph::Graph() {}
+
+	Graph::Graph(int width, int height, const string& color_gradient,
+				 const deque<long long>& data, const string& symbol,
+				 bool invert, bool no_zero, long long max_value, long long offset)
+	: width(width), height(height), color_gradient(color_gradient),
+	  invert(invert), no_zero(no_zero), offset(offset) {
+		if (Config::getB("tty_mode") or symbol == "tty") this->symbol = "tty";
+		else if (symbol != "default") this->symbol = symbol;
+		else this->symbol = Config::getS("graph_symbol");
+		if (this->symbol == "tty") tty_mode = true;
+
+		if (max_value == 0 and offset > 0) max_value = 100;
+		this->max_value = max_value;
+		const int value_width = (tty_mode ? data.size() : ceil((double)data.size() / 2));
+		int data_offset = (value_width > width) ? data.size() - width * (tty_mode ? 1 : 2) : 0;
+
+		if (not tty_mode and (data.size() - data_offset) % 2 != 0) {
+			data_offset--;
+		}
+
+		//? Populate the two switching graph vectors and fill empty space if data size < width
+		for (const int& i : iota(0, height * 2)) {
+			if (tty_mode and i % 2 != current) continue;
+			graphs[(i % 2 != 0)].push_back((value_width < width) ? ((height == 1) ? Mv::r(1) : " "s) * (width - value_width) : "");
+		}
+		if (data.size() == 0) return;
+		this->_create(data, data_offset);
+	}
+
+	string& Graph::operator()(const deque<long long>& data, bool data_same) {
+		if (data_same) return out;
+
+		//? Make room for new characters on graph
+		if (not tty_mode) current = not current;
+		for (const int& i : iota(0, height)) {
+			if (height == 1 and graphs.at(current).at(i).at(1) == '[') {
+				if (graphs.at(current).at(i).at(3) == 'C') graphs.at(current).at(i).erase(0, 4);
+				else graphs.at(current).at(i).erase(0, graphs.at(current).at(i).find_first_of('m') + 4);
+			}
+			else if (graphs.at(current).at(i).at(0) == ' ') graphs.at(current).at(i).erase(0, 1);
+			else graphs.at(current).at(i).erase(0, 3);
+		}
+		this->_create(data, (int)data.size() - 1);
+		return out;
+	}
+
+	string& Graph::operator()() {
+		return out;
+	}
+	//*------------------------------------------------------------------------------------------------------------------------->
+
+}
+
+namespace Cpu {
+	int width_p = 100, height_p = 32;
+	int min_width = 60, min_height = 8;
+	int x = 1, y = 1, width = 20, height;
+	int b_columns, b_column_size;
+	int b_x, b_y, b_width, b_height;
+	float max_observed_pwr = 1.0f;
+
+	int graph_up_height, graph_low_height;
+	int graph_up_width, graph_low_width;
+	int gpu_meter_width;
+	bool shown = true, redraw = true, mid_line = false;
+	string box;
+	vector<Draw::Graph> graphs_upper;
+	vector<Draw::Graph> graphs_lower;
+	Draw::Meter cpu_meter;
+	vector<Draw::Meter> gpu_meters;
+	vector<Draw::Graph> core_graphs;
+	vector<Draw::Graph> temp_graphs;
+	vector<Draw::Graph> gpu_temp_graphs;
+	vector<Draw::Graph> gpu_mem_graphs;
+
+    string draw(const cpu_info& cpu, const vector<Gpu::gpu_info>& gpus, bool force_redraw, bool data_same) {
+		if (Runner::stopping) return "";
+		if (force_redraw) redraw = true;
+		bool show_temps = (Config::getB("check_temp") and got_sensors);
+		bool show_watts = (Config::getB("show_cpu_watts") and supports_watts);
+		auto single_graph = Config::getB("cpu_single_graph");
+		bool hide_cores = show_temps and (cpu_temp_only or not Config::getB("show_coretemp"));
+		const int extra_width = (hide_cores ? max(6, 6 * b_column_size) : (b_columns == 1 && !show_temps) ? 8 : 0);
+	#ifdef GPU_SUPPORT
+		const auto& show_gpu_info = Config::getS("show_gpu_info");
+		const bool gpu_always = show_gpu_info == "On";
+		const bool gpu_auto = show_gpu_info == "Auto";
+		const bool show_gpu = (gpus.size() > 0 and (gpu_always or (gpu_auto and Gpu::shown < Gpu::count)));
+	#else
+		(void)gpus;
+	#endif
+		auto graph_up_field = Config::getS("cpu_graph_upper");
+		if (graph_up_field == "Auto" or not v_contains(Cpu::available_fields, graph_up_field))
+			graph_up_field = "total";
+		auto graph_lo_field = Config::getS("cpu_graph_lower");
+		if (graph_lo_field == "Auto" or not v_contains(Cpu::available_fields, graph_lo_field)) {
+		#ifdef GPU_SUPPORT
+			graph_lo_field = show_gpu ? "gpu-totals" : graph_up_field;
+		#else
+			graph_lo_field = graph_up_field;
+		#endif
+		}
+		auto tty_mode = Config::getB("tty_mode");
+		auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_cpu"));
+		auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6);
+		auto& temp_scale = Config::getS("temp_scale");
+		auto cpu_bottom = Config::getB("cpu_bottom");
+
+		const string& title_left = Theme::c("cpu_box") + (cpu_bottom ? Symbols::title_left_down : Symbols::title_left);
+		const string& title_right = Theme::c("cpu_box") + (cpu_bottom ? Symbols::title_right_down : Symbols::title_right);
+		static int bat_pos = 0, bat_len = 0;
+		if (safeVal(cpu.cpu_percent, "total"s).empty()
+			or safeVal(cpu.core_percent, 0).empty()
+			or (show_temps and safeVal(cpu.temp, 0).empty())) return "";
+		if (safeVal(cpu.cpu_percent, "total"s).empty()
+			or safeVal(cpu.core_percent, 0).empty()
+			or (show_temps and safeVal(cpu.temp, 0).empty())) return "";
+		string out;
+		out.reserve(width * height);
+
+		//* Redraw elements not needed to be updated every cycle
+		if (redraw) {
+			mid_line = (not single_graph and graph_up_field != graph_lo_field);
+			graph_up_height = (single_graph ? height - 2 : ceil((double)(height - 2) / 2) - (mid_line and height % 2 != 0));
+			graph_low_height = height - 2 - graph_up_height - mid_line;
+			const int button_y = cpu_bottom ? y + height - 1 : y;
+			out += box;
+
+			//? Buttons on title
+			out += Mv::to(button_y, x + 10) + title_left + Theme::c("hi_fg") + Fx::b + 'm' + Theme::c("title") + "enu" + Fx::ub + title_right;
+			Input::mouse_mappings["m"] = {button_y, x + 11, 1, 4};
+			out += Mv::to(button_y, x + 16) + title_left + Theme::c("hi_fg") + Fx::b + 'p' + Theme::c("title") + "reset "
+				+ (Config::current_preset < 0 ? "*" : to_string(Config::current_preset)) + Fx::ub + title_right;
+			Input::mouse_mappings["p"] = {button_y, x + 17, 1, 8};
+			const string update = to_string(Config::getI("update_ms")) + "ms";
+			out += Mv::to(button_y, x + width - update.size() - 8) + title_left + Fx::b + Theme::c("hi_fg") + "- " + Theme::c("title") + update
+				+ Theme::c("hi_fg") + " +" + Fx::ub + title_right;
+			Input::mouse_mappings["-"] = {button_y, x + width - (int)update.size() - 7, 1, 2};
+			Input::mouse_mappings["+"] = {button_y, x + width - 5, 1, 2};
+
+			// Draw container engine name
+			if (Cpu::container_engine.has_value()) {
+				fmt::format_to(std::back_inserter(out), "{}{}{}{}{}", Mv::to(button_y, x + 28), title_left, Theme::c("title"), Cpu::container_engine.value(), title_right);
+			}
+
+			//? Graphs & meters
+			const int graph_default_width = x + width - b_width - 3;
+
+			auto init_graphs = [&](vector<Draw::Graph>& graphs, const int graph_height, int& graph_width, const string& graph_field, bool invert) {
+			#ifdef GPU_SUPPORT
+				if (graph_field.starts_with("gpu")) {
+					if (graph_field.find("totals") != string::npos) {
+						graphs.resize(gpus.size());
+						gpu_temp_graphs.resize(gpus.size());
+						gpu_mem_graphs.resize(gpus.size());
+						gpu_meters.resize(gpus.size());
+						const int gpu_draw_count = gpu_always ? Gpu::count : Gpu::count - Gpu::shown;
+						graph_width = gpu_draw_count <= 0 ? graph_default_width : graph_default_width/gpu_draw_count - gpu_draw_count + 1 + graph_default_width%gpu_draw_count;
+						for (size_t i = 0; i < gpus.size(); i++) {
+							if (gpu_auto and v_contains(Gpu::shown_panels, i))
+								continue;
+							auto& gpu = gpus[i]; auto& graph = graphs[i];
+
+							//? GPU graphs
+							if (gpu.supported_functions.gpu_utilization) {
+								if (i + 1 < gpus.size()) {
+									graph = Draw::Graph{graph_width, graph_height, "cpu", safeVal(gpu.gpu_percent, graph_field), graph_symbol, invert, true};
+								}
+								else {
+									graph = Draw::Graph{
+										graph_width + graph_default_width%graph_width - (int)gpus.size() + 1,
+										graph_height, "cpu", safeVal(gpu.gpu_percent, graph_field), graph_symbol, invert, true
+									};
+								}
+							}
+						}
+					} else {
+						graphs.resize(1);
+						graph_width = graph_default_width;
+						graphs[0] = Draw::Graph{ graph_width, graph_height, "cpu", safeVal(Gpu::shared_gpu_percent, graph_field), graph_symbol, invert, true };
+					}
+				}
+				else {
+			#endif
+					graphs.resize(1);
+					graph_width = graph_default_width;
+					graphs[0] = Draw::Graph{ graph_width, graph_height, "cpu", safeVal(cpu.cpu_percent, graph_field), graph_symbol, invert, true };
+			#ifdef GPU_SUPPORT
+				}
+			#endif
+			};
+
+            init_graphs(graphs_upper, graph_up_height, graph_up_width, graph_up_field, false);
+            if (not single_graph)
+            	init_graphs(graphs_lower, graph_low_height, graph_low_width, graph_lo_field, Config::getB("cpu_invert_lower"));
+
+			#ifdef GPU_SUPPORT
+			if (show_gpu and b_columns > 1) {
+				gpu_temp_graphs.resize(gpus.size());
+				gpu_mem_graphs.resize(gpus.size());
+				gpu_meters.resize(gpus.size());
+	
+				// Shrink gpu graph width in small boxes to prevent line width extending past box border
+				auto gpu_graph_width = b_width < 42 ? 4 : 5;
+
+				for (size_t i = 0; i < gpus.size(); i++) {
+					if (gpu_auto and v_contains(Gpu::shown_panels, i))
+						continue;
+					auto& gpu = gpus[i];
+
+					//? GPU graphs/meters
+					auto width_left = b_width - 10 - (gpus.size() > 9 ? 2 : gpus.size() > 1 ? 1 : 0);
+					if (gpu.supported_functions.temp_info and show_temps) {
+						gpu_temp_graphs[i] = Draw::Graph{ gpu_graph_width, 1, "temp", gpu.temp, graph_symbol, false, false, gpu.temp_max, -23 };
+						width_left -= 11;
+					}
+					if (gpu.supported_functions.mem_used and gpu.supported_functions.mem_total and b_columns > 1) {
+						gpu_mem_graphs[i] = Draw::Graph{ gpu_graph_width, 1, "used", safeVal(gpu.gpu_percent, "gpu-vram-totals"s), graph_symbol };
+						width_left -= 5;
+					}
+					width_left -= (gpu.supported_functions.mem_used ? 5 : 0);
+					width_left -= (gpu.supported_functions.mem_total ? 6 : 0);
+					width_left -= (gpu.supported_functions.pwr_usage ? 6 : 0);
+					if (gpu.supported_functions.gpu_utilization) {
+						gpu_meters[i] = Draw::Meter{width_left, "cpu" };
+					}
+				}
+			}
+			#endif
+
+			int cpu_meter_width = b_width - (show_temps ? 23 - (b_column_size <= 1 and b_columns == 1 ? 6 : 0) : 11);
+			if (show_watts) {
+				cpu_meter_width -= 6;
+			}
+
+			cpu_meter = Draw::Meter{cpu_meter_width, "cpu"};
+
+			if (mid_line) {
+				out += Mv::to(y + graph_up_height + 1, x) + Fx::ub + Theme::c("cpu_box") + Symbols::div_left + Theme::c("div_line")
+					+ Symbols::h_line * (width - b_width - 2) + Symbols::div_right
+					+ Mv::to(y + graph_up_height + 1, x + ((width - b_width) / 2) - ((graph_up_field.size() + graph_lo_field.size()) / 2) - 4)
+					+ Theme::c("main_fg") + graph_up_field + Mv::r(1) + "▲▼" + Mv::r(1) + graph_lo_field;
+			}
+
+			if (b_column_size > 0 or extra_width > 0) {
+				core_graphs.clear();
+				for (const auto& core_data : cpu.core_percent) {
+					core_graphs.emplace_back(5 * b_column_size + extra_width, 1, "cpu", core_data, graph_symbol);
+				}
+			}
+
+			if (show_temps) {
+				temp_graphs.clear();
+				temp_graphs.emplace_back(5, 1, "temp", safeVal(cpu.temp, 0), graph_symbol, false, false, cpu.temp_max, -23);
+				if (not hide_cores and b_column_size > 1) {
+					for (const auto& i : iota((size_t)1, cpu.temp.size())) {
+						temp_graphs.emplace_back(5, 1, "temp", safeVal(cpu.temp, i), graph_symbol, false, false, cpu.temp_max, -23);
+					}
+				}
+			}
+		}
+
+		//? Draw battery if enabled and present
+		if (Config::getB("show_battery") and has_battery) {
+			static int old_percent{};   // defaults to = 0
+			static long old_seconds{};  // defaults to = 0
+			static float old_watts{};	// defaults to = 0
+			static string old_status;
+			static Draw::Meter bat_meter {10, "cpu", true};
+			static const std::unordered_map<string, string> bat_symbols = {
+				{"charging", "▲"},
+				{"discharging", "▼"},
+				{"full", "■"},
+				{"unknown", "○"}
+			};
+
+			const auto& [percent, watts, seconds, status] = current_bat;
+
+			if (redraw or percent != old_percent or (watts != old_watts and Config::getB("show_battery_watts")) or seconds != old_seconds or status != old_status) {
+				old_percent = percent;
+				old_watts = watts;
+				old_seconds = seconds;
+				old_status = status;
+				const string str_time = (seconds > 0 ? sec_to_dhms(seconds, false, true) : "");
+				const string str_percent = to_string(percent) + '%';
+				const string str_watts = (watts != -1 and Config::getB("show_battery_watts") ? fmt::format("{:.2f}", watts) + 'W' : "");
+				const auto& bat_symbol = bat_symbols.at((bat_symbols.contains(status) ? status : "unknown"));
+				const int current_len = (Term::width >= 100 ? 11 : 0) + str_time.size() + str_percent.size() + str_watts.size() + to_string(Config::getI("update_ms")).size();
+				const int current_pos = Term::width - current_len - 17;
+
+				if ((bat_pos != current_pos or bat_len != current_len) and bat_pos > 0 and not redraw)
+					out += Mv::to(y, bat_pos) + Fx::ub + Theme::c("cpu_box") + Symbols::h_line * (bat_len + 4);
+				bat_pos = current_pos;
+				bat_len = current_len;
+
+				out += Mv::to(y, bat_pos) + title_left + Theme::c("title") + Fx::b + "BAT" + bat_symbol + ' ' + str_percent
+					+ (Term::width >= 100 ? Fx::ub + ' ' + bat_meter(percent) + Fx::b : "")
+					+ (not str_time.empty() ? ' ' + Theme::c("title") + str_time : "") + (not str_watts.empty() ? " " + Theme::c("title") + Fx::b + str_watts : "") + Fx::ub + title_right;
+			}
+		}
+		else if (bat_pos > 0) {
+			out += Mv::to(y, bat_pos) + Fx::ub + Theme::c("cpu_box") + Symbols::h_line * (bat_len + 4);
+			bat_pos = bat_len = 0;
+		}
+
+		try {
+			//? Cpu/Gpu graphs
+			out += Fx::ub + Mv::to(y + 1, x + 1);
+			auto draw_graphs = [&](vector<Draw::Graph>& graphs, const int graph_height, const int graph_width, const string& graph_field) {
+			#ifdef GPU_SUPPORT
+				if (graph_field.starts_with("gpu"))
+					if (graph_field.ends_with("totals")) {
+						int gpu_drawn = 0;
+						for (size_t i = 0; i < gpus.size(); i++) {
+							if (gpu_auto and v_contains(Gpu::shown_panels, i)) {
+								continue;
+							}
+							try {
+								const auto& gpu_percent = gpus[i].gpu_percent;
+								out += graphs[i](safeVal(gpu_percent, graph_field), (data_same or redraw));
+							} catch (std::out_of_range& /* unused */) {
+								continue;
+							}
+							if (Gpu::count - (gpu_auto ? Gpu::shown : 0) > 1) {
+								auto i_str = to_string(i);
+								out += Mv::l(graph_width-1) + Mv::u(graph_height/2) + (graph_width > 5 ? "GPU" : "") + i_str
+									+ Mv::d(graph_height/2) + Mv::r(graph_width - 1 - (graph_width > 5)*3 - i_str.size());
+							}
+
+							if (++gpu_drawn < Gpu::count - (gpu_auto ? Gpu::shown : 0))
+								out += Theme::c("div_line") + (Symbols::v_line + Mv::l(1) + Mv::u(1))*graph_height + Mv::r(1) + Mv::d(1);
+						}
+					}
+					else
+						out += graphs[0](safeVal(Gpu::shared_gpu_percent, graph_field), (data_same or redraw));
+				else
+			#else
+				(void)graph_height;
+				(void)graph_width;
+			#endif
+					out += graphs[0](safeVal(cpu.cpu_percent, graph_field), (data_same or redraw));
+			};
+
+			draw_graphs(graphs_upper, graph_up_height, graph_up_width, graph_up_field);
+			if (not single_graph) {
+				out += Mv::to(y + graph_up_height + 1 + mid_line, x + 1);
+				draw_graphs(graphs_lower, graph_low_height, graph_low_width, graph_lo_field);
+			}
+
+			//? Uptime
+			if (Config::getB("show_uptime")) {
+				string upstr = sec_to_dhms(system_uptime());
+				if (upstr.size() > 8) {
+					upstr.resize(upstr.size() - 3);
+					upstr = trans(upstr);
+				}
+				out += Mv::to(y + (single_graph or not Config::getB("cpu_invert_lower") ? 1 : height - 2), x + 2)
+					+ Theme::c("graph_text") + "up" + Mv::r(1) + upstr;
+			}
+
+		#ifdef __linux__
+			const bool freq_range = Config::getS("freq_mode") == "range";
+		#else
+			const bool freq_range = false;
+		#endif
+
+			//? Cpu clock and cpu meter
+			if (Config::getB("show_cpu_freq") and not cpuHz.empty())
+				out += Mv::to(b_y, b_x + b_width - (freq_range ? 20 : 10)) + Fx::ub + Theme::c("div_line")
+					+ Symbols::h_line * ((freq_range ? 17 : 7) - cpuHz.size())
+					+ Symbols::title_left + Fx::b + Theme::c("title") + cpuHz + Fx::ub + Theme::c("div_line") + Symbols::title_right;
+
+		out += Mv::to(b_y + 1, b_x + 1) + Theme::c("main_fg") + Fx::b + "CPU " + cpu_meter(safeVal(cpu.cpu_percent, "total"s).back())
+			+ 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") + '%';
+		if (show_temps) {
+			const auto [temp, unit] = celsius_to(safeVal(cpu.temp, 0).back(), temp_scale);
+			const auto temp_color = Theme::g("temp").at(clamp(safeVal(cpu.temp, 0).back() * 100 / cpu.temp_max, 0ll, 100ll));
+			if ((b_column_size > 1 or b_columns > 1) and temp_graphs.size() >= 1ll)
+				out += ' ' + Theme::c("inactive_fg") + graph_bg * 5 + Mv::l(5) + temp_color
+					+ temp_graphs.at(0)(safeVal(cpu.temp, 0), data_same or redraw);
+			out += rjust(to_string(temp), 4) + Theme::c("main_fg") + unit;
+		}
+
+		if (show_watts) {
+			string cwatts = fmt::format(" {:>4.{}f}", cpu.usage_watts, cpu.usage_watts < 10.0f ? 2 : cpu.usage_watts < 100.0f ? 1 : 0);
+			string cwatts_post = "W";
+
+			max_observed_pwr = max(max_observed_pwr, cpu.usage_watts);
+			out += Theme::g("cached").at(clamp(cpu.usage_watts / max_observed_pwr * 100.0f, 0.0f, 100.0f)) + cwatts + Theme::c("main_fg") + cwatts_post; 
+		}
+
+			out += Theme::c("div_line") + Symbols::v_line;
+		} catch (const std::exception& e) {
+			throw std::runtime_error("graphs, clock, meter : " + string{e.what()});
+		}
+
+		int max_row = b_height - 3; // Subtracting one extra row for the load average (and power if enabled)
+		int n_gpus_to_show = 0;
+	#ifdef GPU_SUPPORT
+		n_gpus_to_show = show_gpu ? (gpus.size() - (gpu_always ? 0 : Gpu::shown)) : 0;
+	#endif
+		max_row -= n_gpus_to_show;
+
+		auto is_cpu_enabled = [&cpu](const std::int32_t num) -> bool {
+			return !cpu.active_cpus.has_value() || std::ranges::find(cpu.active_cpus.value(), num) != cpu.active_cpus.value().end();
+		};
+
+		//? Core text and graphs
+		int cx = 0, cy = 1, cc = 0, core_width = (b_column_size == 0 ? 2 : 3);
+		if (Shared::coreCount >= 100) core_width++;
+		for (const auto& n : iota(0, Shared::coreCount)) {
+			auto enabled = is_cpu_enabled(n);
+			out += 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 : "")
+				+ ljust(to_string(n), core_width);
+			if ((b_column_size > 0 or extra_width > 0) and cmp_less(n, core_graphs.size()))
+				out += Theme::c("inactive_fg") + graph_bg * (5 * b_column_size + extra_width) + Mv::l(5 * b_column_size + extra_width)
+					+ core_graphs.at(n)(safeVal(cpu.core_percent, n), data_same or redraw);
+
+			out += enabled ? Theme::g("cpu").at(clamp(safeVal(cpu.core_percent, n).back(), 0ll, 100ll)) : Theme::c("inactive_fg");
+			out += rjust(to_string(safeVal(cpu.core_percent, n).back()), (b_column_size < 2 ? 3 : 4)) + Theme::c(enabled ? "main_fg" : "inactive_fg") + '%';
+
+			if (show_temps and not hide_cores) {
+				const auto [temp, unit] = celsius_to(safeVal(cpu.temp, n+1).back(), temp_scale);
+				const auto temp_color = enabled ? Theme::g("temp").at(clamp(safeVal(cpu.temp, n+1).back() * 100 / cpu.temp_max, 0ll, 100ll)) : Theme::c("inactive_fg");
+				if (b_column_size > 1 and std::cmp_greater_equal(temp_graphs.size(), n))
+					out += ' ' + Theme::c("inactive_fg") + graph_bg * 5 + Mv::l(5)
+						+ temp_graphs.at(n+1)(safeVal(cpu.temp, n+1), data_same or redraw);
+				out += temp_color + rjust(to_string(temp), 4) + Theme::c(enabled ? "main_fg" : "inactive_fg") + unit;
+			}
+
+			out += Theme::c("div_line") + Symbols::v_line;
+
+			if ((++cy > ceil((double)Shared::coreCount / b_columns) or cy == max_row) and n != Shared::coreCount - 1) {
+				if (++cc >= b_columns) break;
+				cy = 1; cx = (b_width / b_columns) * cc;
+			}
+		}
+
+		//? Load average
+		if (cy < b_height - 1 and cc <= b_columns) {
+			cy = b_height - 2 - n_gpus_to_show;
+
+			string load_avg_pre = "Load avg:";
+			string load_avg;
+
+			for (const auto& val : cpu.load_avg) {
+				load_avg += fmt::format(" {:.2f}", val);
+			}
+
+			int len = load_avg_pre.size() + load_avg.size();
+			out += 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;
+		}
+
+	#ifdef GPU_SUPPORT
+		//? Gpu brief info
+		if (show_gpu) {
+			for (unsigned long i = 0; i < gpus.size(); ++i) {
+				if (gpu_auto and v_contains(Gpu::shown_panels, i))
+					continue;
+				out += Mv::to(b_y + ++cy, b_x + 1) + Theme::c("main_fg") + Fx::b + "GPU";
+				if (gpus.size() > 1) out += rjust(to_string(i), 1 + (gpus.size() > 9));
+				if (gpus[i].supported_functions.gpu_utilization) {
+					out += ' ';
+					if (b_columns > 1) {
+					out += gpu_meters[i](safeVal(gpus[i].gpu_percent, "gpu-totals"s).back())
+						+ Theme::g("cpu").at(clamp(safeVal(gpus[i].gpu_percent, "gpu-totals"s).back(), 0ll, 100ll));
+					}
+					out += rjust(to_string(safeVal(gpus[i].gpu_percent, "gpu-totals"s).back()), 3) + Theme::c("main_fg") + '%';
+					if (b_columns == 1)
+						out += ' ';
+				}
+				if (gpus[i].supported_functions.mem_used and gpus[i].supported_functions.mem_total and b_columns > 1) {
+					out += ' ' + Theme::c("inactive_fg") + graph_bg * 5 + Mv::l(5) + Theme::g("used").at(safeVal(gpus[i].gpu_percent, "gpu-vram-totals"s).back())
+						+ gpu_mem_graphs[i](safeVal(gpus[i].gpu_percent, "gpu-vram-totals"s), data_same or redraw);
+				}
+				if (gpus[i].supported_functions.mem_used) {
+						out += Theme::c("main_fg")
+						+ rjust(floating_humanizer(gpus[i].mem_used, true), 5);
+				}
+				if (gpus[i].supported_functions.mem_total) {
+						out += Theme::c("inactive_fg") + '/' + Theme::c("main_fg") + ljust(floating_humanizer(gpus[i].mem_total, true), 4);
+				}
+				if (show_temps and gpus[i].supported_functions.temp_info) {
+					const auto [temp, unit] = celsius_to(gpus[i].temp.back(), temp_scale);
+					out += ' ';
+					if (b_columns > 1)
+						out += 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))
+							+ gpu_temp_graphs[i](gpus[i].temp, data_same or redraw);
+					else out += Theme::g("temp").at(clamp(gpus[i].temp.back() * 100 / gpus[i].temp_max, 0ll, 100ll));
+					out += rjust(to_string(temp), 3) + Theme::c("main_fg") + unit;
+				}
+				if (gpus[i].supported_functions.pwr_usage) {
+					out += ' ' + Theme::g("cached").at(clamp(safeVal(gpus[i].gpu_percent, "gpu-pwr-totals"s).back(), 0ll, 100ll))
+						+ 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';
+				}
+
+				if (cy > b_height - 1) break;
+			}
+		}
+	#endif
+
+		redraw = false;
+		return out + Fx::reset;
+	}
+
+}
+
+#ifdef GPU_SUPPORT
+namespace Gpu {
+	int width_p = 100, height_p = 32;
+	int min_width = 41, min_height = 8;
+	int width = 41, total_height;
+	vector<int> x_vec = {}, y_vec = {}, b_height_vec = {};
+	int b_width;
+	vector<int> b_x_vec = {}, b_y_vec = {};
+	vector<bool> redraw = {};
+	int shown = 0;
+	int count = 0;
+	vector<int> shown_panels = {};
+	int graph_up_height;
+	vector<Draw::Graph> graph_upper_vec = {}, graph_lower_vec = {};
+	vector<Draw::Graph> temp_graph_vec = {};
+	vector<Draw::Graph> mem_used_graph_vec = {}, mem_util_graph_vec = {};
+	vector<Draw::Meter> gpu_meter_vec = {};
+	vector<Draw::Meter> pwr_meter_vec = {};
+	vector<Draw::Meter> enc_meter_vec = {};
+	vector<string> box = {};
+
+    string draw(const gpu_info& gpu, unsigned long index, bool force_redraw, bool data_same) {
+		if (Runner::stopping) return "";
+
+		auto& b_x = b_x_vec[index];
+		auto& b_y = b_y_vec[index];
+		auto& x = x_vec[index];
+		auto& y = y_vec[index];
+
+		auto& graph_upper = graph_upper_vec[index];
+		auto& graph_lower = graph_lower_vec[index];
+		auto& temp_graph = temp_graph_vec[index];
+		auto& mem_used_graph = mem_used_graph_vec[index];
+		auto& mem_util_graph = mem_util_graph_vec[index];
+		auto& gpu_meter = gpu_meter_vec[index];
+		auto& pwr_meter = pwr_meter_vec[index];
+		auto& enc_meter = enc_meter_vec[index];
+
+		if (force_redraw) redraw[index] = true;
+        bool show_temps = gpu.supported_functions.temp_info and (Config::getB("check_temp"));
+        auto tty_mode = Config::getB("tty_mode");
+		auto& temp_scale = Config::getS("temp_scale");
+		auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_gpu"));
+		auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6);
+        auto single_graph = !Config::getB("gpu_mirror_graph");
+		string out;
+		int height = gpu_b_height_offsets[index] + 4;
+		out.reserve(width * height);
+
+		//* Redraw elements not needed to be updated every cycle
+		if (redraw[index]) {
+			out += box[index];
+
+			graph_up_height = single_graph ? b_height_vec[index] : (b_height_vec[index] + 1) / 2;
+			int graph_low_height = single_graph ? 0 : b_height_vec[index] - graph_up_height;
+
+			if (gpu.supported_functions.gpu_utilization) {
+				graph_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
+            	if (not single_graph) {
+                	graph_lower = Draw::Graph{
+                    	x + width - b_width - 3,
+                    	graph_low_height, "cpu",
+                    	safeVal(gpu.gpu_percent, "gpu-totals"s),
+                    	graph_symbol,
+                    	Config::getB("cpu_invert_lower"), true
+                	};
+            	}
+				gpu_meter = Draw::Meter{b_width - (show_temps ? 25 : 12), "cpu"};
+			}
+			if (gpu.supported_functions.temp_info)
+				temp_graph = Draw::Graph{6, 1, "temp", gpu.temp, graph_symbol, false, false, gpu.temp_max, -23};
+			if (gpu.supported_functions.pwr_usage)
+				pwr_meter = Draw::Meter{b_width - (gpu.supported_functions.pwr_state and gpu.pwr_state != 32 ? 25 : 12), "cached"};
+			if (gpu.supported_functions.mem_utilization)
+				mem_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
+			if (gpu.supported_functions.mem_used and gpu.supported_functions.mem_total)
+				mem_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};
+			if (gpu.supported_functions.encoder_utilization)
+				enc_meter = Draw::Meter{b_width/2 - 10, "cpu"};
+		}
+
+
+		//* General GPU info
+		int rows_used = 1;
+		//? Gpu graph, meter & clock speed
+		if (gpu.supported_functions.gpu_utilization) {
+			out += Fx::ub + Mv::to(y + rows_used, x + 1) + graph_upper(safeVal(gpu.gpu_percent, "gpu-totals"s), (data_same or redraw[index]));
+			if (not single_graph)
+				out += Mv::to(y + rows_used + graph_up_height, x + 1) + graph_lower(safeVal(gpu.gpu_percent, "gpu-totals"s), (data_same or redraw[index]));
+
+			out += 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())
+				+ 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") + '%';
+
+			//? Temperature graph, I assume the device supports utilization if it supports temperature
+			if (show_temps) {
+				const auto [temp, unit] = celsius_to(gpu.temp.back(), temp_scale);
+				out += ' ' + Theme::c("inactive_fg") + graph_bg * 6 + Mv::l(6) + Theme::g("temp").at(clamp(gpu.temp.back() * 100 / gpu.temp_max, 0ll, 100ll))
+					+ temp_graph(gpu.temp, data_same or redraw[index]);
+				out += rjust(to_string(temp), 4) + Theme::c("main_fg") + unit;
+			}
+			out += Theme::c("div_line") + Symbols::v_line;
+			rows_used++;
+		}
+
+		if (gpu.supported_functions.gpu_clock) {
+			string clock_speed_string = to_string(gpu.gpu_clock_speed);
+			out += Mv::to(b_y, b_x + b_width - 12) + Theme::c("div_line") + Symbols::h_line*(5-clock_speed_string.size())
+				+ Symbols::title_left + Fx::b + Theme::c("title") + clock_speed_string + " MHz" + Fx::ub + Theme::c("div_line") + Symbols::title_right;
+		}
+
+		//? Power usage meter, power state
+		if (gpu.supported_functions.pwr_usage) {
+			out += 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())
+				+ Theme::g("cached").at(clamp(safeVal(gpu.gpu_percent, "gpu-pwr-totals"s).back(), 0ll, 100ll))
+				+ 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';
+			if (gpu.supported_functions.pwr_state and gpu.pwr_state != 32) // NVML_PSTATE_UNKNOWN; unsupported or non-nvidia card
+				out += std::string(" P-state: ") + (gpu.pwr_state > 9 ? "" : " ") + 'P' + Theme::g("cached").at(clamp(gpu.pwr_state, 0ll, 100ll)) + to_string(gpu.pwr_state);
+			rows_used++;
+		}
+
+		//? Encode and Decode meters
+		bool drawnEncDec = gpu.supported_functions.encoder_utilization and gpu.supported_functions.decoder_utilization;
+		if (drawnEncDec) {
+			out += Mv::to(b_y + rows_used, b_x +1) + Theme::c("main_fg") + Fx::b + "ENC " + enc_meter(gpu.encoder_utilization)
+				+ Theme::g("cpu").at(clamp(gpu.encoder_utilization, 0ll, 100ll)) + rjust(to_string(gpu.encoder_utilization), 4) + Theme::c("main_fg") + '%'
+				+ Theme::c("div_line") + Symbols::v_line + Theme::c("main_fg") + Fx::b + "DEC " + enc_meter(gpu.decoder_utilization)
+				+ Theme::g("cpu").at(clamp(gpu.decoder_utilization, 0ll, 100ll)) + rjust(to_string(gpu.decoder_utilization), 4) + Theme::c("main_fg") + '%';
+			rows_used++;
+		}
+
+		if (gpu.supported_functions.mem_total or gpu.supported_functions.mem_used) {
+			out += Mv::to(b_y + rows_used, b_x);
+			if (gpu.supported_functions.mem_total and gpu.supported_functions.mem_used) {
+				string used_memory_string = floating_humanizer(gpu.mem_used);
+
+				auto offset = (gpu.supported_functions.mem_total or gpu.supported_functions.mem_used)
+					* (1 + 2*(gpu.supported_functions.mem_total and gpu.supported_functions.mem_used) + 2*gpu.supported_functions.mem_utilization);
+
+				//? Used graph, memory section header, total vram
+				out += 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
+					+  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
+					+  Symbols::h_line + Theme::c("title") + "Used:" + Theme::c("div_line")
+					+  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
+					+  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]))
+					+  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
+					+  Mv::r(3) + rjust(to_string(safeVal(gpu.gpu_percent, "gpu-vram-totals"s).back()), 3) + '%';
+
+				//? Memory utilization
+				if (gpu.supported_functions.mem_utilization)
+					out += 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
+						+  Mv::l(b_width/2)   + Mv::d(1) + mem_util_graph(gpu.mem_utilization_percent, (data_same or redraw[index]))
+						+  Mv::l(b_width/2-1) + Mv::u(1) + rjust(to_string(gpu.mem_utilization_percent.back()), 3) + '%';
+
+				//? Memory clock speed
+				if (gpu.supported_functions.mem_clock) {
+					string clock_speed_string = to_string(gpu.mem_clock_speed);
+					out += Mv::to(b_y + rows_used, b_x + b_width/2 - 11) + Theme::c("div_line") + Symbols::h_line*(5-clock_speed_string.size())
+						+ Symbols::title_left + Fx::b + Theme::c("title") + clock_speed_string + " MHz" + Fx::ub + Theme::c("div_line") + Symbols::title_right;
+				}
+			} else {
+				out += Theme::c("main_fg") + Mv::r(1);
+				if (gpu.supported_functions.mem_total)
+					out += "VRAM total:" + rjust(floating_humanizer(gpu.mem_total), b_width/(1 + gpu.supported_functions.mem_clock)-14);
+				else out += "VRAM usage:" + rjust(floating_humanizer(gpu.mem_used), b_width/(1 + gpu.supported_functions.mem_clock)-14);
+
+				if (gpu.supported_functions.mem_clock)
+					out += "   VRAM clock:" + rjust(to_string(gpu.mem_clock_speed) + " MHz", b_width/2-13);
+			}
+		}
+
+		//? Processes section header
+		//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")
+		//	+ Symbols::title_right + Symbols::h_line*(b_width/2-12) + Symbols::div_down + Symbols::h_line*(b_width/2-2) + Symbols::div_right;
+
+		//? PCIe link throughput
+		if (gpu.supported_functions.pcie_txrx and Config::getB("nvml_measure_pcie_speeds")) {
+			string tx_string = floating_humanizer(gpu.pcie_tx, 0, 1, 0, 1);
+			string rx_string = floating_humanizer(gpu.pcie_rx, 0, 1, 0, 1);
+			out += Mv::to(b_y + b_height_vec[index] - 1, b_x+2) + Theme::c("div_line")
+				+ 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())
+				+ 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)
+				+ 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())
+				+ 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;
+		}
+
+		redraw[index] = false;
+		return out + Fx::reset;
+	}
+
+}
+#endif
+
+namespace Mem {
+	int width_p = 45, height_p = 36;
+	int min_width = 36, min_height = 10;
+	int x = 1, y, width = 20, height;
+	int mem_width, disks_width, divider, item_height, mem_size, mem_meter, graph_height, disk_meter;
+	int disks_io_h = 0;
+	int disks_io_half = 0;
+	bool shown = true, redraw = true;
+	string box;
+	std::unordered_map<string, Draw::Meter> mem_meters;
+	std::unordered_map<string, Draw::Graph> mem_graphs;
+	std::unordered_map<string, Draw::Meter> disk_meters_used;
+	std::unordered_map<string, Draw::Meter> disk_meters_free;
+	std::unordered_map<string, Draw::Graph> io_graphs;
+
+	string draw(const mem_info& mem, bool force_redraw, bool data_same) {
+		if (Runner::stopping) return "";
+		if (force_redraw) redraw = true;
+		auto show_swap = Config::getB("show_swap");
+		auto swap_disk = Config::getB("swap_disk");
+		auto show_disks = Config::getB("show_disks");
+		auto show_io_stat = Config::getB("show_io_stat");
+		auto io_mode = Config::getB("io_mode");
+		auto io_graph_combined = Config::getB("io_graph_combined");
+		auto use_graphs = Config::getB("mem_graphs");
+		auto tty_mode = Config::getB("tty_mode");
+		auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_mem"));
+		auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6);
+		auto totalMem = Mem::get_totalMem();
+		string out;
+		out.reserve(height * width);
+
+		//* Redraw elements not needed to be updated every cycle
+		if (redraw) {
+			out += box;
+			mem_meters.clear();
+			mem_graphs.clear();
+			disk_meters_free.clear();
+			disk_meters_used.clear();
+			io_graphs.clear();
+
+			//? Mem graphs and meters
+			for (const auto& name : mem_names) {
+
+				if (use_graphs)
+					mem_graphs[name] = Draw::Graph{mem_meter, graph_height, name, safeVal(mem.percent, name), graph_symbol};
+				else
+					mem_meters[name] = Draw::Meter{mem_meter, name};
+			}
+			if (show_swap and has_swap) {
+				for (const auto& name : swap_names) {
+					if (use_graphs)
+						mem_graphs[name] = Draw::Graph{mem_meter, graph_height, name.substr(5), safeVal(mem.percent, name), graph_symbol};
+					else
+						mem_meters[name] = Draw::Meter{mem_meter, name.substr(5)};
+				}
+			}
+
+			//? Disk meters and io graphs
+			if (show_disks) {
+				if (show_io_stat or io_mode) {
+					std::unordered_map<string, int> custom_speeds;
+					int half_height = 0;
+					if (io_mode) {
+						disks_io_h = max((int)floor((double)(height - 2 - (disk_ios * 2)) / max(1, disk_ios)), (io_graph_combined ? 1 : 2));
+						half_height = ceil((double)disks_io_h / 2);
+
+						if (not Config::getS("io_graph_speeds").empty()) {
+							auto split = ssplit(Config::getS("io_graph_speeds"));
+							for (const auto& entry : split) {
+								auto vals = ssplit(entry, ':');
+								if (vals.size() == 2 and mem.disks.contains(vals.at(0)) and isint(vals.at(1)))
+									try {
+										custom_speeds[vals.at(0)] = std::stoi(vals.at(1));
+									}
+									catch (const std::out_of_range&) { continue; }
+							}
+						}
+					}
+
+					for (const auto& [name, disk] : mem.disks) {
+						if (disk.io_read.empty()) continue;
+
+						io_graphs[name + "_activity"] = Draw::Graph{disks_width - 6, 1, "available", disk.io_activity, graph_symbol};
+
+						if (io_mode) {
+							//? Create one combined graph for IO read/write if enabled
+							long long speed = (custom_speeds.contains(name) ? custom_speeds.at(name) : 100) << 20;
+							if (io_graph_combined) {
+								deque<long long> combined(disk.io_read.size(), 0);
+								rng::transform(disk.io_read, disk.io_write, combined.begin(), std::plus<long long>());
+								io_graphs[name] = Draw::Graph{
+									disks_width, disks_io_h, "available", combined,
+									graph_symbol, false, true, speed};
+							}
+							else {
+								io_graphs[name + "_read"] = Draw::Graph{
+									disks_width, half_height, "free",
+									disk.io_read, graph_symbol, false,
+									true, speed};
+								io_graphs[name + "_write"] = Draw::Graph{
+									disks_width, disks_io_h - half_height,
+									"used", disk.io_write, graph_symbol,
+									true, true, speed};
+							}
+						}
+					}
+				}
+
+				for (int i = 0; const auto& [name, ignored] : mem.disks) {
+					if (i * 2 > height - 2) break;
+					disk_meters_used[name] = Draw::Meter{disk_meter, "used"};
+					if (cmp_less_equal(mem.disks.size() * 3, height - 1))
+						disk_meters_free[name] = Draw::Meter{disk_meter, "free"};
+				}
+
+				out += Mv::to(y, x + width - 6) + Fx::ub + Theme::c("mem_box") + Symbols::title_left + (io_mode ? Fx::b : "") + Theme::c("hi_fg")
+				+ 'i' + Theme::c("title") + 'o' + Fx::ub + Theme::c("mem_box") + Symbols::title_right;
+				Input::mouse_mappings["i"] = {y, x + width - 5, 1, 2};
+			}
+
+		}
+
+		//? Mem and swap
+		int cx = 1, cy = 1;
+		string divider = (graph_height > 0 ? Mv::l(2) + Theme::c("mem_box") + Symbols::div_left + Theme::c("div_line") + Symbols::h_line * (mem_width - 1)
+						+ (show_disks ? "" : Theme::c("mem_box")) + Symbols::div_right + Mv::l(mem_width - 1) + Theme::c("main_fg") : "");
+		string up = (graph_height >= 2 ? Mv::l(mem_width - 2) + Mv::u(graph_height - 1) : "");
+		bool big_mem = mem_width > 21;
+
+		out += 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");
+		vector<string> comb_names (mem_names.begin(), mem_names.end());
+		if (show_swap and has_swap and not swap_disk) comb_names.insert(comb_names.end(), swap_names.begin(), swap_names.end());
+		for (const auto& name : comb_names) {
+			if (cy > height - 4) break;
+			string title;
+			if (name == "swap_used") {
+				if (cy > height - 5) break;
+				if (height - cy > 6) {
+					if (graph_height > 0) out += Mv::to(y+1+cy, x+1+cx) + divider;
+					cy += 1;
+				}
+				out += 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)
+					+ Theme::c("main_fg") + Fx::ub;
+				cy += 1;
+				title = "Used";
+			}
+			else if (name == "swap_free")
+				title = "Free";
+
+			if (title.empty()) title = capitalize(name);
+			const string humanized = floating_humanizer(safeVal(mem.stats, name));
+			const int offset = max(0, divider.empty() ? 9 - (int)humanized.size() : 0);
+			const string graphics = (
+				use_graphs and mem_graphs.contains(name) ? mem_graphs.at(name)(safeVal(mem.percent, name), redraw or data_same)
+				: mem_meters.contains(name) ? mem_meters.at(name)(safeVal(mem.percent, name).back())
+				: "");
+			if (mem_size > 2) {
+				out += Mv::to(y+1+cy, x+1+cx) + divider + title.substr(0, big_mem ? 10 : 5) + ":"
+					+ Mv::to(y+1+cy, x+cx + mem_width - 2 - humanized.size()) + (divider.empty() ? Mv::l(offset) + string(" ") * offset + humanized : trans(humanized))
+					+ Mv::to(y+2+cy, x+cx + (graph_height >= 2 ? 0 : 1)) + graphics + up + rjust(to_string(safeVal(mem.percent, name).back()) + "%", 4);
+				cy += (graph_height == 0 ? 2 : graph_height + 1);
+			}
+			else {
+				out += Mv::to(y+1+cy, x+1+cx) + ljust(title, (mem_size > 1 ? 5 : 1)) + (graph_height >= 2 ? "" : " ")
+					+ graphics + Theme::c("title") + rjust(humanized, (mem_size > 1 ? 9 : 7));
+				cy += (graph_height == 0 ? 1 : graph_height);
+			}
+		}
+		if (graph_height > 0 and cy < height - 2)
+			out += Mv::to(y+1+cy, x+1+cx) + divider;
+
+		//? Disks
+		if (show_disks) {
+			const auto& disks = mem.disks;
+			cx = mem_width; cy = 0;
+			bool big_disk = disks_width >= 25;
+			divider = 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);
+			const string hu_div = Theme::c("div_line") + Symbols::h_line + Theme::c("main_fg");
+			if (io_mode) {
+				for (const auto& mount : mem.disks_order) {
+					if (not disks.contains(mount)) continue;
+					if (cy > height - 3) break;
+					const auto disk = safeVal(disks, mount);
+					if (disk.io_read.empty()) continue;
+					const string total = floating_humanizer(disk.total, not big_disk);
+					out += 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())
+						+ trans(total) + Fx::ub;
+					if (big_disk) {
+						const string used_percent = to_string(disk.used_percent);
+						out += 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;
+					}
+					if (io_graphs.contains(mount + "_activity")) {
+					out += Mv::to(y+2+cy++, x+1+cx) + (big_disk ? " IO% " : " IO   " + Mv::l(2)) + Theme::c("inactive_fg") + graph_bg * (disks_width - 6)
+						+ Mv::l(disks_width - 6) + io_graphs.at(mount + "_activity")(disk.io_activity, redraw or data_same) + Theme::c("main_fg");
+					}
+					if (++cy > height - 3) break;
+					if (io_graph_combined) {
+						if (not io_graphs.contains(mount)) continue;
+						auto comb_val = disk.io_read.back() + disk.io_write.back();
+						const string humanized = (disk.io_write.back() > 0 ? "▼"s : ""s) + (disk.io_read.back() > 0 ? "▲"s : ""s)
+												+ (comb_val > 0 ? Mv::r(1) + floating_humanizer(comb_val, true) : "RW");
+						if (disks_io_h == 1) out += Mv::to(y+1+cy, x+1+cx) + string(5, ' ');
+						out += Mv::to(y+1+cy, x+1+cx) + io_graphs.at(mount)({comb_val}, redraw or data_same)
+							+ Mv::to(y+1+cy, x+1+cx) + Theme::c("main_fg") + humanized;
+						cy += disks_io_h;
+					}
+					else {
+						if (not io_graphs.contains(mount + "_read") or not io_graphs.contains(mount + "_write")) continue;
+						const string human_read = (disk.io_read.back() > 0 ? "▲" + floating_humanizer(disk.io_read.back(), true) : "R");
+						const string human_write = (disk.io_write.back() > 0 ? "▼" + floating_humanizer(disk.io_write.back(), true) : "W");
+						if (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, ' ');
+						out += Mv::to(y+1+cy, x+1+cx) + io_graphs.at(mount + "_read")(disk.io_read, redraw or data_same) + Mv::l(disks_width)
+							+ Mv::d(1) + io_graphs.at(mount + "_write")(disk.io_write, redraw or data_same)
+							+ Mv::to(y+1+cy, x+1+cx) + human_read + Mv::to(y+cy + disks_io_h, x+1+cx) + human_write;
+						cy += disks_io_h;
+					}
+				}
+			}
+			else {
+				for (const auto& mount : mem.disks_order) {
+					if (not disks.contains(mount)) continue;
+					if (cy > height - 3) break;
+					const auto disk = safeVal(disks, mount);
+					if (disk.name.empty() or not disk_meters_used.contains(mount)) continue;
+					auto comb_val = (not disk.io_read.empty() ? disk.io_read.back() + disk.io_write.back() : 0ll);
+					const 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)
+											+ floating_humanizer(comb_val, true) : "");
+					const string human_total = floating_humanizer(disk.total, not big_disk);
+					const string human_used = floating_humanizer(disk.used, not big_disk);
+					const string human_free = floating_humanizer(disk.free, not big_disk);
+
+					out += 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())
+						+ trans(human_total) + Fx::ub + Theme::c("main_fg");
+					if (big_disk and not human_io.empty())
+						out += 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;
+					if (++cy > height - 3) break;
+					if (show_io_stat and io_graphs.contains(mount + "_activity")) {
+						out += 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))
+							+ Mv::l(disks_width - 6) + io_graphs.at(mount + "_activity")(disk.io_activity, redraw or data_same) + Theme::c("main_fg");
+						if (not big_disk) out += Mv::to(y+1+cy, x+cx+1) + Theme::c("main_fg") + human_io;
+						if (++cy > height - 3) break;
+					}
+
+					out += Mv::to(y+1+cy, x+1+cx) + (big_disk ? " Used:" + rjust(to_string(disk.used_percent) + '%', 4) : "U") + ' '
+						+ disk_meters_used.at(mount)(disk.used_percent) + rjust(human_used, (big_disk ? 9 : 5));
+					if (++cy > height - 3) break;
+
+					if (disk_meters_free.contains(mount) and cmp_less_equal(disks.size() * 3 + (show_io_stat ? disk_ios : 0), height - 1)) {
+						out += Mv::to(y+1+cy, x+1+cx) + (big_disk ? " Free:" + rjust(to_string(disk.free_percent) + '%', 4) : "F") + ' '
+						+ disk_meters_free.at(mount)(disk.free_percent) + rjust(human_free, (big_disk ? 9 : 5));
+						cy++;
+						if (cmp_less_equal(disks.size() * 4 + (show_io_stat ? disk_ios : 0), height - 1)) cy++;
+					}
+
+				}
+			}
+			if (cy < height - 2) out += Mv::to(y+1+cy, x+1+cx) + divider;
+		}
+
+		redraw = false;
+		return out + Fx::reset;
+	}
+
+}
+
+namespace Net {
+	int width_p = 45, height_p = 32;
+	int min_width = 36, min_height = 6;
+	int x = 1, y, width = 20, height;
+	int b_x, b_y, b_width, b_height, d_graph_height, u_graph_height;
+	bool shown = true, redraw = true;
+	const int MAX_IFNAMSIZ = 15;
+	string old_ip;
+	std::unordered_map<string, Draw::Graph> graphs;
+	string box;
+
+	string draw(const net_info& net, bool force_redraw, bool data_same) {
+		if (Runner::stopping) return "";
+		if (force_redraw) redraw = true;
+		auto net_sync = Config::getB("net_sync");
+		auto net_auto = Config::getB("net_auto");
+		auto tty_mode = Config::getB("tty_mode");
+		auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_net"));
+		string ip_addr = (net.ipv4.empty() ? net.ipv6 : net.ipv4);
+		if (old_ip != ip_addr) {
+			old_ip = ip_addr;
+			redraw = true;
+		}
+		string out;
+		out.reserve(width * height);
+		const string title_left = Theme::c("net_box") + Fx::ub + Symbols::title_left;
+		const string title_right = Theme::c("net_box") + Fx::ub + Symbols::title_right;
+		const int i_size = min((int)selected_iface.size(), MAX_IFNAMSIZ);
+		const long long down_max = (net_auto ? safeVal(graph_max, "download"s) : ((long long)(Config::getI("net_download")) << 20) / 8);
+		const long long up_max = (net_auto ? safeVal(graph_max, "upload"s) : ((long long)(Config::getI("net_upload")) << 20) / 8);
+
+		//* Redraw elements not needed to be updated every cycle
+		if (redraw) {
+			out = box;
+			//? Graphs
+			graphs.clear();
+			if (safeVal(net.bandwidth, "download"s).empty() or safeVal(net.bandwidth, "upload"s).empty())
+				return out + Fx::reset;
+			graphs["download"] = Draw::Graph{
+				width - b_width - 2, u_graph_height, "download",
+				net.bandwidth.at("download"), graph_symbol,
+				false, true, down_max};
+			graphs["upload"] = Draw::Graph{
+				width - b_width - 2, d_graph_height, "upload",
+				net.bandwidth.at("upload"), graph_symbol, true, true, up_max};
+
+			//? Interface selector and buttons
+
+			out += Mv::to(y, x+width - i_size - 9) + title_left + Fx::b + Theme::c("hi_fg") + Symbols::left + "b " + Theme::c("title")
+				+ uresize(selected_iface, MAX_IFNAMSIZ) + Theme::c("hi_fg") + " n" + Symbols::right + title_right
+				+ 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'
+				+ Theme::c("title") + "ero" + title_right;
+			Input::mouse_mappings["b"] = {y, x+width - i_size - 8, 1, 3};
+			Input::mouse_mappings["n"] = {y, x+width - 6, 1, 3};
+			Input::mouse_mappings["z"] = {y, x+width - i_size - 14, 1, 4};
+			if (width - i_size - 20 > 6) {
+				out += 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;
+				Input::mouse_mappings["a"] = {y, x+width - i_size - 20, 1, 4};
+			}
+			if (width - i_size - 20 > 13) {
+				out += Mv::to(y, x+width - i_size - 27) + title_left + Theme::c("title") + (net_sync ? Fx::b : "") + 's' + Theme::c("hi_fg")
+					+ 'y' + Theme::c("title") + "nc" + title_right;
+				Input::mouse_mappings["y"] = {y, x+width - i_size - 26, 1, 4};
+			}
+		}
+
+		//? IP or device address
+		if (not ip_addr.empty() and cmp_greater(width - i_size - 36, ip_addr.size())) {
+			out += Mv::to(y, x + 8) + title_left + Theme::c("title") + Fx::b + ip_addr + title_right;
+		}
+
+		//? Graphs and stats
+		int cy = 0;
+		for (const string dir : {"download", "upload"}) {
+			out += Mv::to(y+1 + (dir == "upload" ? u_graph_height : 0), x + 1) + graphs.at(dir)(safeVal(net.bandwidth, dir), redraw or data_same or not net.connected)
+				+ Mv::to(y+1 + (dir == "upload" ? height - 3: 0), x + 1) + Fx::ub + Theme::c("graph_text")
+				+ floating_humanizer((dir == "upload" ? up_max : down_max), true);
+			const string speed = floating_humanizer(safeVal(net.stat, dir).speed, false, 0, false, true);
+			const string speed_bits = (b_width >= 20 ? floating_humanizer(safeVal(net.stat, dir).speed, false, 0, true, true) : "");
+			const string top = floating_humanizer(safeVal(net.stat, dir).top, false, 0, true, true);
+			const string total = floating_humanizer(safeVal(net.stat, dir).total);
+			const string symbol = (dir == "upload" ? "▲" : "▼");
+			out += Mv::to(b_y+1+cy, b_x+1) + Fx::ub + Theme::c("main_fg") + symbol + ' ' + ljust(speed, 10) + (b_width >= 20 ? rjust('(' + speed_bits + ')', 13) : "");
+			cy += (b_height == 5 ? 2 : 1);
+			if (b_height >= 8) {
+				out += Mv::to(b_y+1+cy, b_x+1) + symbol + ' ' + "Top: " + rjust('(' + top, (b_width >= 20 ? 17 : 9)) + ')';
+				cy++;
+			}
+			if (b_height >= 6) {
+				out += Mv::to(b_y+1+cy, b_x+1) + symbol + ' ' + "Total: " + rjust(total, (b_width >= 20 ? 16 : 8));
+				cy += (b_height > 6 and b_height % 2 ? 2 : 1);
+			}
+		}
+
+		redraw = false;
+		return out + Fx::reset;
+	}
+
+}
+
+namespace Proc {
+	int width_p = 55, height_p = 68;
+	int min_width = 44, min_height = 16;
+	int x, y, width = 20, height;
+	int start, selected, select_max;
+	bool shown = true, redraw = true;
+	int selected_pid = 0, selected_depth = 0;
+	string selected_name;
+	std::unordered_map<size_t, Draw::Graph> p_graphs;
+	std::unordered_map<size_t, bool> p_wide_cmd;
+	std::unordered_map<size_t, int> p_counters;
+	int counter = 0;
+	Draw::TextEdit filter;
+	Draw::Graph detailed_cpu_graph;
+	Draw::Graph detailed_mem_graph;
+	int user_size, thread_size, prog_size, cmd_size, tree_size;
+	int dgraph_x, dgraph_width, d_width, d_x, d_y;
+
+	string box;
+
+	int selection(const std::string_view cmd_key) {
+		auto start = Config::getI("proc_start");
+		auto selected = Config::getI("proc_selected");
+		auto last_selected = Config::getI("proc_last_selected");
+		const int select_max = (Config::getB("show_detailed") ? (Config::getB("pause_proc_list") ? Proc::select_max - 9 : Proc::select_max - 8) :
+																(Config::getB("pause_proc_list") ? Proc::select_max - 1 : Proc::select_max));
+		auto vim_keys = Config::getB("vim_keys");
+
+		int numpids = Proc::numpids;
+		if ((cmd_key == "up" or (vim_keys and cmd_key == "k")) and selected > 0) {
+			if (start > 0 and selected == 1) start--;
+			else selected--;
+			if (Config::getI("proc_last_selected") > 0) Config::set("proc_last_selected", 0);
+		}
+		else if (cmd_key == "mouse_scroll_up" and start > 0) {
+			start = max(0, start - 3);
+		}
+		else if (cmd_key == "mouse_scroll_down" and start < numpids - select_max) {
+			start = min(numpids - select_max, start + 3);
+		}
+		else if (cmd_key == "down" or (vim_keys and cmd_key == "j")) {
+			if (start < numpids - select_max and selected == select_max) start++;
+			else if (selected == 0 and last_selected > 0) {
+				selected = last_selected;
+				Config::set("proc_last_selected", 0);
+			}
+			else selected++;
+		}
+		else if (cmd_key == "page_up") {
+			if (selected > 0 and start == 0) selected = 0;
+			else start = max(0, start - select_max);
+		}
+		else if (cmd_key == "page_down") {
+			if (selected > 0 and start >= numpids - select_max) selected = select_max;
+			else start = clamp(start + select_max, 0, max(0, numpids - select_max));
+		}
+		else if (cmd_key == "home" or (vim_keys and cmd_key == "g")) {
+			start = 0;
+			if (selected > 0) selected = 1;
+		}
+		else if (cmd_key == "end" or (vim_keys and cmd_key == "G")) {
+			start = max(0, numpids - select_max);
+			if (selected > 0) selected = select_max;
+		}
+		else if (cmd_key.starts_with("mousey")) {
+			int mouse_y = std::atoi(cmd_key.substr(6).data());
+			start = clamp((int)round((double)mouse_y * (numpids - select_max - 2) / (select_max - 2)), 0, max(0, numpids - select_max));
+		}
+
+		bool changed = false;
+		if (start != Config::getI("proc_start")) {
+			Config::set("proc_start", start);
+			changed = true;
+		}
+		if (selected != Config::getI("proc_selected")) {
+			Config::set("proc_selected", selected);
+			changed = true;
+		}
+		return (not changed ? -1 : selected);
+	}
+
+	string draw(const vector<proc_info>& plist, bool force_redraw, bool data_same) {
+		if (Runner::stopping) return "";
+		auto proc_tree = Config::getB("proc_tree");
+		// AltData: 关闭进程详情弹窗/展开逻辑
+		bool show_detailed = false;
+		bool proc_gradient = (Config::getB("proc_gradient") and not Config::getB("lowcolor") and Theme::gradients.contains("proc"));
+		auto proc_colors = Config::getB("proc_colors");
+		auto tty_mode = Config::getB("tty_mode");
+		auto& graph_symbol = (tty_mode ? "tty" : Config::getS("graph_symbol_proc"));
+		auto& graph_bg = Symbols::graph_symbols.at((graph_symbol == "default" ? Config::getS("graph_symbol") + "_up" : graph_symbol + "_up")).at(6);
+		auto mem_bytes = Config::getB("proc_mem_bytes");
+		auto vim_keys = Config::getB("vim_keys");
+		auto show_graphs = Config::getB("proc_cpu_graphs");
+		const auto pause_proc_list = Config::getB("pause_proc_list");
+		start = Config::getI("proc_start");
+		selected = Config::getI("proc_selected");
+		const int y = show_detailed ? Proc::y + 8 : Proc::y;
+		const int height = show_detailed ? Proc::height - 8 : Proc::height;
+		const int select_max = show_detailed ? (pause_proc_list ? Proc::select_max - 9 : Proc::select_max - 8) : 
+												(pause_proc_list ? Proc::select_max - 1 : Proc::select_max);
+		auto totalMem = Mem::get_totalMem();
+		int numpids = Proc::numpids;
+		if (force_redraw) redraw = true;
+		string out;
+		out.reserve(width * height);
+
+		//* Redraw elements not needed to be updated every cycle
+		if (redraw) {
+			out = box;
+			const string title_left = Theme::c("proc_box") + Symbols::title_left;
+			const string title_right = Theme::c("proc_box") + Symbols::title_right;
+			const string title_left_down = Theme::c("proc_box") + Symbols::title_left_down;
+			const string title_right_down = Theme::c("proc_box") + Symbols::title_right_down;
+			// AltData: remove enter mapping completely
+		for (const auto& key : {"T", "K", "S"})
+				if (Input::mouse_mappings.contains(key)) Input::mouse_mappings.erase(key);
+
+			//? AltData: 固定列宽
+			user_size   = 8;   // (未使用)
+			thread_size = -1;  // 不显示 threads
+			prog_size   = 4;   // type: 2中文字符=4列宽
+			// time(8) + 空格(1) + type(4) + 空格(1) + 边框(2) + 滑块(1) = 17
+			cmd_size    = max(10, width - 17);
+			tree_size   = width - 17;
+
+			//? Detailed box
+			if (show_detailed) {
+				bool alive = detailed.status != "Dead";
+				dgraph_x = x;
+				dgraph_width = max(width / 3, width - 121);
+				d_width = width - dgraph_width - 1;
+				d_x = x + dgraph_width + 1;
+				d_y = Proc::y;
+
+				//? Create cpu and mem graphs if process is alive
+				if (alive or pause_proc_list) {
+					detailed_cpu_graph = Draw::Graph{dgraph_width - 1, 7, "cpu", detailed.cpu_percent, graph_symbol, false, true};
+					detailed_mem_graph = Draw::Graph{d_width / 3, 1, "", detailed.mem_bytes, graph_symbol, false, false, detailed.first_mem};
+				}
+
+				//? Draw structure of details box
+				const string pid_str = to_string(detailed.entry.pid);
+				out += Mv::to(y, x) + Theme::c("proc_box") + Symbols::div_left + Symbols::h_line + title_left + Theme::c("hi_fg") + Fx::b
+				+ (tty_mode ? "4" : Symbols::superscript.at(4)) + Theme::c("title") + "proc"
+					+ Fx::ub + title_right + Symbols::h_line * (width - 10) + Symbols::div_right
+					+ Mv::to(d_y, dgraph_x + 2) + title_left + Fx::b + Theme::c("title") + pid_str + Fx::ub + title_right
+					+ title_left + Fx::b + Theme::c("title") + uresize(detailed.entry.name, dgraph_width - pid_str.size() - 7, true) + Fx::ub + title_right;
+
+				out += 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");
+				for (const int& i : iota(1, 8)) out += Mv::to(d_y + i, d_x - 1) + Symbols::v_line;
+
+				const string t_color = (not alive or selected > 0 ? Theme::c("inactive_fg") : Theme::c("title"));
+				const string hi_color = (not alive or selected > 0 ? t_color : Theme::c("hi_fg"));
+				int mouse_x = d_x + 2;
+				out += Mv::to(d_y, d_x + 1);
+				if (width > 55) {
+					out += Fx::ub + title_left + hi_color + Fx::b + 't' + t_color + "erminate" + Fx::ub + title_right;
+					if (alive and selected == 0) Input::mouse_mappings["t"] = {d_y, mouse_x, 1, 9};
+					mouse_x += 11;
+				}
+				out += title_left + hi_color + Fx::b + (vim_keys ? 'K' : 'k') + t_color + "ill" + Fx::ub + title_right
+					+ title_left + hi_color + Fx::b + 's' + t_color + "ignals" + Fx::ub + title_right
+					+ title_left + hi_color + Fx::b + 'N' + t_color + "ice" + Fx::ub + title_right;
+				if (alive and selected == 0) {
+					Input::mouse_mappings["k"] = {d_y, mouse_x, 1, 4};
+					mouse_x += 6;
+					Input::mouse_mappings["s"] = {d_y, mouse_x, 1, 7};
+				    mouse_x += 9;
+					Input::mouse_mappings["N"] = {d_y, mouse_x, 1, 5};
+				}
+
+				//? Labels
+				const int item_fit = floor((double)(d_width - 2) / 10);
+				const int item_width = floor((double)(d_width - 2) / min(item_fit, 8));
+				out += Mv::to(d_y + 1, d_x + 1) + Fx::b + Theme::c("title")
+										+ cjust("Status:", item_width)
+										+ cjust("Elapsed:", item_width);
+				if (item_fit >= 3) out += cjust("IO/R:", item_width);
+				if (item_fit >= 4) out += cjust("IO/W:", item_width);
+				if (item_fit >= 5) out += cjust("Parent:", item_width);
+				if (item_fit >= 6) out += cjust("User:", item_width);
+				if (item_fit >= 7) out += cjust("Threads:", item_width);
+				if (item_fit >= 8) out += cjust("Nice:", item_width);
+
+
+				//? Command line
+				for (int i = 0; const auto& l : {'C', 'M', 'D'})
+				out += Mv::to(d_y + 5 + i++, d_x + 1) + l;
+
+				out += Theme::c("main_fg") + Fx::ub;
+				const auto san_cmd = replace_ascii_control(detailed.entry.cmd);
+				const int cmd_size = ulen(san_cmd, true);
+				for (int num_lines = min(3, (int)ceil((double)cmd_size / (d_width - 5))), i = 0; i < num_lines; i++) {
+					out += Mv::to(d_y + 5 + (num_lines == 1 ? 1 : i), d_x + 3)
+						+ cjust(luresize(san_cmd, cmd_size - (d_width - 5) * i, true), d_width - 5, true, true);
+				}
+
+			}
+
+			//? Filter
+			auto filtering = Config::getB("proc_filtering"); // ? filter(20) : Config::getS("proc_filter"))
+			const auto filter_text = (filtering) ? filter(max(6, width - 58)) : uresize(Config::getS("proc_filter"), max(6, width - 58));
+			out += Mv::to(y, x+9) + title_left + (not filter_text.empty() ? Fx::b : "") + Theme::c("hi_fg") + 'f'
+				+ Theme::c("title") + (not filter_text.empty() ? ' ' + filter_text : "ilter")
+				+ (not filtering and not filter_text.empty() ? Theme::c("hi_fg") + " del" : "")
+				+ (filtering ? Theme::c("hi_fg") + ' ' + Symbols::enter : "") + Fx::ub + title_right;
+			if (not filtering) {
+				int f_len = (filter_text.empty() ? 6 : ulen(filter_text) + 2);
+				Input::mouse_mappings["f"] = {y, x + 10, 1, f_len};
+				if (filter_text.empty() and Input::mouse_mappings.contains("delete"))
+					Input::mouse_mappings.erase("delete");
+				else if (not filter_text.empty())
+					Input::mouse_mappings["delete"] = {y, x + 11 + f_len, 1, 3};
+			}
+
+			//? AltData: 移除 per-core, reverse, tree, sorting 按钮
+
+			//? AltData: 移除底部 select/info/terminate/kill/signals/Nice 按钮
+
+			//? Labels for fields in list
+			if (not proc_tree)
+				out += Mv::to(y+1, x+1) + Theme::c("title") + Fx::b
+					+ rjust("time:", 8) + ' '
+					+ ljust("tag:", prog_size, true) + ' '
+					+ (cmd_size > 0 ? "message:" : "");
+			else
+				out += Mv::to(y+1, x+1) + Theme::c("title") + Fx::b
+					+ ljust("Tree:", tree_size) + ' ';
+
+			out += Fx::ub;  // AltData: 移除 User/Mem%/Cpu% 列
+		}
+		//* End of redraw block
+
+		//? Draw details box if shown
+		if (show_detailed) {
+			bool alive = detailed.status != "Dead";
+			const int item_fit = floor((double)(d_width - 2) / 10);
+			const int item_width = floor((double)(d_width - 2) / min(item_fit, 8));
+
+			//? Graph part of box
+			string cpu_str = (alive or pause_proc_list ? fmt::format("{:.2f}", detailed.entry.cpu_p) : "");
+			if (alive or pause_proc_list) {
+				cpu_str.resize(4);
+				if (cpu_str.ends_with('.')) { cpu_str.pop_back(); cpu_str.pop_back(); }
+			}
+			out += Mv::to(d_y + 1, dgraph_x + 1) + Fx::ub + detailed_cpu_graph(detailed.cpu_percent, (redraw or data_same or not alive))
+				+ Mv::to(d_y + 1, dgraph_x + 1) + Theme::c("title") + Fx::b + rjust(cpu_str, 4) + "%";
+			for (int i = 0; const auto& l : {'C', 'P', 'U'})
+					out += Mv::to(d_y + 3 + i++, dgraph_x + 1) + l;
+
+			//? Info part of box
+			const string stat_color = (not alive ? Theme::c("inactive_fg") : (detailed.status == "Running" ? Theme::c("proc_misc") : Theme::c("main_fg")));
+			out += Mv::to(d_y + 2, d_x + 1) + stat_color + Fx::ub
+									+ cjust(detailed.status, item_width) + Theme::c("main_fg")
+									+ cjust(detailed.elapsed, item_width);
+			if (item_fit >= 3) out += cjust(detailed.io_read, item_width);
+			if (item_fit >= 4) out += cjust(detailed.io_write, item_width);
+			if (item_fit >= 5) out += cjust(detailed.parent, item_width, true);
+			if (item_fit >= 6) out += cjust(detailed.entry.user, item_width, true);
+			if (item_fit >= 7) out += cjust(to_string(detailed.entry.threads), item_width);
+			if (item_fit >= 8) out += cjust(to_string(detailed.entry.p_nice), item_width);
+
+
+			const double mem_p = detailed.mem_bytes.back() * 100.0 / totalMem;
+			string mem_str = fmt::format("{:.2f}", mem_p);
+			mem_str.resize(4);
+			if (mem_str.ends_with('.')) mem_str.pop_back();
+			out += 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)
+				+ Theme::c("inactive_fg") + Fx::ub + graph_bg * (d_width / 3) + Mv::l(d_width / 3)
+				+ Theme::c("proc_misc") + detailed_mem_graph(detailed.mem_bytes, (redraw or data_same or not alive)) + ' '
+				+ Theme::c("title") + Fx::b + detailed.memory;
+		}
+
+		//? Check bounds of current selection and view
+		if (start > 0 and numpids <= select_max)
+			start = 0;
+		if (start > numpids - select_max)
+			start = max(0, numpids - select_max);
+		if (selected > select_max)
+			selected = select_max;
+		if (selected > numpids)
+			selected = numpids;
+
+		//* Iteration over processes
+		int lc = 0;
+		for (int n=0; auto& p : plist) {
+			if (p.filtered or (proc_tree and p.tree_index == plist.size()) or n++ < start) continue;
+			bool is_selected = (lc + 1 == selected);
+			if (is_selected) {
+				selected_pid = (int)p.pid;
+				selected_name = p.name;
+				selected_depth = p.depth;
+			}
+
+			//? Update graphs for processes with above 0.0% cpu usage, delete if below 0.1% 10x times
+			bool has_graph = show_graphs ? p_counters.contains(p.pid) : false;
+			if (show_graphs and ((p.cpu_p > 0 and not has_graph) or (not data_same and has_graph))) {
+				if (not has_graph) {
+					p_graphs[p.pid] = Draw::Graph{5, 1, "", {}, graph_symbol};
+					p_counters[p.pid] = 0;
+				}
+				else if (p.cpu_p < 0.1 and ++p_counters[p.pid] >= 10) {
+					if (p_graphs.contains(p.pid)) p_graphs.erase(p.pid);
+					p_counters.erase(p.pid);
+				}
+				else
+					p_counters[p.pid] = 0;
+			}
+
+			out += Fx::reset;
+
+			//? Set correct gradient colors if enabled
+			string c_color, m_color, t_color, g_color, end;
+			if (is_selected) {
+				c_color = m_color = t_color = g_color = Fx::b;
+				end = Fx::ub;
+				out += Theme::c("selected_bg") + Theme::c("selected_fg") + Fx::b;
+			}
+			else {
+				int calc = (selected > lc) ? selected - lc : lc - selected;
+				if (proc_colors) {
+					end = Theme::c("main_fg") + Fx::ub;
+					array<string, 3> colors;
+					for (int i = 0; int v : {(int)round(p.cpu_p), (int)round(p.mem * 100 / totalMem), (int)p.threads / 3}) {
+						if (proc_gradient) {
+							int val = (min(v, 100) + 100) - calc * 100 / select_max;
+							if (val < 100) colors[i++] = Theme::g("proc_color").at(max(0, val));
+							else colors[i++] = Theme::g("process").at(clamp(val - 100, 0, 100));
+						}
+						else
+							colors[i++] = Theme::g("process").at(clamp(v, 0, 100));
+					}
+					c_color = colors.at(0); m_color = colors.at(1); t_color = colors.at(2);
+				}
+				else {
+					c_color = m_color = t_color = Fx::b;
+					end = Fx::ub;
+				}
+				if (proc_gradient) {
+					g_color = Theme::g("proc").at(clamp(calc * 100 / select_max, 0, 100));
+				}
+			}
+
+			const auto san_cmd = replace_ascii_control(p.cmd);
+
+			// AltData: 每次重新计算是否包含宽字符,不缓存
+			const bool is_wide = ulen(san_cmd) != ulen(san_cmd, true);
+
+			//? Normal view line
+			if (not proc_tree) {
+				const bool name_wide = ulen(p.name) != ulen(p.name, true);
+				// AltData: 按重要程度分配颜色
+				string tc = c_color;
+				if (p.name == "链上异动" || p.name == "清算数据") tc = Theme::c("hi_fg");  // 红-最重要
+				else if (p.name == "新闻") tc = Theme::c("title");                         // 白亮-重要
+				else if (p.name == "信号" || p.name == "公告") tc = Theme::c("proc_misc"); // 绿-中等
+				// 舆情/推特/日历/交易 用默认 c_color
+
+				out += Mv::to(y+2+lc, x+1)
+					+ g_color + rjust(p.short_cmd.substr(0,5), 8) + ' '
+					+ tc + ljust(p.name, prog_size, true, name_wide, true) + ' ' + end
+					+ (cmd_size > 0 ? g_color + ljust(san_cmd, cmd_size, true, is_wide, true) : "");
+			}
+			//? Tree view line
+			else {
+				const string prefix_pid = p.prefix + to_string(p.pid);
+				int width_left = tree_size;
+				out += Mv::to(y+2+lc, x+1) + g_color + uresize(prefix_pid, width_left) + ' ';
+				width_left -= ulen(prefix_pid);
+				if (width_left > 0) {
+					out += c_color + uresize(p.name, width_left - 1) + end + ' ';
+					width_left -= (ulen(p.name) + 1);
+				}
+				if (width_left > 7) {
+					const string_view cmd = width_left > 40 ? rtrim(san_cmd) : p.short_cmd;
+					if (not cmd.empty() and cmd != p.name) {
+						out += g_color + '(' + uresize(string{cmd}, width_left - 3, p_wide_cmd[p.pid]) + ") ";
+						width_left -= (ulen(string{cmd}, true) + 3);
+					}
+				}
+				out += string(max(0, width_left), ' ') + Mv::to(y+2+lc, x+2+tree_size);
+			}
+			//? Common end of line
+			string cpu_str = fmt::format("{:.2f}", p.cpu_p);
+			if (p.cpu_p < 10 or (p.cpu_p >= 100 and p.cpu_p < 1000)) cpu_str.resize(3);
+			else if (p.cpu_p >= 10'000) {
+				cpu_str = fmt::format("{:.2f}", p.cpu_p / 1000);
+				cpu_str.resize(3);
+				if (cpu_str.ends_with('.')) cpu_str.pop_back();
+				cpu_str += "k";
+			}
+			string mem_str = (mem_bytes ? floating_humanizer(p.mem, true) : "");
+			if (not mem_bytes) {
+				double mem_p = clamp((double)p.mem * 100 / totalMem, 0.0, 100.0);
+				mem_str = mem_p < 0.01 ? "0" : fmt::format("{:.1f}", mem_p);
+				if (mem_str.size() > 3) mem_str.resize(3);
+				if (mem_str.ends_with('.')) mem_str.pop_back();
+				mem_str += '%';
+			}
+
+			// Shorten process thread representation when larger than 5 digits: 10000 -> 10K ...
+			const std::string proc_threads_string = [&] {
+				if (p.threads > 9999) {
+					return std::to_string(p.threads / 1000) + 'K';
+				} else {
+					return std::to_string(p.threads);
+				}
+			}();
+
+			out += end;  // AltData: 移除 User/Mem%/Cpu% 数据列
+			if (lc++ > height - 5) break;
+			else if (lc > height - 5 and pause_proc_list) break;
+		}
+
+		out += Fx::reset;
+		while (lc++ < height - 3) out += Mv::to(y+lc+1, x+1) + string(width - 2, ' ');
+		if (pause_proc_list) {
+			fmt::format_to(std::back_inserter(out), "{}{}{}{}{:^{}}{}",
+				Mv::to(y + height - 2, x + 1),
+				Theme::c("proc_pause_bg"), Theme::c("title"), 
+				Fx::b, "Process list paused", width - 2,
+				Fx::reset);
+		}
+
+		//? Draw scrollbar if needed
+		if (numpids > select_max) {
+			const int scroll_pos = clamp((int)round((double)start * select_max / (numpids - select_max)), 0, height - 5);
+			out += Mv::to(y + 1, x + width - 2) + Fx::b + Theme::c("main_fg") + Symbols::up
+				+ Mv::to(y + height - 2, x + width - 2) + Symbols::down;
+
+			for (int i = y + 2; i < y + height - 2; i++) {
+				out += Mv::to(i, x + width - 2) + ((i == y + 2 + scroll_pos) ? "█" : " ");
+			}
+		}
+
+		//? Current selection and number of processes
+		string location = to_string(start + selected) + '/' + to_string(numpids);
+		string loc_clear = Symbols::h_line * max((size_t)0, 9 - location.size());
+		out += Mv::to(y + height - 1, x+width - 3 - max(9, (int)location.size())) + Fx::ub + Theme::c("proc_box") + loc_clear
+			+ Symbols::title_left_down + Theme::c("title") + Fx::b + location + Fx::ub + Theme::c("proc_box") + Symbols::title_right_down;
+
+		//? Clear out left over graphs from dead processes at a regular interval
+		if (not data_same and ++counter >= 100) {
+			counter = 0;
+
+			std::erase_if(p_graphs, [&](const auto& pair) {
+				return rng::find(plist, pair.first, &proc_info::pid) == plist.end();
+			});
+
+			std::erase_if(p_counters, [&](const auto& pair) {
+				return rng::find(plist, pair.first, &proc_info::pid) == plist.end();
+			});
+
+			std::erase_if(p_wide_cmd, [&](const auto& pair) {
+				return rng::find(plist, pair.first, &proc_info::pid) == plist.end();
+			});
+		}
+
+		//? Draw hide button if detailed view is shown
+		// AltData: 关闭详细视图入口,取消 enter/hide 按钮
+
+		if (selected == 0 and selected_pid != 0) {
+			selected_pid = 0;
+			selected_name.clear();
+		}
+		redraw = false;
+		return out + Fx::reset;
+	}
+
+}
+
+namespace Draw {
+	void calcSizes() {
+		atomic_wait(Runner::active);
+		Config::unlock();
+		auto boxes = Config::getS("shown_boxes");
+		auto cpu_bottom = Config::getB("cpu_bottom");
+		auto mem_below_net = Config::getB("mem_below_net");
+		auto proc_left = Config::getB("proc_left");
+
+		Cpu::box.clear();
+
+		Mem::box.clear();
+		Net::box.clear();
+		Proc::box.clear();
+		Global::clock.clear();
+		Global::overlay.clear();
+		Runner::pause_output = false;
+		Runner::redraw = true;
+		Proc::p_counters.clear();
+		Proc::p_graphs.clear();
+		if (Menu::active) Menu::redraw = true;
+
+		Input::mouse_mappings.clear();
+
+		Cpu::x = Mem::x = Net::x = Proc::x = 1;
+		Cpu::y = Mem::y = Net::y = Proc::y = 1;
+		Cpu::width = Mem::width = Net::width = Proc::width = 0;
+		Cpu::height = Mem::height = Net::height = Proc::height = 0;
+		Cpu::redraw = Mem::redraw = Net::redraw = Proc::redraw = true;
+
+		Cpu::shown = boxes.contains("cpu");
+	#ifdef GPU_SUPPORT
+		Gpu::box.clear();
+		Gpu::width = 0;
+		Gpu::shown_panels.clear();
+		if (Gpu::count > 0) {
+			std::istringstream iss(boxes, std::istringstream::in);
+			string current;
+			while (iss >> current) {
+				if (current.starts_with("gpu"))
+					Gpu::shown_panels.push_back(current.back()-'0');
+			}
+		}
+		Gpu::shown = Gpu::shown_panels.size();
+
+		// Calculate the minimum possible GPU height, store in total_height
+		// The actual total_height value will of course be overwritten later
+		Gpu::total_height = 0;
+		for (int i = 0; i < Gpu::shown; i++) {
+			using namespace Gpu;
+			total_height += 4 + gpu_b_height_offsets[shown_panels[i]];
+		}
+	#endif
+		Mem::shown = boxes.contains("mem");
+		Net::shown = boxes.contains("net");
+		Proc::shown = boxes.contains("proc");
+
+		//* Calculate and draw cpu box outlines
+		if (Cpu::shown) {
+			using namespace Cpu;
+		#ifdef GPU_SUPPORT
+			// inline GPU information
+			int gpus_extra_height =
+				Config::getS("show_gpu_info") == "On" ? Gpu::count
+				: Config::getS("show_gpu_info") == "Auto" ? Gpu::count - Gpu::shown
+				: 0;
+		#endif
+            const bool show_temp = (Config::getB("check_temp") and got_sensors);
+			width = round((double)Term::width * width_p / 100);
+		#ifdef GPU_SUPPORT
+			if (Gpu::shown != 0 and not (Mem::shown or Net::shown or Proc::shown)) {
+				height = Term::height - Gpu::total_height - gpus_extra_height;
+			} else {
+				height = max(8, (int)ceil((double)Term::height * (trim(boxes) == "cpu" ? 100 : height_p/(Gpu::shown+1) + (Gpu::shown != 0)*5) / 100));
+			}
+			if (height <= Term::height-gpus_extra_height) height += gpus_extra_height;
+		#else
+			height = max(8, (int)ceil((double)Term::height * (trim(boxes) == "cpu" ? 100 : height_p) / 100));
+		#endif
+			x = 1;
+			y = cpu_bottom ? Term::height - height + 1 : 1;
+
+		#ifdef GPU_SUPPORT
+			b_columns = max(2, (int)ceil((double)(Shared::coreCount + 1) / (height - gpus_extra_height - 5)));
+		#else
+			b_columns = max(1, (int)ceil((double)(Shared::coreCount + 1) / (height - 5)));
+		#endif
+			if (b_columns * (21 + 12 * show_temp) < width - (width / 3)) {
+				b_column_size = 2;
+				b_width =  max(29, (21 + 12 * show_temp) * b_columns - (b_columns - 1));
+			}
+			else if (b_columns * (15 + 6 * show_temp) < width - (width / 3)) {
+				b_column_size = 1;
+				b_width = (15 + 6 * show_temp) * b_columns - (b_columns - 1);
+			}
+			else if (b_columns * (8 + 6 * show_temp) < width - (width / 3)) {
+				b_column_size = 0;
+			}
+			else {
+				b_columns = (width - width / 3) / (8 + 6 * show_temp);
+				b_column_size = 0;
+			}
+
+			if (b_column_size == 0) b_width = (8 + 6 * show_temp) * b_columns + 1;
+		#ifdef GPU_SUPPORT
+			//gpus_extra_height = max(0, gpus_extra_height - 1);
+			b_height = min(height - 2, (int)ceil((double)Shared::coreCount / b_columns) + 4 + gpus_extra_height);
+		#else
+			b_height = min(height - 2, (int)ceil((double)Shared::coreCount / b_columns) + 4);
+		#endif
+
+			b_x = x + width - b_width - 1;
+			b_y = y + ceil((double)(height - 2) / 2) - ceil((double)b_height / 2) + 1;
+
+			box = createBox(x, y, width, height, Theme::c("cpu_box"), true, (cpu_bottom ? "" : "cpu"), (cpu_bottom ? "cpu" : ""), 1);
+
+			auto& custom = Config::getS("custom_cpu_name");
+			static const bool hasCpuHz = not Cpu::get_cpuHz().empty();
+		#ifdef __linux__
+			static const bool freq_range = Config::getS("freq_mode") == "range";
+		#else
+			static const bool freq_range = false;
+		#endif
+			const string cpu_title = uresize(
+					(custom.empty() ? Cpu::cpuName : custom),
+					b_width - (Config::getB("show_cpu_freq") and hasCpuHz ? (freq_range ? 24 : 14) : 5)
+			);
+			box += createBox(b_x, b_y, b_width, b_height, "", false, cpu_title);
+		}
+
+	#ifdef GPU_SUPPORT
+		//* Calculate and draw gpu box outlines
+		if (Gpu::shown != 0) {
+			using namespace Gpu;
+			x_vec.resize(shown); y_vec.resize(shown);
+			b_x_vec.resize(shown); b_y_vec.resize(shown);
+			b_height_vec.resize(shown);
+			box.resize(shown);
+			graph_upper_vec.resize(shown); graph_lower_vec.resize(shown);
+			temp_graph_vec.resize(shown);
+			mem_used_graph_vec.resize(shown); mem_util_graph_vec.resize(shown);
+			gpu_meter_vec.resize(shown);
+			pwr_meter_vec.resize(shown);
+			enc_meter_vec.resize(shown);
+			redraw.resize(shown);
+			total_height = 0;
+			for (auto i = 0; i < shown; ++i) {
+				redraw[i] = true;
+				int height = 0;
+				width = Term::width;
+				if (Cpu::shown)
+					if (not (Mem::shown or Net::shown or Proc::shown))
+						height = min_height;
+					else height = Cpu::height;
+				else
+					if (not (Mem::shown or Net::shown or Proc::shown))
+						height = (Term::height - total_height) / (Gpu::shown - i) + (i == 0) * ((Term::height - total_height) % (Gpu::shown - i));
+					else
+						height = max(min_height, (int)ceil((double)Term::height * height_p/Gpu::shown / 100));
+
+				b_height_vec[i] = gpu_b_height_offsets[shown_panels[i]] + 2;
+				height += (height+Cpu::height == Term::height-1);
+				height = max(height, b_height_vec[i] + 2);
+				x_vec[i] = 1; y_vec[i] = 1 + total_height + (not Config::getB("cpu_bottom"))*Cpu::shown*Cpu::height;
+				box[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
+				b_width = clamp(width/2, min_width, 65);
+				total_height += height;
+
+				//? Main statistics box
+				b_x_vec[i] = x_vec[i] + width - b_width - 1;
+				b_y_vec[i] = y_vec[i] + ceil((double)(height - 2 - b_height_vec[i]) / 2) + 1;
+
+				string name = Config::getS(std::string("custom_gpu_name") + (char)(shown_panels[i]+'0'));
+				if (name.empty()) name = gpu_names[shown_panels[i]];
+
+				box[i] += createBox(b_x_vec[i], b_y_vec[i], b_width, b_height_vec[i], "", false, name.substr(0, b_width-5));
+				b_height_vec[i] = height - 2;
+			}
+		}
+	#endif
+
+		//* Calculate and draw mem box outlines
+		if (Mem::shown) {
+			using namespace Mem;
+			auto show_disks = Config::getB("show_disks");
+			auto swap_disk = Config::getB("swap_disk");
+			auto mem_graphs = Config::getB("mem_graphs");
+
+			width = round((double)Term::width * (Proc::shown ? width_p : 100) / 100);
+		#ifdef GPU_SUPPORT
+			height = ceil((double)Term::height * (100 - Net::height_p * Net::shown*4 / ((Gpu::shown != 0 and Cpu::shown) + 4)) / 100) - Cpu::height - Gpu::total_height;
+		#else
+			height = ceil((double)Term::height * (100 - Cpu::height_p * Cpu::shown - Net::height_p * Net::shown) / 100) + 1;
+		#endif
+			x = (proc_left and Proc::shown) ? Term::width - width + 1: 1;
+			if (mem_below_net and Net::shown)
+		#ifdef GPU_SUPPORT
+				y = Term::height - height + 1 - (cpu_bottom ? Cpu::height : 0);
+			else
+				y = (cpu_bottom ? 1 : Cpu::height + 1) + Gpu::total_height;
+		#else
+				y = Term::height - height + 1 - (cpu_bottom ? Cpu::height : 0);
+			else
+				y = cpu_bottom ? 1 : Cpu::height + 1;
+		#endif
+
+			if (show_disks) {
+				mem_width = ceil((double)(width - 3) / 2);
+				mem_width += mem_width % 2;
+				disks_width = width - mem_width - 2;
+				divider = x + mem_width;
+			}
+			else
+				mem_width = width - 1;
+
+			item_height = has_swap and not swap_disk ? 6 : 4;
+			if (height - (has_swap and not swap_disk ? 3 : 2) > 2 * item_height)
+				mem_size = 3;
+			else if (mem_width > 25)
+				mem_size = 2;
+			else
+				mem_size = 1;
+
+			mem_meter = max(0, mem_width - (mem_size > 2 ? 7 : 17));
+			if (mem_size == 1) mem_meter += 6;
+
+			if (mem_graphs) {
+				graph_height = max(1, (int)round((double)((height - (has_swap and not swap_disk ? 2 : 1)) - (mem_size == 3 ? 2 : 1) * item_height) / item_height));
+				if (graph_height > 1) mem_meter += 6;
+			}
+			else
+				graph_height = 0;
+
+			if (show_disks) {
+				disk_meter = max(-14, width - mem_width - 23);
+				if (disks_width < 25) disk_meter += 14;
+			}
+
+			box = createBox(x, y, width, height, Theme::c("mem_box"), true, "mem", "", 2);
+			box += Mv::to(y, (show_disks ? divider + 2 : x + width - 9)) + Theme::c("mem_box") + Symbols::title_left + (show_disks ? Fx::b : "")
+				+ Theme::c("hi_fg") + 'd' + Theme::c("title") + "isks" + Fx::ub + Theme::c("mem_box") + Symbols::title_right;
+			Input::mouse_mappings["d"] = {y, (show_disks ? divider + 3 : x + width - 8), 1, 5};
+			if (show_disks) {
+				box += Mv::to(y, divider) + Symbols::div_up + Mv::to(y + height - 1, divider) + Symbols::div_down + Theme::c("div_line");
+				for (auto i : iota(1, height - 1))
+					box += Mv::to(y + i, divider) + Symbols::v_line;
+			}
+		}
+
+		//* Calculate and draw net box outlines
+		if (Net::shown) {
+			using namespace Net;
+			width = round((double)Term::width * (Proc::shown ? width_p : 100) / 100);
+		#ifdef GPU_SUPPORT
+			height = Term::height - Cpu::height - Gpu::total_height - Mem::height;
+		#else
+			height = Term::height - Cpu::height - Mem::height;
+		#endif
+			x = (proc_left and Proc::shown) ? Term::width - width + 1 : 1;
+			if (mem_below_net and Mem::shown)
+			#ifdef GPU_SUPPORT
+				y = (cpu_bottom ? 1 : Cpu::height + 1) + Gpu::total_height;
+			#else
+				y = cpu_bottom ? 1 : Cpu::height + 1;
+			#endif
+			else
+				y = Term::height - height + 1 - (cpu_bottom ? Cpu::height : 0);
+
+			b_width = (width > 45) ? 27 : 19;
+			b_height = (height > 10) ? 9 : height - 2;
+			b_x = x + width - b_width - 1;
+			b_y = y + ((height - 2) / 2) - b_height / 2 + 1;
+			d_graph_height = round((double)(height - 2) / 2);
+			u_graph_height = height - 2 - d_graph_height;
+
+			box = createBox(x, y, width, height, Theme::c("net_box"), true, "net", "", 3);
+			box += createBox(b_x, b_y, b_width, b_height, "", false, "download", "upload");
+		}
+
+		//* Calculate and draw proc box outlines
+		if (Proc::shown) {
+			using namespace Proc;
+			width = Term::width - (Mem::shown ? Mem::width : (Net::shown ? Net::width : 0));
+		#ifdef GPU_SUPPORT
+			height = Term::height - Cpu::height - Gpu::total_height;
+		#else
+			height = Term::height - Cpu::height;
+		#endif
+			x = proc_left ? 1 : Term::width - width + 1;
+		#ifdef GPU_SUPPORT
+			y = ((cpu_bottom and Cpu::shown) ? 1 : Cpu::height + 1) + Gpu::total_height;
+		#else
+			y = (cpu_bottom and Cpu::shown) ? 1 : Cpu::height + 1;
+		#endif
+			select_max = height - 3;
+			box = createBox(x, y, width, height, Theme::c("proc_box"), true, "proc", "", 4);
+		}
+	}
+}

+ 141 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_draw.hpp

@@ -0,0 +1,141 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#pragma once
+
+#include <array>
+#include <deque>
+#include <string>
+#include <string_view>
+#include <unordered_map>
+#include <vector>
+
+using std::array;
+using std::deque;
+using std::string;
+using std::vector;
+
+namespace Symbols {
+	const string h_line				= "─";
+	const string v_line				= "│";
+	const string dotted_v_line		= "╎";
+	const string left_up			= "┌";
+	const string right_up			= "┐";
+	const string left_down			= "└";
+	const string right_down			= "┘";
+	const string round_left_up		= "╭";
+	const string round_right_up		= "╮";
+	const string round_left_down	= "╰";
+	const string round_right_down	= "╯";
+	const string title_left_down	= "┘";
+	const string title_right_down	= "└";
+	const string title_left			= "┐";
+	const string title_right		= "┌";
+	const string div_right			= "┤";
+	const string div_left			= "├";
+	const string div_up				= "┬";
+	const string div_down			= "┴";
+
+
+	const string up = "↑";
+	const string down = "↓";
+	const string left = "←";
+	const string right = "→";
+	const string enter = "↵";
+}
+
+namespace Draw {
+
+	//* Generate if needed and return the btop++ banner
+	string banner_gen(int y=0, int x=0, bool centered=false, bool redraw=false);
+
+	//* An editable text field
+	class TextEdit {
+		size_t pos{};
+		size_t upos{};
+		bool numeric = false;
+	public:
+		string text;
+		TextEdit();
+		explicit TextEdit(string text, bool numeric=false);
+		bool command(const std::string_view key);
+		string operator()(const size_t limit=0);
+		void clear();
+	};
+
+	//* Create a box and return as a string
+	string createBox(
+			const int x, const int y, const int width, const int height, string line_color = "", bool fill = false,
+			const std::string_view title = "", const std::string_view title2 = "", const int num = 0
+	);
+
+	bool update_clock(bool force = false);
+
+	//* Class holding a percentage meter
+	class Meter {
+		int width;
+		string color_gradient;
+		bool invert;
+		array<string, 101> cache;
+	public:
+		Meter();
+		Meter(const int width, string color_gradient, bool invert = false);
+
+		//* Return a string representation of the meter with given value
+		string operator()(int value);
+	};
+
+	//* Class holding a percentage graph
+	class Graph {
+		int width, height;
+		string color_gradient;
+		string out, symbol = "default";
+		bool invert, no_zero;
+		long long offset;
+		long long last = 0, max_value = 0;
+		bool current = true, tty_mode = false;
+		std::unordered_map<bool, vector<string>> graphs = { {true, {}}, {false, {}}};
+
+		//* Create two representations of the graph to switch between to represent two values for each braille character
+		void _create(const deque<long long>& data, int data_offset);
+
+	public:
+		Graph();
+		Graph(int width, int height,
+			const string& color_gradient,
+			const deque<long long>& data,
+			const string& symbol="default",
+			bool invert=false, bool no_zero=false,
+			long long max_value=0, long long offset=0);
+
+		//* Add last value from back of <data> and return string representation of graph
+		string& operator()(const deque<long long>& data, bool data_same=false);
+
+		//* Return string representation of graph
+		string& operator()();
+	};
+
+	//* Calculate sizes of boxes, draw outlines and save to enabled boxes namespaces
+	void calcSizes();
+}
+
+namespace Proc {
+	extern Draw::TextEdit filter;
+	extern std::unordered_map<size_t, Draw::Graph> p_graphs;
+	extern std::unordered_map<size_t, int> p_counters;
+}

+ 542 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_input.cpp

@@ -0,0 +1,542 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#include <limits>
+#include <ranges>
+#include <vector>
+#include <thread>
+#include <mutex>
+#include <fmt/format.h>
+#include <signal.h>
+#include <sys/select.h>
+#include <utility>
+
+#include "btop_input.hpp"
+#include "btop_tools.hpp"
+#include "btop_config.hpp"
+#include "btop_shared.hpp"
+#include "btop_menu.hpp"
+#include "btop_draw.hpp"
+
+using namespace Tools;
+using namespace std::literals; // for operator""s
+namespace rng = std::ranges;
+
+namespace Input {
+
+	//* Map for translating key codes to readable values
+	const std::unordered_map<string, string> Key_escapes = {
+		{"\033",	"escape"},
+		{"\x12",	"ctrl_r"},
+		{"\n",		"enter"},
+		{" ",		"space"},
+		{"\x7f",	"backspace"},
+		{"\x08",	"backspace"},
+		{"[A", 		"up"},
+		{"OA",		"up"},
+		{"[B", 		"down"},
+		{"OB",		"down"},
+		{"[D", 		"left"},
+		{"OD",		"left"},
+		{"[C", 		"right"},
+		{"OC",		"right"},
+		{"[2~",		"insert"},
+		{"[4h",		"insert"},
+		{"[3~",		"delete"},
+		{"[P",		"delete"},
+		{"[H",		"home"},
+		{"[1~",		"home"},
+		{"[F",		"end"},
+		{"[4~",		"end"},
+		{"[5~",		"page_up"},
+		{"[6~",		"page_down"},
+		{"\t",		"tab"},
+		{"[Z",		"shift_tab"},
+		{"OP",		"f1"},
+		{"OQ",		"f2"},
+		{"OR",		"f3"},
+		{"OS",		"f4"},
+		{"[15~",	"f5"},
+		{"[17~",	"f6"},
+		{"[18~",	"f7"},
+		{"[19~",	"f8"},
+		{"[20~",	"f9"},
+		{"[21~",	"f10"},
+		{"[23~",	"f11"},
+		{"[24~",	"f12"}
+	};
+
+	sigset_t signal_mask;
+	std::atomic<bool> polling (false);
+	array<int, 2> mouse_pos;
+	std::unordered_map<string, Mouse_loc> mouse_mappings;
+
+	deque<string> history(50, "");
+	string old_filter;
+	string input;
+
+	bool poll(const uint64_t timeout) {
+		atomic_lock lck(polling);
+		fd_set fds;
+		FD_ZERO(&fds);
+		FD_SET(STDIN_FILENO, &fds);
+		struct timespec wait;
+		struct timespec *waitptr = nullptr;
+
+		if(timeout != std::numeric_limits<uint64_t>::max()) {
+			wait.tv_sec = timeout / 1000;
+			wait.tv_nsec = (timeout % 1000) * 1000000;
+			waitptr = &wait;
+		}
+
+		if(pselect(STDIN_FILENO + 1, &fds, nullptr, nullptr, waitptr, &signal_mask) > 0) {
+			input.clear();
+			char buf[1024];
+			ssize_t count = 0;
+			while((count = read(STDIN_FILENO, buf, sizeof(buf))) > 0) {
+				input.append(std::string_view(buf, count));
+			}
+
+			return true;
+		}
+
+		return false;
+	}
+
+	string get() {
+		string key = input;
+		if (not key.empty()) {
+			//? Remove escape code prefix if present
+			if (key.length() > 1 and key.at(0) == Fx::e.at(0)) {
+				key.erase(0, 1);
+			}
+			//? Detect if input is an mouse event
+			if (key.starts_with("[<")) {
+				std::string_view key_view = key;
+				string mouse_event;
+				if (key_view.starts_with("[<0;") and key_view.find('M') != std::string_view::npos) {
+					mouse_event = "mouse_click";
+					key_view.remove_prefix(4);
+				}
+				// else if (key_view.starts_with("[<0;") and key_view.ends_with('m')) {
+				// 	mouse_event = "mouse_release";
+				// 	key_view.remove_prefix(4);
+				// }
+				else if (key_view.starts_with("[<64;")) {
+					mouse_event = "mouse_scroll_up";
+					key_view.remove_prefix(5);
+				}
+				else if (key_view.starts_with("[<65;")) {
+					mouse_event = "mouse_scroll_down";
+					key_view.remove_prefix(5);
+				}
+				else
+					key.clear();
+
+				if (Config::getB("proc_filtering")) {
+					if (mouse_event == "mouse_click") return mouse_event;
+					else return "";
+				}
+
+				//? Get column and line position of mouse and check for any actions mapped to current position
+				if (not key.empty()) {
+					try {
+						const auto delim = key_view.find(';');
+						mouse_pos[0] = stoi((string)key_view.substr(0, delim));
+						mouse_pos[1] = stoi((string)key_view.substr(delim + 1, key_view.find('M', delim)));
+					}
+					catch (const std::invalid_argument&) { mouse_event.clear(); }
+					catch (const std::out_of_range&) { mouse_event.clear(); }
+
+					key = mouse_event;
+
+					if (key == "mouse_click") {
+						const auto& [col, line] = mouse_pos;
+
+						for (const auto& [mapped_key, pos] : (Menu::active ? Menu::mouse_mappings : mouse_mappings)) {
+							if (col >= pos.col and col < pos.col + pos.width and line >= pos.line and line < pos.line + pos.height) {
+								key = mapped_key;
+								break;
+							}
+						}
+					}
+				}
+
+			}
+			else if (auto it = Key_escapes.find(key); it != Key_escapes.end())
+				key = it->second;
+			else if (ulen(key) > 1)
+				key.clear();
+
+			if (not key.empty()) {
+				history.push_back(key);
+				history.pop_front();
+			}
+		}
+		return key;
+	}
+
+	string wait() {
+		while(not poll(std::numeric_limits<uint64_t>::max())) {}
+		return get();
+	}
+
+	void interrupt() {
+		kill(getpid(), SIGUSR1);
+	}
+
+	void clear() {
+		// do not need it, actually
+	}
+
+	void process(const std::string_view key) {
+		if (key.empty()) return;
+		try {
+			auto filtering = Config::getB("proc_filtering");
+			auto vim_keys = Config::getB("vim_keys");
+			auto help_key = (vim_keys ? "H" : "h");
+			auto kill_key = (vim_keys ? "K" : "k");
+			//? Global input actions
+			if (not filtering) {
+				bool keep_going = false;
+				if (key == "q") {
+					clean_quit(0);
+				}
+				else if (is_in(key, "escape", "m")) {
+					Menu::show(Menu::Menus::Main);
+					return;
+				}
+				else if (is_in(key, "f1", "?", help_key)) {
+					Menu::show(Menu::Menus::Help);
+					return;
+				}
+				else if (is_in(key, "f2", "o")) {
+					Menu::show(Menu::Menus::Options);
+					return;
+				}
+				else if (key.size() == 1 and isint(key)) {
+					auto intKey = std::atoi(key.data());
+					// AltData: 1=net, 2=proc,其他屏蔽
+					if (intKey != 1 and intKey != 2)
+						return;
+					// 映射: 1->net(3), 2->proc(4)
+					static const array<string, 3> altBoxes = {"", "net", "proc"};
+					atomic_wait(Runner::active);
+
+					if (not Config::toggle_box(altBoxes.at(intKey))) {
+						Menu::show(Menu::Menus::SizeError);
+						return;
+					}
+					Config::current_preset = -1;
+					Draw::calcSizes();
+					Runner::run("all", false, true);
+					return;
+				}
+				else if (is_in(key, "p", "P") and Config::preset_list.size() > 1) {
+					const auto old_preset = Config::current_preset;
+					if (key == "p") {
+						if (++Config::current_preset >= (int)Config::preset_list.size()) Config::current_preset = 0;
+					}
+					else {
+						if (--Config::current_preset < 0) Config::current_preset = Config::preset_list.size() - 1;
+					}
+					atomic_wait(Runner::active);
+					if (not Config::apply_preset(Config::preset_list.at(Config::current_preset))) {
+						Menu::show(Menu::Menus::SizeError);
+						Config::current_preset = old_preset;
+						return;
+					}
+					Draw::calcSizes();
+					Runner::run("all", false, true);
+					return;
+				} else if (is_in(key, "ctrl_r")) {
+					kill(getpid(), SIGUSR2);
+					return;
+				} else
+					keep_going = true;
+
+				if (not keep_going) return;
+			}
+
+			//? Input actions for proc box
+			if (Proc::shown) {
+				bool keep_going = false;
+				bool no_update = true;
+				bool redraw = true;
+				if (filtering) {
+					if (key == "enter" or key == "down") {
+						Config::set("proc_filter", Proc::filter.text);
+						Config::set("proc_filtering", false);
+						old_filter.clear();
+						if(key == "down"){
+							Config::unlock();
+							Config::lock();
+							process("down");
+							return;
+						}
+					}
+					else if (key == "escape" or key == "mouse_click") {
+						Config::set("proc_filter", old_filter);
+						Config::set("proc_filtering", false);
+						old_filter.clear();
+					}
+					else if (Proc::filter.command(key)) {
+						if (Config::getS("proc_filter") != Proc::filter.text)
+							Config::set("proc_filter", Proc::filter.text);
+					}
+					else
+						return;
+				}
+				else if (key == "left" or (vim_keys and key == "h")) {
+					int cur_i = v_index(Proc::sort_vector, Config::getS("proc_sorting"));
+					if (--cur_i < 0)
+						cur_i = Proc::sort_vector.size() - 1;
+					Config::set("proc_sorting", Proc::sort_vector.at(cur_i));
+				}
+				else if (key == "right" or (vim_keys and key == "l")) {
+					int cur_i = v_index(Proc::sort_vector, Config::getS("proc_sorting"));
+					if (std::cmp_greater(++cur_i, Proc::sort_vector.size() - 1))
+						cur_i = 0;
+					Config::set("proc_sorting", Proc::sort_vector.at(cur_i));
+				}
+				else if (is_in(key, "f", "/")) {
+					Config::flip("proc_filtering");
+					Proc::filter = Draw::TextEdit{Config::getS("proc_filter")};
+					old_filter = Proc::filter.text;
+				}
+				else if (key == "e") {
+					Config::flip("proc_tree");
+					no_update = false;
+				}
+				else if (is_in(key, "F")) {
+					Config::flip("pause_proc_list");
+					redraw = true;
+				}
+				else if (key == "r")
+					Config::flip("proc_reversed");
+
+				else if (key == "c")
+					Config::flip("proc_per_core");
+
+				else if (key == "%")
+					Config::flip("proc_mem_bytes");
+
+				else if (key == "delete" and not Config::getS("proc_filter").empty())
+					Config::set("proc_filter", ""s);
+
+				else if (key.starts_with("mouse_")) {
+					redraw = false;
+					const auto& [col, line] = mouse_pos;
+					const int y = (Config::getB("show_detailed") ? Proc::y + 8 : Proc::y);
+					const int height = (Config::getB("show_detailed") ? Proc::height - 8 : Proc::height);
+					if (col >= Proc::x + 1 and col < Proc::x + Proc::width and line >= y + 1 and line < y + height - 1) {
+						if (key == "mouse_click") {
+							if (col < Proc::x + Proc::width - 2) {
+								const auto& current_selection = Config::getI("proc_selected");
+								if (current_selection == line - y - 1) {
+									redraw = true;
+									if (Config::getB("proc_tree")) {
+										const int x_pos = col - Proc::x;
+										const int offset = Config::getI("selected_depth") * 3;
+										if (x_pos > offset and x_pos < 4 + offset) {
+											process("space");
+											return;
+										}
+									}
+									// AltData: disable enter-triggered detail toggle
+									return;
+								}
+								else if (current_selection == 0 or line - y - 1 == 0)
+									redraw = true;
+								Config::set("proc_selected", line - y - 1);
+							}
+							else if (line == y + 1) {
+								if (Proc::selection("page_up") == -1) return;
+							}
+							else if (line == y + height - 2) {
+								if (Proc::selection("page_down") == -1) return;
+							}
+							else if (Proc::selection("mousey" + to_string(line - y - 2)) == -1)
+								return;
+						}
+						else
+							goto proc_mouse_scroll;
+					}
+					else if (key == "mouse_click" and Config::getI("proc_selected") > 0) {
+						Config::set("proc_selected", 0);
+						redraw = true;
+					}
+					else
+						keep_going = true;
+				}
+				else if (key == "enter") {
+					// AltData: disable enter-triggered detail toggle
+					return;
+				}
+				else if (is_in(key, "+", "-", "space", "u") and Config::getB("proc_tree") and Config::getI("proc_selected") > 0) {
+					atomic_wait(Runner::active);
+					auto& pid = Config::getI("selected_pid");
+					if (key == "+" or key == "space") Proc::expand = pid;
+					if (key == "-" or key == "space") Proc::collapse = pid;
+					if (key == "u")	Proc::toggle_children = pid;
+					no_update = false;
+				}
+				else if (is_in(key, "t", kill_key) and (Config::getB("show_detailed") or Config::getI("selected_pid") > 0)) {
+					atomic_wait(Runner::active);
+					if (Config::getB("show_detailed") and Config::getI("proc_selected") == 0 and Proc::detailed.status == "Dead") return;
+					Menu::show(Menu::Menus::SignalSend, (key == "t" ? SIGTERM : SIGKILL));
+					return;
+				}
+				else if (key == "s" and (Config::getB("show_detailed") or Config::getI("selected_pid") > 0)) {
+					atomic_wait(Runner::active);
+					if (Config::getB("show_detailed") and Config::getI("proc_selected") == 0 and Proc::detailed.status == "Dead") return;
+					Menu::show(Menu::Menus::SignalChoose);
+					return;
+				}
+			    else if (key == "N" and (Config::getB("show_detailed") or Config::getI("selected_pid") > 0)) {
+					atomic_wait(Runner::active);
+				    if (Config::getB("show_detailed") and Config::getI("proc_selected") == 0 and Proc::detailed.status == "Dead") return;
+				    Menu::show(Menu::Menus::Renice);
+				    return;
+			    }
+				else if (is_in(key, "up", "down", "page_up", "page_down", "home", "end") or (vim_keys and is_in(key, "j", "k", "g", "G"))) {
+					proc_mouse_scroll:
+					redraw = false;
+					auto old_selected = Config::getI("proc_selected");
+					auto new_selected = Proc::selection(key);
+					if (new_selected == -1)
+						return;
+					else if (old_selected != new_selected and (old_selected == 0 or new_selected == 0))
+						redraw = true;
+				}
+				else keep_going = true;
+
+				if (not keep_going) {
+					Runner::run("proc", no_update, redraw);
+					return;
+				}
+			}
+
+			//? Input actions for cpu box
+			if (Cpu::shown) {
+				bool keep_going = false;
+				bool no_update = true;
+				bool redraw = true;
+				static uint64_t last_press = 0;
+
+				if (key == "+" and Config::getI("update_ms") <= 86399900) {
+					int add = (Config::getI("update_ms") <= 86399000 and last_press >= time_ms() - 200
+						and rng::all_of(Input::history, [](const auto& str){ return str == "+"; })
+						? 1000 : 100);
+					Config::set("update_ms", Config::getI("update_ms") + add);
+					last_press = time_ms();
+					redraw = true;
+				}
+				else if (key == "-" and Config::getI("update_ms") >= 200) {
+					int sub = (Config::getI("update_ms") >= 2000 and last_press >= time_ms() - 200
+						and rng::all_of(Input::history, [](const auto& str){ return str == "-"; })
+						? 1000 : 100);
+					Config::set("update_ms", Config::getI("update_ms") - sub);
+					last_press = time_ms();
+					redraw = true;
+				}
+				else keep_going = true;
+
+				if (not keep_going) {
+					Runner::run("cpu", no_update, redraw);
+					return;
+				}
+			}
+
+			//? Input actions for mem box
+			if (Mem::shown) {
+				bool keep_going = false;
+				bool no_update = true;
+				bool redraw = true;
+
+				if (key == "i") {
+					Config::flip("io_mode");
+				}
+				else if (key == "d") {
+					Config::flip("show_disks");
+					no_update = false;
+					Draw::calcSizes();
+				}
+				else keep_going = true;
+
+				if (not keep_going) {
+					Runner::run("mem", no_update, redraw);
+					return;
+				}
+			}
+
+			//? Input actions for net box
+			if (Net::shown) {
+				bool keep_going = false;
+				bool no_update = true;
+				bool redraw = true;
+
+				if (is_in(key, "b", "n")) {
+					atomic_wait(Runner::active);
+					int c_index = v_index(Net::interfaces, Net::selected_iface);
+					if (c_index != (int)Net::interfaces.size()) {
+						if (key == "b") {
+							if (--c_index < 0) c_index = Net::interfaces.size() - 1;
+						}
+						else if (key == "n") {
+							if (++c_index == (int)Net::interfaces.size()) c_index = 0;
+						}
+						Net::selected_iface = Net::interfaces.at(c_index);
+						Net::rescale = true;
+					}
+				}
+				else if (key == "y") {
+					Config::flip("net_sync");
+					Net::rescale = true;
+				}
+				else if (key == "a") {
+					Config::flip("net_auto");
+					Net::rescale = true;
+				}
+				else if (key == "z") {
+					atomic_wait(Runner::active);
+					auto& ndev = Net::current_net.at(Net::selected_iface);
+					if (ndev.stat.at("download").offset + ndev.stat.at("upload").offset > 0) {
+						ndev.stat.at("download").offset = 0;
+						ndev.stat.at("upload").offset = 0;
+					}
+					else {
+						ndev.stat.at("download").offset = ndev.stat.at("download").last + ndev.stat.at("download").rollover;
+						ndev.stat.at("upload").offset = ndev.stat.at("upload").last + ndev.stat.at("upload").rollover;
+					}
+					no_update = false;
+				}
+				else keep_going = true;
+
+				if (not keep_going) {
+					Runner::run("net", no_update, redraw);
+					return;
+				}
+			}
+		}
+
+		catch (const std::exception& e) {
+			throw std::runtime_error { fmt::format(R"(Input::process("{}"))", e.what()) };
+		}
+	}
+}

+ 78 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_input.hpp

@@ -0,0 +1,78 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#pragma once
+
+#include <array>
+#include <atomic>
+#include <deque>
+#include <string>
+#include <string_view>
+#include <unordered_map>
+
+using std::array;
+using std::atomic;
+using std::deque;
+using std::string;
+
+/* The input functions rely on the following termios parameters being set:
+	Non-canonical mode (c_lflags & ~(ICANON))
+	VMIN and VTIME (c_cc) set to 0
+	These will automatically be set when running Term::init() from btop_tools.cpp
+*/
+
+//* Functions and variables for handling keyboard and mouse input
+namespace Input {
+
+	struct Mouse_loc {
+		int line, col, height, width;
+	};
+
+	//? line, col, height, width
+	extern std::unordered_map<string, Mouse_loc> mouse_mappings;
+
+	//* Signal mask used during polling read
+	extern sigset_t signal_mask;
+
+	extern atomic<bool> polling;
+
+	//* Mouse column and line position
+	extern array<int, 2> mouse_pos;
+
+	//* Last entered key
+	extern deque<string> history;
+
+	//* Poll keyboard & mouse input for <timeout> ms and return input availability as a bool
+	bool poll(const uint64_t timeout=0);
+
+	//* Get a key or mouse action from input
+	string get();
+
+	//* Wait until input is available and return key
+	string wait();
+
+	//* Interrupt poll/wait
+	void interrupt();
+
+	//* Clears last entered key
+	void clear();
+
+	//* Process actions for input <key>
+	void process(const std::string_view key);
+
+}

+ 1800 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_menu.cpp

@@ -0,0 +1,1800 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#include "btop_menu.hpp"
+
+#include "btop_config.hpp"
+#include "btop_draw.hpp"
+#include "btop_shared.hpp"
+#include "btop_theme.hpp"
+#include "btop_tools.hpp"
+
+#include <errno.h>
+#include <signal.h>
+
+#include <array>
+#include <cmath>
+#include <filesystem>
+#include <unordered_map>
+#include <utility>
+
+using std::array;
+using std::ceil;
+using std::max;
+using std::min;
+using std::ref;
+using std::views::iota;
+
+using namespace Tools;
+
+namespace fs = std::filesystem;
+
+namespace Menu {
+
+   atomic<bool> active (false);
+   string bg;
+   bool redraw{true};
+   int currentMenu = -1;
+   msgBox messageBox;
+   int signalToSend{};
+   int signalKillRet{};
+
+   const array<string, 32> P_Signals = {
+	   "0",
+#ifdef __linux__
+#if defined(__hppa__)
+		"SIGHUP", "SIGINT", "SIGQUIT", "SIGILL",
+		"SIGTRAP", "SIGABRT", "SIGSTKFLT", "SIGFPE",
+		"SIGKILL", "SIGBUS", "SIGSEGV", "SIGXCPU",
+		"SIGPIPE", "SIGALRM", "SIGTERM", "SIGUSR1",
+		"SIGUSR2", "SIGCHLD", "SIGPWR", "SIGVTALRM",
+		"SIGPROF", "SIGIO", "SIGWINCH", "SIGSTOP",
+		"SIGTSTP", "SIGCONT", "SIGTTIN", "SIGTTOU",
+		"SIGURG", "SIGXFSZ", "SIGSYS"
+#elif defined(__mips__)
+		"SIGHUP", "SIGINT", "SIGQUIT", "SIGILL",
+		"SIGTRAP", "SIGABRT", "SIGEMT", "SIGFPE",
+		"SIGKILL", "SIGBUS", "SIGSEGV", "SIGSYS",
+		"SIGPIPE", "SIGALRM", "SIGTERM", "SIGUSR1",
+		"SIGUSR2", "SIGCHLD", "SIGPWR", "SIGWINCH",
+		"SIGURG", "SIGIO", "SIGSTOP", "SIGTSTP",
+		"SIGCONT", "SIGTTIN", "SIGTTOU", "SIGVTALRM",
+		"SIGPROF", "SIGXCPU", "SIGXFSZ"
+#elif defined(__alpha__)
+		"SIGHUP", "SIGINT", "SIGQUIT", "SIGILL",
+		"SIGTRAP", "SIGABRT", "SIGEMT", "SIGFPE",
+		"SIGKILL", "SIGBUS", "SIGSEGV", "SIGSYS",
+		"SIGPIPE", "SIGALRM", "SIGTERM", "SIGURG",
+		"SIGSTOP", "SIGTSTP", "SIGCONT", "SIGCHLD",
+		"SIGTTIN", "SIGTTOU", "SIGIO", "SIGXCPU",
+		"SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH",
+		"SIGPWR", "SIGUSR1", "SIGUSR2"
+#elif defined (__sparc__)
+		"SIGHUP", "SIGINT", "SIGQUIT", "SIGILL",
+		"SIGTRAP", "SIGABRT", "SIGEMT", "SIGFPE",
+		"SIGKILL", "SIGBUS", "SIGSEGV", "SIGSYS",
+		"SIGPIPE", "SIGALRM", "SIGTERM", "SIGURG",
+		"SIGSTOP", "SIGTSTP", "SIGCONT", "SIGCHLD",
+		"SIGTTIN", "SIGTTOU", "SIGIO", "SIGXCPU",
+		"SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH",
+		"SIGLOST", "SIGUSR1", "SIGUSR2"
+#else
+		"SIGHUP", "SIGINT",	"SIGQUIT",	"SIGILL",
+		"SIGTRAP", "SIGABRT", "SIGBUS", "SIGFPE",
+		"SIGKILL", "SIGUSR1", "SIGSEGV", "SIGUSR2",
+		"SIGPIPE", "SIGALRM", "SIGTERM", "SIGSTKFLT",
+		"SIGCHLD", "SIGCONT", "SIGSTOP", "SIGTSTP",
+		"SIGTTIN", "SIGTTOU", "SIGURG", "SIGXCPU",
+		"SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH",
+		"SIGIO", "SIGPWR", "SIGSYS"
+#endif
+#elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__APPLE__)
+		"SIGHUP", "SIGINT", "SIGQUIT", "SIGILL",
+		"SIGTRAP", "SIGABRT", "SIGEMT", "SIGFPE",
+		"SIGKILL", "SIGBUS", "SIGSEGV", "SIGSYS",
+		"SIGPIPE", "SIGALRM", "SIGTERM", "SIGURG",
+		"SIGSTOP", "SIGTSTP", "SIGCONT", "SIGCHLD",
+		"SIGTTIN", "SIGTTOU", "SIGIO", "SIGXCPU",
+		"SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH",
+		"SIGINFO", "SIGUSR1", "SIGUSR2"
+#else
+		"SIGHUP", "SIGINT", "SIGQUIT", "SIGILL",
+		"SIGTRAP", "SIGABRT", "7", "SIGFPE",
+		"SIGKILL", "10", "SIGSEGV", "12",
+		"SIGPIPE", "SIGALRM", "SIGTERM", "16",
+		"17", "18", "19", "20",
+		"21", "22", "23", "24",
+		"25", "26", "27", "28",
+		"29", "30", "31"
+#endif
+	};
+
+  std::unordered_map<string, Input::Mouse_loc> mouse_mappings;
+
+   const array<array<string, 3>, 3> menu_normal = {
+		array<string, 3>{
+			"┌─┐┌─┐┌┬┐┬┌─┐┌┐┌┌─┐",
+			"│ │├─┘ │ ││ ││││└─┐",
+			"└─┘┴   ┴ ┴└─┘┘└┘└─┘"
+		},
+		{
+			"┬ ┬┌─┐┬  ┌─┐",
+			"├─┤├┤ │  ├─┘",
+			"┴ ┴└─┘┴─┘┴  "
+		},
+		{
+			"┌─┐ ┬ ┬ ┬┌┬┐",
+			"│─┼┐│ │ │ │ ",
+			"└─┘└└─┘ ┴ ┴ "
+		}
+	};
+
+	const array<array<string, 3>, 3> menu_selected = {
+		array<string, 3>{
+			"╔═╗╔═╗╔╦╗╦╔═╗╔╗╔╔═╗",
+			"║ ║╠═╝ ║ ║║ ║║║║╚═╗",
+			"╚═╝╩   ╩ ╩╚═╝╝╚╝╚═╝"
+		},
+		{
+			"╦ ╦╔═╗╦  ╔═╗",
+			"╠═╣╠╣ ║  ╠═╝",
+			"╩ ╩╚═╝╩═╝╩  "
+		},
+		{
+			"╔═╗ ╦ ╦ ╦╔╦╗ ",
+			"║═╬╗║ ║ ║ ║  ",
+			"╚═╝╚╚═╝ ╩ ╩  "
+		}
+	};
+
+	const array<int, 3> menu_width = {19, 12, 12};
+
+	const vector<array<string, 2>> help_text = {
+		{"Mouse 1", "Clicks buttons and selects in process list."},
+		{"Mouse scroll", "Scrolls any scrollable list/text under cursor."},
+		{"Esc, m", "Toggles main menu."},
+		{"p", "Cycle view presets forwards."},
+		{"shift + p", "Cycle view presets backwards."},
+		{"1", "Toggle CPU box."},
+		{"2", "Toggle MEM box."},
+		{"3", "Toggle NET box."},
+		{"4", "Toggle PROC box."},
+		{"5", "Toggle GPU box."},
+		{"d", "Toggle disks view in MEM box."},
+		{"F2, o", "Shows options."},
+		{"F1, ?, h", "Shows this window."},
+		{"ctrl + z", "Sleep program and put in background."},
+		{"ctrl + r", "Reloads config file from disk."},
+		{"q, ctrl + c", "Quits program."},
+		{"+, -", "Add/Subtract 100ms to/from update timer."},
+		{"Up, Down", "Select in process list."},
+		{"Enter", "Show detailed information for selected process."},
+		{"Spacebar", "Expand/collapse the selected process in tree view."},
+		{"u", "Expand/collapse the selected process' children."},
+		{"Pg Up, Pg Down", "Jump 1 page in process list."},
+		{"Home, End", "Jump to first or last page in process list."},
+		{"Left, Right", "Select previous/next sorting column."},
+		{"b, n", "Select previous/next network device."},
+		{"i", "Toggle disks io mode with big graphs."},
+		{"z", "Toggle totals reset for current network device"},
+		{"a", "Toggle auto scaling for the network graphs."},
+		{"y", "Toggle synced scaling mode for network graphs."},
+		{"f, /", "To enter a process filter. Start with ! for regex."},
+		{"F", "Pause process list."},
+		{"delete", "Clear any entered filter."},
+		{"c", "Toggle per-core cpu usage of processes."},
+		{"r", "Reverse sorting order in processes box."},
+		{"e", "Toggle processes tree view."},
+		{"%", "Toggles memory display mode in processes box."},
+		{"Selected +, -", "Expand/collapse the selected process in tree view."},
+		{"Selected t", "Terminate selected process with SIGTERM - 15."},
+		{"Selected k", "Kill selected process with SIGKILL - 9."},
+		{"Selected s", "Select or enter signal to send to process."},
+		{"Selected N", "Select new nice value for selected process."},
+		{"", " "},
+		{"", "For bug reporting and project updates, visit:"},
+		{"", "https://github.com/aristocratos/btop"},
+	};
+
+	const vector<vector<vector<string>>> categories = {
+		{
+			{"color_theme",
+				"Set color theme.",
+				"",
+				"Choose from all theme files in (usually)",
+				"\"/usr/[local/]share/btop/themes\" and",
+				"\"~/.config/btop/themes\".",
+				"",
+				"\"Default\" for builtin default theme.",
+				"\"TTY\" for builtin 16-color theme.",
+				"",
+				"For theme updates see:",
+				"https://github.com/aristocratos/btop"},
+			{"theme_background",
+				"If the theme set background should be shown.",
+				"",
+				"Set to False if you want terminal background",
+				"transparency."},
+			{"truecolor",
+				"Sets if 24-bit truecolor should be used.",
+				"",
+				"Will convert 24-bit colors to 256 color",
+				"(6x6x6 color cube) if False.",
+				"",
+				"Set to False if your terminal doesn't have",
+				"truecolor support and can't convert to",
+				"256-color."},
+			{"force_tty",
+				"TTY mode.",
+				"",
+				"Set to true to force tty mode regardless",
+				"if a real tty has been detected or not.",
+				"",
+				"Will force 16-color mode and TTY theme,",
+				"set all graph symbols to \"tty\" and swap",
+				"out other non tty friendly symbols."},
+			{"vim_keys",
+				"Enable vim keys.",
+				"Set to True to enable \"h,j,k,l\" keys for",
+				"directional control in lists.",
+				"",
+				"Conflicting keys for",
+				"h (help) and k (kill)",
+				"is accessible while holding shift."},
+
+			{"presets",
+				"Define presets for the layout of the boxes.",
+				"",
+				"Preset 0 is always all boxes shown with",
+				"default settings.",
+				"Max 9 presets.",
+				"",
+				"Format: \"box_name:P:G,box_name:P:G\"",
+				"P=(0 or 1) for alternate positions.",
+				"G=graph symbol to use for box.",
+				"",
+				"Use whitespace \" \" as separator between",
+				"different presets.",
+				"",
+				"Example:",
+				"\"mem:0:tty,proc:1:default cpu:0:braille\""},
+			{"shown_boxes",
+				"Manually set which boxes to show.",
+				"",
+				"Available values are \"cpu mem net proc\".",
+			#ifdef GPU_SUPPORT
+				"Or \"gpu0\" through \"gpu5\" for GPU boxes.",
+			#endif
+				"Separate values with whitespace.",
+				"",
+				"Toggle between presets with key \"p\"."},
+			{"update_ms",
+				"Update time in milliseconds.",
+				"",
+				"Recommended 2000 ms or above for better",
+				"sample times for graphs.",
+				"",
+				"Min value: 100 ms",
+				"Max value: 86400000 ms = 24 hours."},
+			{"rounded_corners",
+				"Rounded corners on boxes.",
+				"",
+				"True or False",
+				"",
+				"Is always False if TTY mode is ON."},
+			{"terminal_sync",
+				"Output synchronization.",
+				"",
+				"Use terminal synchronized output sequences",
+				"to reduce flickering on supported terminals.",
+				"",
+				"True or False."},
+			{"graph_symbol",
+				"Default symbols to use for graph creation.",
+				"",
+				"\"braille\", \"block\" or \"tty\".",
+				"",
+				"\"braille\" offers the highest resolution but",
+				"might not be included in all fonts.",
+				"",
+				"\"block\" has half the resolution of braille",
+				"but uses more common characters.",
+				"",
+				"\"tty\" uses only 3 different symbols but will",
+				"work with most fonts.",
+				"",
+				"Note that \"tty\" only has half the horizontal",
+				"resolution of the other two,",
+				"so will show a shorter historical view."},
+			{"clock_format",
+				"Draw a clock at top of screen.",
+				"(Only visible if cpu box is enabled!)",
+				"",
+				"Formatting according to strftime, empty",
+				"string to disable.",
+				"",
+				"Custom formatting options:",
+				"\"/host\" = hostname",
+				"\"/user\" = username",
+				"\"/uptime\" = system uptime",
+				"",
+				"Examples of strftime formats:",
+				"\"%X\" = locale HH:MM:SS",
+				"\"%H\" = 24h hour, \"%I\" = 12h hour",
+				"\"%M\" = minute, \"%S\" = second",
+				"\"%d\" = day, \"%m\" = month, \"%y\" = year"},
+			{"base_10_sizes",
+				"Use base 10 for bits and bytes sizes.",
+				"",
+				"Uses KB = 1000 instead of KiB = 1024,",
+				"MB = 1000KB instead of MiB = 1024KiB,",
+				"and so on.",
+				"",
+				"True or False."},
+			{"background_update",
+				"Update main ui when menus are showing.",
+				"",
+				"True or False.",
+				"",
+				"Set this to false if the menus is flickering",
+				"too much for a comfortable experience."},
+			{"show_battery",
+				"Show battery stats.",
+				"(Only visible if cpu box is enabled!)",
+				"",
+				"Show battery stats in the top right corner",
+				"if a battery is present."},
+			{"selected_battery",
+				"Select battery.",
+				"",
+				"Which battery to use if multiple are present.",
+				"Can be both batteries and UPS.",
+				"",
+				"\"Auto\" for auto detection."},
+			{"show_battery_watts",
+				"Show battery power.",
+				"",
+				"Show discharge power when discharging.",
+				"Show charging power when charging."},
+			{"log_level",
+				"Set loglevel for error.log",
+				"",
+				"\"ERROR\", \"WARNING\", \"INFO\" and \"DEBUG\".",
+				"",
+				"The level set includes all lower levels,",
+				"i.e. \"DEBUG\" will show all logging info."}
+		},
+		{
+			{"cpu_bottom",
+				"Cpu box location.",
+				"",
+				"Show cpu box at bottom of screen instead",
+				"of top."},
+			{"graph_symbol_cpu",
+				"Graph symbol to use for graphs in cpu box.",
+				"",
+				"\"default\", \"braille\", \"block\" or \"tty\".",
+				"",
+				"\"default\" for the general default symbol.",},
+			{"cpu_graph_upper",
+				"Cpu upper graph.",
+				"",
+				"Sets the CPU/GPU stat shown in upper half of",
+				"the CPU graph.",
+				"",
+				"CPU:",
+				"\"total\" = Total cpu usage. (Auto)",
+				"\"user\" = User mode cpu usage.",
+				"\"system\" = Kernel mode cpu usage.",
+				"+ more depending on kernel.",
+		#ifdef GPU_SUPPORT
+				"",
+				"GPU:",
+				"\"gpu-totals\" = GPU usage split by device.",
+				"\"gpu-vram-totals\" = VRAM usage split by GPU.",
+				"\"gpu-pwr-totals\" = Power usage split by GPU.",
+				"\"gpu-average\" = Avg usage of all GPUs.",
+				"\"gpu-vram-total\" = VRAM usage of all GPUs.",
+				"\"gpu-pwr-total\" = Power usage of all GPUs.",
+				"Not all stats are supported on all devices."
+		#endif
+				},
+			{"cpu_graph_lower",
+				"Cpu lower graph.",
+				"",
+				"Sets the CPU/GPU stat shown in lower half of",
+				"the CPU graph.",
+				"",
+				"CPU:",
+				"\"total\" = Total cpu usage.",
+				"\"user\" = User mode cpu usage.",
+				"\"system\" = Kernel mode cpu usage.",
+				"+ more depending on kernel.",
+		#ifdef GPU_SUPPORT
+				"",
+				"GPU:",
+				"\"gpu-totals\" = GPU usage split/device. (Auto)",
+				"\"gpu-vram-totals\" = VRAM usage split by GPU.",
+				"\"gpu-pwr-totals\" = Power usage split by GPU.",
+				"\"gpu-average\" = Avg usage of all GPUs.",
+				"\"gpu-vram-total\" = VRAM usage of all GPUs.",
+				"\"gpu-pwr-total\" = Power usage of all GPUs.",
+				"Not all stats are supported on all devices."
+		#endif
+				},
+			{"cpu_invert_lower",
+					"Toggles orientation of the lower CPU graph.",
+					"",
+					"True or False."},
+			{"cpu_single_graph",
+					"Completely disable the lower CPU graph.",
+					"",
+					"Shows only upper CPU graph and resizes it",
+					"to fit to box height.",
+					"",
+					"True or False."},
+		#ifdef GPU_SUPPORT
+			{"show_gpu_info",
+					"Show gpu info in cpu box.",
+					"",
+					"Toggles gpu stats in cpu box and the",
+					"gpu graph (if \"cpu_graph_lower\" is set to",
+					"\"Auto\").",
+					"",
+					"\"Auto\" to show when no gpu box is shown.",
+					"\"On\" to always show.",
+					"\"Off\" to never show."},
+		#endif
+			{"check_temp",
+				"Enable cpu temperature reporting.",
+				"",
+				"True or False."},
+			{"cpu_sensor",
+				"Cpu temperature sensor.",
+				"",
+				"Select the sensor that corresponds to",
+				"your cpu temperature.",
+				"",
+				"Set to \"Auto\" for auto detection."},
+			{"show_coretemp",
+				"Show temperatures for cpu cores.",
+				"",
+				"Only works if check_temp is True and",
+				"the system is reporting core temps."},
+			{"cpu_core_map",
+				"Custom mapping between core and coretemp.",
+				"",
+				"Can be needed on certain cpus to get correct",
+				"temperature for correct core.",
+				"",
+				"Use lm-sensors or similar to see which cores",
+				"are reporting temperatures on your machine.",
+				"",
+				"Format: \"X:Y\"",
+				"X=core with wrong temp.",
+				"Y=core with correct temp.",
+				"Use space as separator between multiple",
+				"entries.",
+				"",
+				"Example: \"4:0 5:1 6:3\""},
+			{"temp_scale",
+				"Which temperature scale to use.",
+				"",
+				"Celsius, default scale.",
+				"",
+				"Fahrenheit, the american one.",
+				"",
+				"Kelvin, 0 = absolute zero, 1 degree change",
+				"equals 1 degree change in Celsius.",
+				"",
+				"Rankine, 0 = absolute zero, 1 degree change",
+				"equals 1 degree change in Fahrenheit."},
+			{"show_cpu_freq",
+				"Show CPU frequency.",
+				"",
+				"Can cause slowdowns on systems with many",
+				"cores and certain kernel versions."},
+		#ifdef __linux__
+			{"freq_mode",
+				"How the CPU frequency will be displayed.",
+				"",
+				"First, get the frequency from the first",
+				"core.",
+				"",
+				"Range, show the lowest and the highest",
+				"frequency.",
+				"",
+				"Lowest, the lowest frequency.",
+				"",
+				"Highest, the highest frequency.",
+				"",
+				"Average, sum and divide."},
+		#endif
+			{"custom_cpu_name",
+				"Custom cpu model name in cpu percentage box.",
+				"",
+				"Empty string to disable."},
+			{"show_uptime",
+				"Shows the system uptime in the CPU box.",
+				"",
+				"Can also be shown in the clock by using",
+				"\"/uptime\" in the formatting.",
+				"",
+				"True or False."},
+			{"show_cpu_watts",
+				"Shows the CPU power consumption in watts.",
+				"",
+				"Requires running `make setcap` or",
+				"`make setuid` or running with sudo.",
+				"",
+				"True or False."},
+		},
+	#ifdef GPU_SUPPORT
+		{
+			{"nvml_measure_pcie_speeds",
+				"Measure PCIe throughput on NVIDIA cards.",
+				"",
+				"May impact performance on certain cards.",
+				"",
+				"True or False."},
+			{"rsmi_measure_pcie_speeds",
+				"Measure PCIe throughput on AMD cards.",
+				"",
+				"May impact performance on certain cards.",
+				"",
+				"True or False."},
+			{"graph_symbol_gpu",
+				"Graph symbol to use for graphs in gpu box.",
+				"",
+				"\"default\", \"braille\", \"block\" or \"tty\".",
+				"",
+				"\"default\" for the general default symbol.",},
+			{"gpu_mirror_graph",
+				"Horizontally mirror the GPU graph.",
+				"",
+				"True or False."},
+			{"shown_gpus",
+				"Manually set which gpu vendors to show.",
+				"",
+				"Available values are",
+				"\"nvidia\", \"amd\", and \"intel\".",
+				"Separate values with whitespace.",
+				"",
+				"A restart is required to apply changes."},
+			{"custom_gpu_name0",
+				"Custom gpu0 model name in gpu stats box.",
+				"",
+				"Empty string to disable."},
+			{"custom_gpu_name1",
+				"Custom gpu1 model name in gpu stats box.",
+				"",
+				"Empty string to disable."},
+			{"custom_gpu_name2",
+				"Custom gpu2 model name in gpu stats box.",
+				"",
+				"Empty string to disable."},
+			{"custom_gpu_name3",
+				"Custom gpu3 model name in gpu stats box.",
+				"",
+				"Empty string to disable."},
+			{"custom_gpu_name4",
+				"Custom gpu4 model name in gpu stats box.",
+				"",
+				"Empty string to disable."},
+			{"custom_gpu_name5",
+				"Custom gpu5 model name in gpu stats box.",
+				"",
+				"Empty string to disable."},
+		},
+	#endif
+		{
+			{"mem_below_net",
+				"Mem box location.",
+				"",
+				"Show mem box below net box instead of above."},
+			{"graph_symbol_mem",
+				"Graph symbol to use for graphs in mem box.",
+				"",
+				"\"default\", \"braille\", \"block\" or \"tty\".",
+				"",
+				"\"default\" for the general default symbol.",},
+			{"mem_graphs",
+				"Show graphs for memory values.",
+				"",
+				"True or False."},
+			{"show_disks",
+				"Split memory box to also show disks.",
+				"",
+				"True or False."},
+			{"show_io_stat",
+				"Toggle IO activity graphs.",
+				"",
+				"Show small IO graphs that for disk activity",
+				"(disk busy time) when not in IO mode.",
+				"",
+				"True or False."},
+			{"io_mode",
+				"Toggles io mode for disks.",
+				"",
+				"Shows big graphs for disk read/write speeds",
+				"instead of used/free percentage meters.",
+				"",
+				"True or False."},
+			{"io_graph_combined",
+				"Toggle combined read and write graphs.",
+				"",
+				"Only has effect if \"io mode\" is True.",
+				"",
+				"True or False."},
+			{"io_graph_speeds",
+				"Set top speeds for the io graphs.",
+				"",
+				"Manually set which speed in MiB/s that",
+				"equals 100 percent in the io graphs.",
+				"(100 MiB/s by default).",
+				"",
+				"Format: \"device:speed\" separate disks with",
+				"whitespace \" \".",
+				"",
+				"Example: \"/dev/sda:100, /dev/sdb:20\"."},
+			{"show_swap",
+				"If swap memory should be shown in memory box.",
+				"",
+				"True or False."},
+			{"swap_disk",
+				"Show swap as a disk.",
+				"",
+				"Ignores show_swap value above.",
+				"Inserts itself after first disk."},
+			{"only_physical",
+				"Filter out non physical disks.",
+				"",
+				"Set this to False to include network disks,",
+				"RAM disks and similar.",
+				"",
+				"True or False."},
+			{"use_fstab",
+				"(Linux) Read disks list from /etc/fstab.",
+				"",
+				"This also disables only_physical.",
+				"",
+				"True or False."},
+			{"zfs_hide_datasets",
+				"(Linux) Hide ZFS datasets in disks list.",
+				"",
+				"Setting this to True will hide all datasets,",
+				"and only show ZFS pools.",
+				"",
+				"(IO stats will be calculated per-pool)",
+				"",
+				"True or False."},
+			{"disk_free_priv",
+				"(Linux) Type of available disk space.",
+				"",
+				"Set to true to show how much disk space is",
+				"available for privileged users.",
+				"",
+				"Set to false to show available for normal",
+				"users."},
+			{"disks_filter",
+				"Optional filter for shown disks.",
+				"",
+				"Should be full path of a mountpoint.",
+				"Separate multiple values with",
+				"whitespace \" \".",
+				"",
+				"Only disks matching the filter will be shown.",
+				"Prepend \033[3mexclude=\033[23m to only show disks ",
+				"not matching the filter.",
+				"",
+				"Examples:",
+				"/boot /home/user",
+				"exclude=/boot /home/user"},
+			{"zfs_arc_cached",
+				"(Linux) Count ZFS ARC as cached memory.",
+				"",
+				"Add ZFS ARC used to cached memory and",
+				"ZFS ARC available to available memory.",
+				"These are otherwise reported by the Linux",
+				"kernel as used memory.",
+				"",
+				"True or False."},
+		},
+		{
+			{"graph_symbol_net",
+				"Graph symbol to use for graphs in net box.",
+				"",
+				"\"default\", \"braille\", \"block\" or \"tty\".",
+				"",
+				"\"default\" for the general default symbol.",},
+			{"net_download",
+				"Fixed network graph download value.",
+				"",
+				"Value in Mebibits, default \"100\".",
+				"",
+				"Can be toggled with auto button."},
+			{"net_upload",
+				"Fixed network graph upload value.",
+				"",
+				"Value in Mebibits, default \"100\".",
+				"",
+				"Can be toggled with auto button."},
+			{"net_auto",
+				"Start in network graphs auto rescaling mode.",
+				"",
+				"Ignores any values set above at start and",
+				"rescales down to 10Kibibytes at the lowest.",
+				"",
+				"True or False."},
+			{"net_sync",
+				"Network scale sync.",
+				"",
+				"Syncs the scaling for download and upload to",
+				"whichever currently has the highest scale.",
+				"",
+				"True or False."},
+			{"net_iface",
+				"Network Interface.",
+				"",
+				"Manually set the starting Network Interface.",
+				"",
+				"Will otherwise automatically choose the NIC",
+				"with the highest total download since boot."},
+		    {"base_10_bitrate",
+			    "Base 10 bitrate",
+			    "",
+			    "True:  Use SI prefixes for bitrates",
+			    "       (1000Kbps = 1Mbps)",
+			    "False: Use binary prefixes for bitrates",
+			    "       (1024Kibps = 1Mibps)",
+			    "Auto:  Use the General -> Base 10 Sizes",
+			    "       setting for bitrates",
+			    "",
+			    "True, False, or Auto",},
+		},
+		{
+			{"proc_left",
+				"Proc box location.",
+				"",
+				"Show proc box on left side of screen",
+				"instead of right."},
+			{"graph_symbol_proc",
+				"Graph symbol to use for graphs in proc box.",
+				"",
+				"\"default\", \"braille\", \"block\" or \"tty\".",
+				"",
+				"\"default\" for the general default symbol.",},
+			{"proc_sorting",
+				"Processes sorting option.",
+				"",
+				"Possible values:",
+				"\"pid\", \"program\", \"arguments\", \"threads\",",
+				"\"user\", \"memory\", \"cpu lazy\" and",
+				"\"cpu direct\".",
+				"",
+				"\"cpu lazy\" updates top process over time.",
+				"\"cpu direct\" updates top process",
+				"directly."},
+			{"proc_reversed",
+				"Reverse processes sorting order.",
+				"",
+				"True or False."},
+			{"proc_tree",
+				"Processes tree view.",
+				"",
+				"Set true to show processes grouped by",
+				"parents with lines drawn between parent",
+				"and child process."},
+			{"proc_aggregate",
+				"Aggregate child's resources in parent.",
+				"",
+				"In tree-view, include all child resources",
+				"with the parent even while expanded."},
+			{"proc_colors",
+				"Enable colors in process view.",
+				"",
+				"True or False."},
+			{"proc_gradient",
+				"Enable process view gradient fade.",
+				"",
+				"Fades from top or current selection.",
+				"Max fade value is equal to current themes",
+				"\"inactive_fg\" color value."},
+			{"proc_per_core",
+				"Process usage per core.",
+				"",
+				"If process cpu usage should be of the core",
+				"it's running on or usage of the total",
+				"available cpu power.",
+				"",
+				"If true and process is multithreaded",
+				"cpu usage can reach over 100%."},
+			{"proc_mem_bytes",
+				"Show memory as bytes in process list.",
+				" ",
+				"Will show percentage of total memory",
+				"if False."},
+			{"keep_dead_proc_usage",
+				"Cpu and Mem usage for dead processes",
+				"",
+				"Set true if process should preserve the cpu",
+				"and memory usage of when it died while",
+				"paused."},
+			{"proc_cpu_graphs",
+				"Show cpu graph for each process.",
+				"",
+				"True or False"},
+			{"proc_filter_kernel",
+				"(Linux) Filter kernel processes from output.",
+				"",
+				"Set to 'True' to filter out internal",
+				"processes started by the Linux kernel."},
+		}
+	};
+
+	msgBox::msgBox() {}
+	msgBox::msgBox(int width, int boxtype, const vector<string>& content, const std::string_view title)
+	: width(width), boxtype(boxtype) {
+		auto tty_mode = Config::getB("tty_mode");
+		auto rounded = Config::getB("rounded_corners");
+		const auto& right_up = (tty_mode or not rounded ? Symbols::right_up : Symbols::round_right_up);
+		const auto& left_up = (tty_mode or not rounded ? Symbols::left_up : Symbols::round_left_up);
+		const auto& right_down = (tty_mode or not rounded ? Symbols::right_down : Symbols::round_right_down);
+		const auto& left_down = (tty_mode or not rounded ? Symbols::left_down : Symbols::round_left_down);
+		height = content.size() + 7;
+		x = Term::width / 2 - width / 2;
+		y = Term::height/2 - height/2;
+		if (boxtype == 2) selected = 1;
+
+
+		button_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;
+		button_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);
+
+		box_contents = Draw::createBox(x, y, width, height, Theme::c("hi_fg"), true, title) + Mv::d(1);
+		for (const auto& line : content) {
+			box_contents += Mv::save + Mv::r(max((size_t)0, (width / 2) - (Fx::uncolor(line).size() / 2) - 1)) + line + Mv::restore + Mv::d(1);
+		}
+	}
+
+	string msgBox::operator()() {
+		string out;
+		int pos = width / 2 - (boxtype == 0 ? 6 : 14);
+		const auto first_color = (selected == 0 ? Theme::c("hi_fg") : Theme::c("div_line"));
+		out = Mv::d(1) + Mv::r(pos) + Fx::b + first_color + button_left + (selected == 0 ? Theme::c("title") : Theme::c("main_fg") + Fx::ub)
+			+ (boxtype == 0 ? "    Ok    " : "    Yes    ") + first_color + button_right;
+		mouse_mappings["button1"] = Input::Mouse_loc{y + height - 4, x + pos + 1, 3, 12 + (boxtype > 0 ? 1 : 0)};
+		if (boxtype > 0) {
+			const auto second_color = (selected == 1 ? Theme::c("hi_fg") : Theme::c("div_line"));
+			out += Mv::r(2) + second_color + button_left + (selected == 1 ? Theme::c("title") : Theme::c("main_fg") + Fx::ub)
+				+ "    No    " + second_color + button_right;
+			mouse_mappings["button2"] = Input::Mouse_loc{y + height - 4, x + pos + 15 + (boxtype > 0 ? 1 : 0), 3, 12};
+		}
+		return box_contents + out + Fx::reset;
+	}
+
+	//? Process input
+	int msgBox::input(const string& key) {
+		if (key.empty()) return Invalid;
+
+		if (is_in(key, "escape", "backspace", "q") or key == "button2") {
+			return No_Esc;
+		}
+		else if (key == "button1" or (boxtype == 0 and str_to_upper(key) == "O")) {
+			return Ok_Yes;
+		}
+		else if (is_in(key, "enter", "space")) {
+			return selected + 1;
+		}
+		else if (boxtype == 0) {
+			return Invalid;
+		}
+		else if (str_to_upper(key) == "Y") {
+			return Ok_Yes;
+		}
+		else if (str_to_upper(key) == "N") {
+			return No_Esc;
+		}
+		else if (is_in(key, "right", "tab")) {
+			if (++selected > 1) selected = 0;
+			return Select;
+		}
+		else if (is_in(key, "left", "shift_tab")) {
+			if (--selected < 0) selected = 1;
+			return Select;
+		}
+
+		return Invalid;
+	}
+
+	void msgBox::clear() {
+		box_contents.clear();
+		box_contents.shrink_to_fit();
+		button_left.clear();
+		button_left.shrink_to_fit();
+		button_right.clear();
+		button_right.shrink_to_fit();
+		mouse_mappings.erase("button1");
+		mouse_mappings.erase("button2");
+	}
+
+	enum menuReturnCodes {
+		NoChange,
+		Changed,
+		Closed,
+		Switch
+	};
+
+	static int signalChoose(const string& key) {
+		auto s_pid = (Config::getB("show_detailed") and Config::getI("selected_pid") == 0 ? Config::getI("detailed_pid") : Config::getI("selected_pid"));
+		static int x{};
+		static int y{};
+		static int selected_signal = -1;
+
+		if (bg.empty()) selected_signal = -1;
+		auto& out = Global::overlay;
+		int retval = Changed;
+
+		if (redraw) {
+			x = Term::width/2 - 40;
+			y = Term::height/2 - 9;
+			bg = Draw::createBox(x + 2, y, 78, 19, Theme::c("hi_fg"), true, "signals");
+			bg += Mv::to(y+2, x+3) + Theme::c("title") + Fx::b + cjust("Send signal to PID " + to_string(s_pid) + " ("
+				+ uresize((s_pid == Config::getI("detailed_pid") ? Proc::detailed.entry.name : Config::getS("selected_name")), 30) + ")", 76);
+		}
+		else if (is_in(key, "escape", "q")) {
+			return Closed;
+		}
+		else if (key.starts_with("button_")) {
+			if (int new_select = stoi(key.substr(7)); new_select == selected_signal)
+				goto ChooseEntering;
+			else
+				selected_signal = new_select;
+		}
+		else if (is_in(key, "enter", "space") and selected_signal >= 0) {
+			ChooseEntering:
+			signalKillRet = 0;
+			if (s_pid < 1) {
+				signalKillRet = ESRCH;
+				menuMask.set(SignalReturn);
+			}
+			else if (kill(s_pid, selected_signal) != 0) {
+				signalKillRet = errno;
+				menuMask.set(SignalReturn);
+			}
+			return Closed;
+		}
+		else if (key.size() == 1 and isdigit(key.at(0)) and selected_signal < 10) {
+			selected_signal = std::min(std::stoi((selected_signal < 1 ? key : to_string(selected_signal) + key)), 64);
+		}
+		else if (key == "backspace" and selected_signal != -1) {
+			selected_signal = (selected_signal < 10 ? -1 : selected_signal / 10);
+		}
+		else if (is_in(key, "up", "k") and selected_signal != 16) {
+			if (selected_signal == 1) selected_signal = 31;
+			else if (selected_signal < 6) selected_signal += 25;
+			else {
+				bool offset = (selected_signal > 16);
+				selected_signal -= 5;
+				if (selected_signal <= 16 and offset) selected_signal--;
+			}
+		}
+		else if (is_in(key, "down", "j")) {
+			if (selected_signal == 31) selected_signal = 1;
+			else if (selected_signal < 1 or selected_signal == 16) selected_signal = 1;
+			else if (selected_signal > 26) selected_signal -= 25;
+			else {
+				bool offset = (selected_signal < 16);
+				selected_signal += 5;
+				if (selected_signal >= 16 and offset) selected_signal++;
+				if (selected_signal > 31) selected_signal = 31;
+			}
+		}
+		else if (is_in(key, "left", "h") and selected_signal > 0 and selected_signal != 16) {
+			if (--selected_signal < 1) selected_signal = 31;
+			else if (selected_signal == 16) selected_signal--;
+		}
+		else if (is_in(key, "right", "l") and selected_signal <= 31 and selected_signal != 16) {
+			if (++selected_signal > 31) selected_signal = 1;
+			else if (selected_signal == 16) selected_signal++;
+		}
+		else {
+			retval = NoChange;
+		}
+
+		if (retval == Changed) {
+			int cy = y+4, cx = x+4;
+			out = bg + Mv::to(cy++, x+3) + Theme::c("main_fg") + Fx::ub
+				+ rjust("Enter signal number: ", 48) + Theme::c("hi_fg") + (selected_signal >= 0 ? to_string(selected_signal) : "") + Theme::c("main_fg") + Fx::bl + "█" + Fx::ubl;
+
+			auto sig_str = to_string(selected_signal);
+			for (int count = 0, i = 0; const auto& sig : P_Signals) {
+				if (count == 0 or count == 16) { count++; continue; }
+				if (i++ % 5 == 0) { ++cy; cx = x+4; }
+				out += Mv::to(cy, cx);
+				if (count == selected_signal) out += Theme::c("selected_bg") + Theme::c("selected_fg") + Fx::b + ljust(to_string(count), 3) + ljust('(' + sig + ')', 12) + Fx::reset;
+				else out += Theme::c("hi_fg") + ljust(to_string(count), 3) + Theme::c("main_fg") + ljust('(' + sig + ')', 12);
+				if (redraw) mouse_mappings["button_" + to_string(count)] = {cy, cx, 1, 15};
+				count++;
+				cx += 15;
+			}
+
+			cy++;
+			out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust( "↑ ↓ ← →", 33, true) + Theme::c("main_fg") + Fx::ub + " | To choose signal.";
+			out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust("0-9", 33) + Theme::c("main_fg") + Fx::ub + " | Enter manually.";
+			out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust("ENTER", 33) + Theme::c("main_fg") + Fx::ub + " | To send signal.";
+			mouse_mappings["enter"] = {cy, x, 1, 73};
+			out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust("ESC or \"q\"", 33) + Theme::c("main_fg") + Fx::ub + " | To abort.";
+			mouse_mappings["escape"] = {cy, x, 1, 73};
+
+			out += Fx::reset;
+		}
+
+		return (redraw ? Changed : retval);
+	}
+
+	static int sizeError(const string& key) {
+		if (redraw) {
+			vector<string> cont_vec {
+				Fx::b + Theme::g("used")[100] + "Error:" + Theme::c("main_fg") + Fx::ub,
+				"Terminal size too small to" + Fx::reset,
+				"display menu or box!" + Fx::reset };
+
+			messageBox = Menu::msgBox{45, 0, cont_vec, "error"};
+			Global::overlay = messageBox();
+		}
+
+		auto ret = messageBox.input(key);
+		if (ret == msgBox::Ok_Yes or ret == msgBox::No_Esc) {
+			messageBox.clear();
+			return Closed;
+		}
+		else if (redraw) {
+			return Changed;
+		}
+		return NoChange;
+	}
+
+	static int signalSend(const string& key) {
+		auto s_pid = (Config::getB("show_detailed") and Config::getI("selected_pid") == 0 ? Config::getI("detailed_pid") : Config::getI("selected_pid"));
+		if (s_pid == 0) return Closed;
+		if (redraw) {
+			atomic_wait(Runner::active);
+			auto& p_name = (s_pid == Config::getI("detailed_pid") ? Proc::detailed.entry.name : Config::getS("selected_name"));
+			vector<string> cont_vec = {
+				Fx::b + Theme::c("main_fg") + "Send signal: " + Fx::ub + Theme::c("hi_fg") + to_string(signalToSend)
+				+ (signalToSend > 0 and signalToSend <= 32 ? Theme::c("main_fg") + " (" + P_Signals.at(signalToSend) + ')' : ""),
+
+				Fx::b + Theme::c("main_fg") + "To PID: " + Fx::ub + Theme::c("hi_fg") + to_string(s_pid) + Theme::c("main_fg") + " ("
+				+ uresize(p_name, 16) + ')' + Fx::reset,
+			};
+			messageBox = Menu::msgBox{50, 1, cont_vec, (signalToSend > 1 and signalToSend <= 32 and signalToSend != 17 ? P_Signals.at(signalToSend) : "signal")};
+			Global::overlay = messageBox();
+		}
+		auto ret = messageBox.input(key);
+		if (ret == msgBox::Ok_Yes) {
+			signalKillRet = 0;
+			if (kill(s_pid, signalToSend) != 0) {
+				signalKillRet = errno;
+				menuMask.set(SignalReturn);
+			}
+			messageBox.clear();
+			return Closed;
+		}
+		else if (ret == msgBox::No_Esc) {
+			messageBox.clear();
+			return Closed;
+		}
+		else if (ret == msgBox::Select) {
+			Global::overlay = messageBox();
+			return Changed;
+		}
+		else if (redraw) {
+			return Changed;
+		}
+		return NoChange;
+	}
+
+	static int signalReturn(const string& key) {
+		if (redraw) {
+			vector<string> cont_vec;
+			cont_vec.push_back(Fx::b + Theme::g("used")[100] + "Failure:" + Theme::c("main_fg") + Fx::ub);
+			if (signalKillRet == EINVAL) {
+				cont_vec.push_back("Unsupported signal!" + Fx::reset);
+			}
+			else if (signalKillRet == EPERM) {
+				cont_vec.push_back("Insufficient permissions to send signal!" + Fx::reset);
+			}
+			else if (signalKillRet == ESRCH) {
+				cont_vec.push_back("Process not found!" + Fx::reset);
+			}
+			else {
+				cont_vec.push_back("Unknown error! (errno: " + to_string(signalKillRet) + ')' + Fx::reset);
+			}
+
+			messageBox = Menu::msgBox{50, 0, cont_vec, "error"};
+			Global::overlay = messageBox();
+		}
+
+		auto ret = messageBox.input(key);
+		if (ret == msgBox::Ok_Yes or ret == msgBox::No_Esc) {
+			messageBox.clear();
+			return Closed;
+		}
+		else if (redraw) {
+			return Changed;
+		}
+		return NoChange;
+	}
+
+	static int mainMenu(const string& key) {
+		enum MenuItems { Options, Help, Quit };
+		static int y{};
+		static int selected{};
+		static vector<string> colors_selected;
+		static vector<string> colors_normal;
+		auto tty_mode = Config::getB("tty_mode");
+		if (bg.empty()) selected = 0;
+		int retval = Changed;
+
+		if (redraw) {
+			y = Term::height/2 - 10;
+			bg = Draw::banner_gen(y, 0, true);
+			if (not tty_mode) {
+				colors_selected = {
+					Theme::hex_to_color(Global::Banner_src.at(0).at(0)),
+					Theme::hex_to_color(Global::Banner_src.at(2).at(0)),
+					Theme::hex_to_color(Global::Banner_src.at(4).at(0))
+				};
+				colors_normal = {
+					Theme::hex_to_color("#CC"),
+					Theme::hex_to_color("#AA"),
+					Theme::hex_to_color("#80")
+				};
+			}
+		}
+		else if (is_in(key, "escape", "q", "m", "mouse_click")) {
+			return Closed;
+		}
+		else if (key.starts_with("button_")) {
+			if (int new_select = key.back() - '0'; new_select == selected)
+				goto MainEntering;
+			else
+				selected = new_select;
+		}
+		else if (is_in(key, "enter", "space")) {
+			MainEntering:
+			switch (selected) {
+				case Options:
+					menuMask.set(Menus::Options);
+					currentMenu = Menus::Options;
+					return Switch;
+				case Help:
+					menuMask.set(Menus::Help);
+					currentMenu = Menus::Help;
+					return Switch;
+				case Quit:
+					clean_quit(0);
+			}
+		}
+		else if (is_in(key, "down", "tab", "mouse_scroll_down", "j")) {
+			if (++selected > 2) selected = 0;
+		}
+		else if (is_in(key, "up", "shift_tab", "mouse_scroll_up", "k")) {
+			if (--selected < 0) selected = 2;
+		}
+		else {
+			retval = NoChange;
+		}
+
+		if (retval == Changed) {
+			auto& out = Global::overlay;
+			out = bg + Fx::reset + Fx::b;
+			auto cy = y + 7;
+			for (const auto& i : iota(0, 3)) {
+				if (tty_mode) out += (i == selected ? Theme::c("hi_fg") : Theme::c("main_fg"));
+				const auto& menu = (not tty_mode and i == selected ? menu_selected[i] : menu_normal[i]);
+				const auto& colors = (i == selected ? colors_selected : colors_normal);
+				if (redraw) mouse_mappings["button_" + to_string(i)] = {cy, Term::width/2 - menu_width[i]/2, 3, menu_width[i]};
+				for (int ic = 0; const auto& line : menu) {
+					out += Mv::to(cy++, Term::width/2 - menu_width[i]/2) + (tty_mode ? "" : colors[ic++]) + line;
+				}
+			}
+			out += Fx::reset;
+		}
+
+		return (redraw ? Changed : retval);
+	}
+
+static int optionsMenu(const string& key) {
+ 		enum Predispositions { isBool, isInt, isString, is2D, isBrowsable, isEditable};
+		static int y{};
+		static int x{};
+		static int height{};
+		static int page{};
+		static int pages{};
+		static int selected{};
+		static int select_max{};
+		static int item_height{};
+		static int selected_cat{};
+		static int max_items{};
+		static int last_sel{};
+		static bool editing{};
+		static Draw::TextEdit editor;
+		static string warnings;
+		static bitset<8> selPred;
+		static const std::unordered_map<string, std::reference_wrapper<const vector<string>>> optionsList = {
+			{"color_theme", std::cref(Theme::themes)},
+			{"log_level", std::cref(Logger::log_levels)},
+			{"temp_scale", std::cref(Config::temp_scales)},
+		#ifdef __linux__
+			{"freq_mode", std::cref(Config::freq_modes)},
+		#endif
+			{"proc_sorting", std::cref(Proc::sort_vector)},
+			{"graph_symbol", std::cref(Config::valid_graph_symbols)},
+			{"graph_symbol_cpu", std::cref(Config::valid_graph_symbols_def)},
+			{"graph_symbol_mem", std::cref(Config::valid_graph_symbols_def)},
+			{"graph_symbol_net", std::cref(Config::valid_graph_symbols_def)},
+			{"graph_symbol_proc", std::cref(Config::valid_graph_symbols_def)},
+			{"cpu_graph_upper", std::cref(Cpu::available_fields)},
+			{"cpu_graph_lower", std::cref(Cpu::available_fields)},
+			{"cpu_sensor", std::cref(Cpu::available_sensors)},
+			{"selected_battery", std::cref(Config::available_batteries)},
+	        {"base_10_bitrate", std::cref(Config::base_10_bitrate_values)},
+		#ifdef GPU_SUPPORT
+			{"show_gpu_info", std::cref(Config::show_gpu_values)},
+			{"graph_symbol_gpu", std::cref(Config::valid_graph_symbols_def)},
+		#endif
+		};
+		auto tty_mode = Config::getB("tty_mode");
+		auto vim_keys = Config::getB("vim_keys");
+		if (max_items == 0) {
+			for (const auto& cat : categories) {
+				if ((int)cat.size() > max_items) max_items = cat.size();
+			}
+		}
+		if (bg.empty()) {
+			page = selected = selected_cat = last_sel = 0;
+			redraw = true;
+			Theme::updateThemes();
+		}
+		int retval = Changed;
+		bool recollect{};
+		bool screen_redraw{};
+		bool theme_refresh{};
+
+		//? Draw background if needed else process input
+		if (redraw) {
+			mouse_mappings.clear();
+			selPred.reset();
+			y = max(1, Term::height/2 - 3 - max_items);
+			x = Term::width/2 - 39;
+			height = min(Term::height - 7, max_items * 2 + 4);
+			if (height % 2 != 0) height--;
+			bg 	= Draw::banner_gen(y, 0, true)
+				+ Draw::createBox(x, y + 6, 78, height, Theme::c("hi_fg"), true, "tab" + Symbols::right)
+				+ Mv::to(y+8, x) + Theme::c("hi_fg") + Symbols::div_left + Theme::c("div_line") + Symbols::h_line * 29
+				+ Symbols::div_up + Symbols::h_line * (78 - 32) + Theme::c("hi_fg") + Symbols::div_right
+				+ Mv::to(y+6+height - 1, x+30) + Symbols::div_down + Theme::c("div_line");
+			for (const auto& i : iota(0, height - 4)) {
+				bg += Mv::to(y+9 + i, x + 30) + Symbols::v_line;
+			}
+		}
+		else if (not warnings.empty() and not key.empty()) {
+			auto ret = messageBox.input(key);
+			if (ret == msgBox::msgReturn::Ok_Yes or ret == msgBox::msgReturn::No_Esc) {
+				warnings.clear();
+				messageBox.clear();
+			}
+		}
+		else if (editing and not key.empty()) {
+			if (is_in(key, "escape", "mouse_click")) {
+				editor.clear();
+				editing = false;
+			}
+			else if (key == "enter") {
+				const auto& option = categories[selected_cat][item_height * page + selected][0];
+				if (selPred.test(isString) and Config::stringValid(option, editor.text)) {
+					Config::set(option, editor.text);
+					if (option == "custom_cpu_name" or option.starts_with("custom_gpu_name"))
+						screen_redraw = true;
+					else if (is_in(option, "shown_boxes", "presets")) {
+						screen_redraw = true;
+						Config::current_preset = -1;
+					}
+					else if (option == "clock_format") {
+						Draw::update_clock(true);
+						screen_redraw = true;
+					}
+					else if (option == "cpu_core_map") {
+						atomic_wait(Runner::active);
+						Cpu::core_mapping = Cpu::get_core_mapping();
+					}
+				}
+				else if (selPred.test(isInt) and Config::intValid(option, editor.text)) {
+					Config::set(option, stoi(editor.text));
+				}
+				else
+					warnings = Config::validError;
+
+				editor.clear();
+				editing = false;
+			}
+			else if (not editor.command(key))
+				retval = NoChange;
+		}
+		else if (key == "mouse_click") {
+			const auto [mouse_x, mouse_y] = Input::mouse_pos;
+			if (mouse_x < x or mouse_x > x + 80 or mouse_y < y + 6 or mouse_y > y + 6 + height) {
+				return Closed;
+			}
+			else if (mouse_x < x + 30 and mouse_y > y + 8) {
+				auto m_select = ceil((double)(mouse_y - y - 8) / 2) - 1;
+				if (selected != m_select)
+					selected = m_select;
+				else if (selPred.test(isEditable))
+					goto mouseEnter;
+				else retval = NoChange;
+			}
+		}
+		else if (is_in(key, "enter", "e", "E") and selPred.test(isEditable)) {
+			mouseEnter:
+			const auto& option = categories[selected_cat][item_height * page + selected][0];
+			editor = Draw::TextEdit{Config::getAsString(option), selPred.test(isInt)};
+			editing = true;
+			mouse_mappings.clear();
+		}
+		else if (is_in(key, "escape", "q", "o", "backspace")) {
+			return Closed;
+		}
+		else if (is_in(key, "down", "mouse_scroll_down") or (vim_keys and key == "j")) {
+			if (++selected > select_max or selected >= item_height) {
+				if (page < pages - 1) page++;
+				else if (pages > 1) page = 0;
+				selected = 0;
+			}
+		}
+		else if (is_in(key, "up", "mouse_scroll_up") or (vim_keys and key == "k")) {
+			if (--selected < 0) {
+				if (page > 0) page--;
+				else if (pages > 1) page = pages - 1;
+
+				selected = item_height - 1;
+			}
+		}
+		else if (pages > 1 and key == "page_down") {
+			if (++page >= pages) page = 0;
+			selected = 0;
+			last_sel = -1;
+		}
+		else if (pages > 1 and key == "page_up") {
+			if (--page < 0) page = pages - 1;
+			selected = 0;
+			last_sel = -1;
+		}
+		else if (key == "tab") {
+			if (++selected_cat >= (int)categories.size()) selected_cat = 0;
+			page = selected = 0;
+		}
+		else if (key == "shift_tab") {
+			if (--selected_cat < 0) selected_cat = (int)categories.size() - 1;
+			page = selected = 0;
+		}
+#ifdef GPU_SUPPORT
+		else if (is_in(key, "1", "2", "3", "4", "5", "6") or key.starts_with("select_cat_")) {
+#else
+		else if (is_in(key, "1", "2", "3", "4", "5") or key.starts_with("select_cat_")) {
+#endif
+		selected_cat = key.back() - '0' - 1;
+			page = selected = 0;
+		}
+		else if (is_in(key, "left", "right") or (vim_keys and is_in(key, "h", "l"))) {
+			const auto& option = categories[selected_cat][item_height * page + selected][0];
+			if (selPred.test(isInt)) {
+				const int mod = (option == "update_ms" ? 100 : 1);
+				long value = Config::getI(option);
+				if (key == "right" or (vim_keys and key == "l")) value += mod;
+				else value -= mod;
+
+				if (Config::intValid(option, to_string(value)))
+					Config::set(option, static_cast<int>(value));
+				else {
+					warnings = Config::validError;
+				}
+			}
+			else if (selPred.test(isBool)) {
+				Config::flip(option);
+				screen_redraw = true;
+				if (option == "truecolor") {
+					theme_refresh = true;
+					Config::flip("lowcolor");
+				}
+				else if (option == "force_tty") {
+					theme_refresh = true;
+					Config::flip("tty_mode");
+				}
+				else if (is_in(option, "rounded_corners", "theme_background"))
+					theme_refresh = true;
+				else if (option == "background_update") {
+					Runner::pause_output = false;
+				}
+				else if (option == "base_10_sizes") {
+					recollect = true;
+				}
+			}
+			else if (selPred.test(isBrowsable)) {
+				auto& optList = optionsList.at(option).get();
+				int i = v_index(optList, Config::getS(option));
+
+				if ((key == "right" or (vim_keys and key == "l")) and ++i >= (int)optList.size()) i = 0;
+				else if ((key == "left" or (vim_keys and key == "h")) and --i < 0) i = optList.size() - 1;
+				Config::set(option, optList.at(i));
+
+				if (option == "color_theme")
+					theme_refresh = true;
+				else if (option == "log_level") {
+					Logger::set(optList.at(i));
+					Logger::info("Logger set to " + optList.at(i));
+				}
+				else if (option == "base_10_bitrate") {
+				    recollect = true;
+				}
+				else if (is_in(option, "proc_sorting", "cpu_sensor", "show_gpu_info") or option.starts_with("graph_symbol") or option.starts_with("cpu_graph_"))
+					screen_redraw = true;
+			}
+			else
+				retval = NoChange;
+		}
+		else {
+			retval = NoChange;
+		}
+
+		//? Draw the menu
+		if (retval == Changed) {
+			Config::unlock();
+			auto& out = Global::overlay;
+			out = bg;
+			item_height = min((int)categories[selected_cat].size(), (int)floor((double)(height - 4) / 2));
+			pages = ceil((double)categories[selected_cat].size() / item_height);
+			if (page > pages - 1) page = pages - 1;
+			select_max = min(item_height - 1, (int)categories[selected_cat].size() - 1 - item_height * page);
+			if (selected > select_max) {
+				selected = select_max;
+			}
+
+			//? Get variable properties for currently selected option
+			if (selPred.none() or last_sel != (selected_cat << 8) + selected) {
+				selPred.reset();
+				last_sel = (selected_cat << 8) + selected;
+				const auto& selOption = categories[selected_cat][item_height * page + selected][0];
+				if (Config::ints.contains(selOption))
+					selPred.set(isInt);
+				else if (Config::bools.contains(selOption))
+					selPred.set(isBool);
+				else
+					selPred.set(isString);
+
+				if (not selPred.test(isString))
+					selPred.set(is2D);
+				else if (optionsList.contains(selOption)) {
+					selPred.set(isBrowsable);
+				}
+				if (not selPred.test(isBrowsable) and (selPred.test(isString) or selPred.test(isInt)))
+					selPred.set(isEditable);
+			}
+
+			//? Category buttons
+			out += Mv::to(y+7, x+4);
+		#ifdef GPU_SUPPORT
+			for (int i = 0; const auto& m : {"general", "cpu", "gpu", "mem", "net", "proc"}) {
+		#else
+			for (int i = 0; const auto& m : {"general", "cpu", "mem", "net", "proc"}) {
+		#endif
+				out += Fx::b + (i == selected_cat
+						? Theme::c("hi_fg") + '[' + Theme::c("title") + m + Theme::c("hi_fg") + ']'
+						: Theme::c("hi_fg") + to_string(i + 1) + Theme::c("title") + m + ' ')
+				#ifdef GPU_SUPPORT
+					+ Mv::r(7);
+				#else
+					+ Mv::r(10);
+				#endif
+				if (string button_name = "select_cat_" + to_string(i + 1); not editing and not mouse_mappings.contains(button_name))
+					mouse_mappings[button_name] = {y+6, x+2 + 15*i, 3, 15};
+				i++;
+			}
+			if (pages > 1) {
+				out += Mv::to(y+6 + height - 1, x+2) + Theme::c("hi_fg") + Symbols::title_left_down + Fx::b + Symbols::up + Theme::c("title") + " page "
+					+ to_string(page+1) + '/' + to_string(pages) + ' ' + Theme::c("hi_fg") + Symbols::down + Fx::ub + Symbols::title_right_down;
+			}
+			//? Option name and value
+			auto cy = y+9;
+			for (int c = 0, i = max(0, item_height * page); c++ < item_height and i < (int)categories[selected_cat].size(); i++) {
+				const auto& option = categories[selected_cat][i][0];
+				const auto& value = (option == "color_theme" ? fs::path(Config::getS("color_theme")).stem().string() : Config::getAsString(option));
+
+				out += Mv::to(cy++, x + 1) + (c-1 == selected ? Theme::c("selected_bg") + Theme::c("selected_fg") : Theme::c("title"))
+					+ Fx::b + cjust(capitalize(s_replace(option, "_", " "))
+						+ (c-1 == selected and selPred.test(isBrowsable)
+							? ' ' + to_string(v_index(optionsList.at(option).get(), (option == "color_theme" ? Config::getS("color_theme") : value)) + 1) + '/' + to_string(optionsList.at(option).get().size())
+							: ""), 29);
+				out	+= Mv::to(cy++, x + 1) + (c-1 == selected ? "" : Theme::c("main_fg")) + Fx::ub + "  "
+					+ (c-1 == selected and editing ? cjust(editor(24), 34, true) : cjust(value, 25, true)) + "  ";
+
+				if (c-1 == selected) {
+					if (not editing and (selPred.test(is2D) or selPred.test(isBrowsable))) {
+						out += Fx::b + Mv::to(cy-1, x+2) + Symbols::left + Mv::to(cy-1, x+28) + Symbols::right;
+						mouse_mappings["left"] = {cy-2, x, 2, 5};
+						mouse_mappings["right"] = {cy-2, x+25, 2, 5};
+					}
+					if (selPred.test(isEditable)) {
+						out += Fx::b + Mv::to(cy-1, x+28 - (not editing and selPred.test(isInt) ? 2 : 0)) + (tty_mode ? "E" : Symbols::enter);
+					}
+					//? Description of selected option
+					out += Fx::reset + Theme::c("title") + Fx::b;
+					for (int cyy = y+7; const auto& desc : categories[selected_cat][i]) {
+						if (cyy++ == y+7) continue;
+						else if (cyy == y+10) out += Theme::c("main_fg") + Fx::ub;
+						else if (cyy > y + height + 4) break;
+						out += Mv::to(cyy, x+32) + desc;
+					}
+				}
+			}
+
+			if (not warnings.empty()) {
+				messageBox = msgBox{min(78, (int)ulen(warnings) + 10), msgBox::BoxTypes::OK, {uresize(warnings, 74)}, "warning"};
+				out += messageBox();
+			}
+
+			out += Fx::reset;
+		}
+
+		if (theme_refresh) {
+			Theme::setTheme();
+			Draw::banner_gen(0, 0, false, true);
+			screen_redraw = true;
+			redraw = true;
+			optionsMenu("");
+		}
+		if (screen_redraw) {
+			auto overlay_bkp = std::move(Global::overlay);
+			auto clock_bkp = std::move(Global::clock);
+			Draw::calcSizes();
+			Global::overlay = std::move(overlay_bkp);
+			Global::clock = std::move(clock_bkp);
+			recollect = true;
+		}
+		if (recollect) {
+			Runner::run("all", false, true);
+			retval = NoChange;
+		}
+
+		return (redraw ? Changed : retval);
+	}
+
+	static int helpMenu(const string& key) {
+		static int y{};
+		static int x{};
+		static int height{};
+		static int page{};
+		static int pages{};
+
+		if (bg.empty()) page = 0;
+		int retval = Changed;
+
+		if (redraw) {
+			y = max(1, Term::height/2 - 4 - (int)(help_text.size() / 2));
+			x = Term::width/2 - 39;
+			height = min(Term::height - 6, (int)help_text.size() + 3);
+			pages = ceil((double)help_text.size() / (height - 3));
+			page = 0;
+			bg = Draw::banner_gen(y, 0, true);
+			bg += Draw::createBox(x, y + 6, 78, height, Theme::c("hi_fg"), true, "help");
+		}
+		else if (is_in(key, "escape", "q", "h", "backspace", "space", "enter", "mouse_click")) {
+			return Closed;
+		}
+		else if (pages > 1 and is_in(key, "down", "j", "page_down", "tab", "mouse_scroll_down")) {
+			if (++page >= pages) page = 0;
+		}
+		else if (pages > 1 and is_in(key, "up", "k", "page_up", "shift_tab", "mouse_scroll_up")) {
+			if (--page < 0) page = pages - 1;
+		}
+		else {
+			retval = NoChange;
+		}
+
+
+		if (retval == Changed) {
+			auto& out = Global::overlay;
+			out = bg;
+			if (pages > 1) {
+				out += Mv::to(y+height+6, x + 2) + Theme::c("hi_fg") + Symbols::title_left_down + Fx::b + Symbols::up + Theme::c("title") + " page "
+					+ to_string(page+1) + '/' + to_string(pages) + ' ' + Theme::c("hi_fg") + Symbols::down + Fx::ub + Symbols::title_right_down;
+			}
+			auto cy = y+7;
+			out += Mv::to(cy++, x + 1) + Theme::c("title") + Fx::b + cjust("Key:", 20) + "Description:";
+			for (int c = 0, i = max(0, (height - 3) * page); c++ < height - 3 and i < (int)help_text.size(); i++) {
+				out += Mv::to(cy++, x + 1) + Theme::c("hi_fg") + Fx::b + cjust(help_text[i][0], 20)
+					+ Theme::c("main_fg") + Fx::ub + help_text[i][1];
+			}
+			out += Fx::reset;
+		}
+
+
+		return (redraw ? Changed : retval);
+	}
+
+	static int reniceMenu(const string& key) {
+		auto s_pid = (Config::getB("show_detailed") and Config::getI("selected_pid") == 0 ? Config::getI("detailed_pid") : Config::getI("selected_pid"));
+		static int x{};
+		static int y{};
+		static int selected_nice = 0;
+		static string nice_edit;
+
+		if (bg.empty()) {
+			selected_nice = 0;
+			nice_edit.clear();
+		}
+		auto& out = Global::overlay;
+		int retval = Changed;
+
+		if (redraw) {
+			x = Term::width/2 - 25;
+			y = Term::height/2 - 6;
+			bg = Draw::createBox(x + 2, y, 50, 13, Theme::c("hi_fg"), true, "renice");
+			bg += Mv::to(y+2, x+3) + Theme::c("title") + Fx::b + cjust("Renice PID " + to_string(s_pid) + " ("
+				+ uresize((s_pid == Config::getI("detailed_pid") ? Proc::detailed.entry.name : Config::getS("selected_name")), 15) + ")", 48);
+		}
+		else if (is_in(key, "escape", "q")) {
+			return Closed;
+		}
+		else if (is_in(key, "enter", "space")) {
+			if (s_pid > 0) {
+				if (not nice_edit.empty()) {
+					try {
+						selected_nice = stoi(nice_edit);
+					}
+					catch (...) { selected_nice = 0; }
+				}
+				if (not Proc::set_priority(s_pid, selected_nice)) {
+					// TODO: show error message
+				}
+			}
+			return Closed;
+		}
+		else if (key.size() == 1 and (isdigit(key.at(0)) or (key.at(0) == '-' and nice_edit.empty()))) {
+			nice_edit += key;
+		}
+		else if (key == "backspace" and not nice_edit.empty()) {
+			nice_edit.pop_back();
+		}
+		else if (is_in(key, "up", "k")) {
+			if (++selected_nice > 19) selected_nice = -20;
+			nice_edit.clear();
+		}
+		else if (is_in(key, "down", "j")) {
+			if (--selected_nice < -20) selected_nice = 19;
+			nice_edit.clear();
+		}
+		else if (is_in(key, "left", "h")) {
+			if ((selected_nice -= 5) < -20) selected_nice += 40;
+			nice_edit.clear();
+		}
+		else if (is_in(key, "right", "l")) {
+			if ((selected_nice += 5) > 19) selected_nice -= 40;
+			nice_edit.clear();
+		}
+		else {
+			retval = NoChange;
+		}
+
+		if (retval == Changed) {
+			int cy = y+4;
+			if (not nice_edit.empty()) {
+				try {
+					selected_nice = stoi(nice_edit);
+				}
+				catch (...) { selected_nice = 0; }
+			}
+			out = bg + Mv::to(cy++, x+3) + Theme::c("main_fg") + Fx::ub
+				+ 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;
+
+			cy++;
+			out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust( "↑ ↓", 20, true) + Theme::c("main_fg") + Fx::ub + " | To change value.";
+			out += 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.";
+			out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust("0-9", 20) + Theme::c("main_fg") + Fx::ub + " | Enter manually.";
+			out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust("ENTER", 20) + Theme::c("main_fg") + Fx::ub + " | To set nice value.";
+			out += Mv::to(++cy, x+3) + Fx::b + Theme::c("hi_fg") + rjust("ESC or 'q'", 20) + Theme::c("main_fg") + Fx::ub + " | To abort.";
+
+			out += Fx::reset;
+		}
+
+		return (redraw ? Changed : retval);
+	}
+
+	//* Add menus here and update enum Menus in header
+	const auto menuFunc = vector{
+		ref(sizeError),
+		ref(signalChoose),
+		ref(signalSend),
+		ref(signalReturn),
+		ref(optionsMenu),
+		ref(helpMenu),
+		ref(reniceMenu),
+		ref(mainMenu),
+	};
+	bitset<8> menuMask;
+
+	void process(const std::string_view key) {
+		if (menuMask.none()) {
+			Menu::active = false;
+			Global::overlay.clear();
+			Global::overlay.shrink_to_fit();
+			Runner::pause_output = false;
+			bg.clear();
+			bg.shrink_to_fit();
+			currentMenu = -1;
+			Runner::run("all", true, true);
+			mouse_mappings.clear();
+			return;
+		}
+
+		if (currentMenu < 0 or not menuMask.test(currentMenu)) {
+			Menu::active = true;
+			redraw = true;
+			if (((menuMask.test(Main) or menuMask.test(Options) or menuMask.test(Help) or menuMask.test(SignalChoose))
+			and (Term::width < 80 or Term::height < 24))
+			or (Term::width < 50 or Term::height < 20)) {
+				menuMask.reset();
+				menuMask.set(SizeError);
+			}
+
+			for (const auto& i : iota(0, (int)menuMask.size())) {
+				if (menuMask.test(i)) currentMenu = i;
+			}
+
+		}
+
+		auto retCode = menuFunc.at(currentMenu)(key.data());
+		if (retCode == Closed) {
+			menuMask.reset(currentMenu);
+			mouse_mappings.clear();
+			bg.clear();
+			Runner::pause_output = false;
+			process();
+		}
+		else if (redraw) {
+			redraw = false;
+			Runner::run("all", true, true);
+		}
+		else if (retCode == Changed)
+			Runner::run("overlay");
+		else if (retCode == Switch) {
+			Runner::pause_output = false;
+			bg.clear();
+			redraw = true;
+			mouse_mappings.clear();
+			process();
+		}
+	}
+
+	void show(int menu, int signal) {
+		menuMask.set(menu);
+		signalToSend = signal;
+		process();
+	}
+}

+ 99 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_menu.hpp

@@ -0,0 +1,99 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#pragma once
+
+#include <atomic>
+#include <bitset>
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include "btop_input.hpp"
+
+using std::atomic;
+using std::bitset;
+using std::string;
+using std::vector;
+
+namespace Menu {
+
+	extern atomic<bool> active;
+	extern string output;
+	extern int signalToSend;
+	extern bool redraw;
+
+	//? line, col, height, width
+	extern std::unordered_map<string, Input::Mouse_loc> mouse_mappings;
+
+	//* Creates a message box centered on screen
+	//? Height of box is determined by size of content vector
+	//? Boxtypes: 0 = OK button | 1 = YES and NO with YES selected | 2 = Same as 1 but with NO selected
+	//? Strings in content vector is not checked for box width overflow
+	class msgBox {
+		string box_contents, button_left, button_right;
+		int height{};
+		int width{};
+		int boxtype{};
+		int selected{};
+		int x{};
+		int y{};
+	public:
+		enum BoxTypes { OK, YES_NO, NO_YES };
+		enum msgReturn {
+			Invalid,
+			Ok_Yes,
+			No_Esc,
+			Select
+		};
+		msgBox();
+		msgBox(int width, int boxtype, const vector<string>& content, std::string_view title);
+
+		//? Draw and return box as a string
+		string operator()();
+
+		//? Process input and returns value from enum Ret
+		int input(const string& key);
+
+		//? Clears content vector and private strings
+		void clear();
+        int getX() const { return x; }
+        int getY() const { return y; }
+	};
+
+	extern bitset<8> menuMask;
+
+	//* Enum for functions in vector menuFuncs
+	enum Menus {
+		SizeError,
+		SignalChoose,
+		SignalSend,
+		SignalReturn,
+		Options,
+		Help,
+	    Renice,
+		Main
+	};
+
+	//* Handles redirection of input for menu functions and handles return codes
+	void process(const std::string_view key = "");
+
+	//* Show a menu from enum Menu::Menus
+	void show(int menu, int signal=-1);
+
+}

+ 292 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_shared.cpp

@@ -0,0 +1,292 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#include <sys/resource.h>
+#include <filesystem>
+#include <fstream>
+#include <ranges>
+#include <regex>
+#include <string>
+
+#include "btop_config.hpp"
+#include "btop_shared.hpp"
+#include "btop_tools.hpp"
+
+namespace fs = std::filesystem;
+namespace rng = std::ranges;
+using namespace Tools;
+
+namespace Cpu {
+    std::optional<std::string> container_engine;
+
+	string trim_name(string name) {
+		auto name_vec = ssplit(name);
+
+		if ((name.contains("Xeon") or v_contains(name_vec, "Duo"s)) and v_contains(name_vec, "CPU"s)) {
+			auto cpu_pos = v_index(name_vec, "CPU"s);
+			if (cpu_pos < name_vec.size() - 1 and not name_vec.at(cpu_pos + 1).ends_with(')'))
+				name = name_vec.at(cpu_pos + 1);
+			else
+				name.clear();
+		} else if (v_contains(name_vec, "Ryzen"s)) {
+			auto ryz_pos = v_index(name_vec, "Ryzen"s);
+			name = "Ryzen";
+			int tokens = 0;
+			for (auto i = ryz_pos + 1; i < name_vec.size() && tokens < 2; i++) {
+				const std::string& p = name_vec.at(i);
+				if (p != "AI" && p != "PRO" && p != "H" && p != "HX")
+					tokens++;
+				name += " " + p;
+			}
+		} else if (name.contains("Intel") and v_contains(name_vec, "CPU"s)) {
+			auto cpu_pos = v_index(name_vec, "CPU"s);
+			if (cpu_pos < name_vec.size() - 1 and not name_vec.at(cpu_pos + 1).ends_with(')') and name_vec.at(cpu_pos + 1) != "@")
+				name = name_vec.at(cpu_pos + 1);
+			else
+				name.clear();
+		} else
+			name.clear();
+
+		if (name.empty() and not name_vec.empty()) {
+			for (const auto &n : name_vec) {
+				if (n == "@") break;
+				name += n + ' ';
+			}
+			name.pop_back();
+			for (const auto& replace : {"Processor", "CPU", "(R)", "(TM)", "Intel", "AMD", "Apple", "Core"}) {
+				name = s_replace(name, replace, "");
+				name = s_replace(name, "  ", " ");
+			}
+			name = trim(name);
+		}
+
+		return name;
+	}
+}
+
+#ifdef GPU_SUPPORT
+namespace Gpu {
+	vector<string> gpu_names;
+	vector<int> gpu_b_height_offsets;
+	std::unordered_map<string, deque<long long>> shared_gpu_percent = {
+		{"gpu-average", {}},
+		{"gpu-vram-total", {}},
+		{"gpu-pwr-total", {}},
+	};
+	long long gpu_pwr_total_max = 0;
+}
+#endif
+
+namespace Proc {
+bool set_priority(pid_t pid, int priority) {
+  if (setpriority(PRIO_PROCESS, pid, priority) == 0) {
+    return true;
+  }
+  return false;
+}
+
+	void proc_sorter(vector<proc_info>& proc_vec, const string& sorting, bool reverse, bool tree) {
+		if (reverse) {
+			switch (v_index(sort_vector, sorting)) {
+			case 0: rng::stable_sort(proc_vec, rng::less{}, &proc_info::pid); 		break;
+			case 1: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::name);		break;
+			case 2: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::cmd); 		break;
+			case 3: rng::stable_sort(proc_vec, rng::less{}, &proc_info::threads);	break;
+			case 4: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::user); 		break;
+			case 5: rng::stable_sort(proc_vec, rng::less{}, &proc_info::mem); 		break;
+			case 6: rng::stable_sort(proc_vec, rng::less{}, &proc_info::cpu_p);		break;
+			case 7: rng::stable_sort(proc_vec, rng::less{}, &proc_info::cpu_c);		break;
+			}
+		}
+		else {
+			switch (v_index(sort_vector, sorting)) {
+			case 0: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::pid); 		break;
+			case 1: rng::stable_sort(proc_vec, rng::less{}, &proc_info::name);		break;
+			case 2: rng::stable_sort(proc_vec, rng::less{}, &proc_info::cmd); 		break;
+			case 3: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::threads);	break;
+			case 4: rng::stable_sort(proc_vec, rng::less{}, &proc_info::user);		break;
+			case 5: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::mem); 		break;
+			case 6: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::cpu_p);   	break;
+			case 7: rng::stable_sort(proc_vec, rng::greater{}, &proc_info::cpu_c);   	break;
+			}
+		}
+
+		//* When sorting with "cpu lazy" push processes over threshold cpu usage to the front regardless of cumulative usage
+		if (not tree and not reverse and sorting == "cpu lazy") {
+			double max = 10.0, target = 30.0;
+			for (size_t i = 0, x = 0, offset = 0; i < proc_vec.size(); i++) {
+				if (i <= 5 and proc_vec.at(i).cpu_p > max)
+					max = proc_vec.at(i).cpu_p;
+				else if (i == 6)
+					target = (max > 30.0) ? max : 10.0;
+				if (i == offset and proc_vec.at(i).cpu_p > 30.0)
+					offset++;
+				else if (proc_vec.at(i).cpu_p > target) {
+					rotate(proc_vec.begin() + offset, proc_vec.begin() + i, proc_vec.begin() + i + 1);
+					if (++x > 10) break;
+				}
+			}
+		}
+	}
+
+	void tree_sort(vector<tree_proc>& proc_vec, const string& sorting, bool reverse, bool paused, int& c_index, const int index_max, bool collapsed) {
+		if (proc_vec.size() > 1 and not paused) {
+			if (reverse) {
+				switch (v_index(sort_vector, sorting)) {
+				case 3: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().threads < b.entry.get().threads; });	break;
+				case 5: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().mem < b.entry.get().mem; });	break;
+				case 6: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_p < b.entry.get().cpu_p; });	break;
+				case 7: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_c < b.entry.get().cpu_c; });	break;
+				}
+			}
+			else {
+				switch (v_index(sort_vector, sorting)) {
+				case 3: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().threads > b.entry.get().threads; });	break;
+				case 5: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().mem > b.entry.get().mem; });	break;
+				case 6: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_p > b.entry.get().cpu_p; });	break;
+				case 7: rng::stable_sort(proc_vec, [](const auto& a, const auto& b) { return a.entry.get().cpu_c > b.entry.get().cpu_c; });	break;
+				}
+			}
+		}
+
+		for (auto& r : proc_vec) {
+			r.entry.get().tree_index = (collapsed or r.entry.get().filtered ? index_max : c_index++);
+			if (not r.children.empty()) {
+				tree_sort(r.children, sorting, reverse, paused, c_index, (collapsed or r.entry.get().collapsed or r.entry.get().tree_index == (size_t)index_max));
+			}
+		}
+	}
+
+	auto matches_filter(const proc_info& proc, const std::string& filter) -> bool {
+		if (filter.starts_with("!")) {
+			if (filter.size() == 1) {
+				return true;
+			}
+
+			// An incomplete regex throws, see issue https://github.com/aristocratos/btop/issues/1133
+			try {
+				std::regex regex { filter.substr(1), std::regex::extended };
+				return std::regex_search(std::to_string(proc.pid), regex) || std::regex_search(proc.name, regex) ||
+							 std::regex_match(proc.cmd, regex) || std::regex_search(proc.user, regex);
+			} catch (std::regex_error& /* unused */) {
+				return false;
+			}
+		}
+
+		return std::to_string(proc.pid).contains(filter) || s_contains_ic(proc.name, filter) ||
+					 s_contains_ic(proc.cmd, filter) || s_contains_ic(proc.user, filter);
+	}
+
+	void _tree_gen(proc_info& cur_proc, vector<proc_info>& in_procs, vector<tree_proc>& out_procs,
+		int cur_depth, bool collapsed, const string& filter, bool found, bool no_update, bool should_filter) {
+		bool filtering = false;
+
+		//? If filtering, include children of matching processes
+		if (not found and (should_filter or not filter.empty())) {
+			if (!matches_filter(cur_proc, filter)) {
+				filtering = true;
+				cur_proc.filtered = true;
+				filter_found++;
+			}
+			else {
+				found = true;
+				cur_depth = 0;
+			}
+		}
+		else if (cur_proc.filtered) cur_proc.filtered = false;
+
+		cur_proc.depth = cur_depth;
+
+		//? Set tree index position for process if not filtered out or currently in a collapsed sub-tree
+		out_procs.push_back({ cur_proc, {} });
+		if (not collapsed and not filtering) {
+			cur_proc.tree_index = out_procs.size() - 1;
+
+			//? Try to find name of the binary file and append to program name if not the same
+			if (cur_proc.short_cmd.empty() and not cur_proc.cmd.empty()) {
+				std::string_view cmd_view = cur_proc.cmd;
+				cmd_view = cmd_view.substr((size_t)0, std::min(cmd_view.find(' '), cmd_view.size()));
+				cmd_view = cmd_view.substr(std::min(cmd_view.find_last_of('/') + 1, cmd_view.size()));
+				cur_proc.short_cmd = string{cmd_view};
+			}
+		}
+		else {
+			cur_proc.tree_index = in_procs.size();
+		}
+
+		//? Recursive iteration over all children
+		for (auto& p : rng::equal_range(in_procs, cur_proc.pid, rng::less{}, &proc_info::ppid)) {
+			if (collapsed and not filtering) {
+				cur_proc.filtered = true;
+			}
+
+			_tree_gen(p, in_procs, out_procs.back().children, cur_depth + 1, (collapsed or cur_proc.collapsed), filter, found, no_update, should_filter);
+
+			if (not no_update and not filtering and (collapsed or cur_proc.collapsed)) {
+				//auto& parent = cur_proc;
+				if (p.state != 'X') {
+					cur_proc.cpu_p += p.cpu_p;
+					cur_proc.cpu_c += p.cpu_c;
+					cur_proc.mem += p.mem;
+					cur_proc.threads += p.threads;
+				}
+				filter_found++;
+				p.filtered = true;
+			}
+			else if (Config::getB("proc_aggregate") and p.state != 'X') {
+				cur_proc.cpu_p += p.cpu_p;
+				cur_proc.cpu_c += p.cpu_c;
+				cur_proc.mem += p.mem;
+				cur_proc.threads += p.threads;
+			}
+		}
+	}
+
+	void _collect_prefixes(tree_proc &t, const bool is_last, const string &header) {
+		const bool is_filtered = t.entry.get().filtered;
+		if (is_filtered) t.entry.get().depth = 0;
+
+		if (!t.children.empty()) t.entry.get().prefix = header + (t.entry.get().collapsed ? "[+]─": "[-]─");
+		else t.entry.get().prefix = header + (is_last ? " └─": " ├─");
+
+		for (auto child = t.children.begin(); child != t.children.end(); ++child) {
+			_collect_prefixes(*child, child == (t.children.end() - 1),
+				is_filtered ? "": header + (is_last ? "   ": " │ "));
+		}
+	}
+}
+
+auto detect_container() -> std::optional<std::string> {
+    std::error_code err;
+
+    if (fs::exists(fs::path("/run/.containerenv"), err)) {
+        return std::make_optional(std::string { "podman" });
+    }
+    if (fs::exists(fs::path("/.dockerenv"), err)) {
+        return std::make_optional(std::string { "docker" });
+    }
+    auto systemd_container = fs::path("/run/systemd/container");
+    if (fs::exists(systemd_container, err)) {
+        auto stream = std::ifstream { systemd_container };
+        auto buf = std::string {};
+        stream >> buf;
+        return std::make_optional(buf);
+    }
+
+    return std::nullopt;
+}

+ 461 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_shared.hpp

@@ -0,0 +1,461 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#pragma once
+
+#include <array>
+#include <atomic>
+#include <cstdint>
+#include <deque>
+#include <filesystem>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <tuple>
+#include <unordered_map>
+#include <vector>
+
+#include <unistd.h>
+
+// From `man 3 getifaddrs`: <net/if.h> must be included before <ifaddrs.h>
+// clang-format off
+#include <net/if.h>
+#include <ifaddrs.h>
+// clang-format on
+
+#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
+# include <kvm.h>
+#endif
+
+using std::array;
+using std::atomic;
+using std::deque;
+using std::string;
+using std::tuple;
+using std::vector;
+
+using namespace std::literals; // for operator""s
+
+void term_resize(bool force=false);
+void banner_gen();
+
+extern void clean_quit(int sig);
+
+namespace Global {
+	extern const vector<array<string, 2>> Banner_src;
+	extern const string Version;
+	extern atomic<bool> quitting;
+	extern string exit_error_msg;
+	extern atomic<bool> thread_exception;
+	extern string banner;
+	extern atomic<bool> resized;
+	extern string overlay;
+	extern string clock;
+	extern uid_t real_uid, set_uid;
+	extern atomic<bool> init_conf;
+}
+
+namespace Runner {
+	extern atomic<bool> active;
+	extern atomic<bool> reading;
+	extern atomic<bool> stopping;
+	extern atomic<bool> redraw;
+	extern atomic<bool> coreNum_reset;
+	extern pthread_t runner_id;
+	extern bool pause_output;
+	extern string debug_bg;
+
+	void run(const string& box="", bool no_update = false, bool force_redraw = false);
+	void stop();
+
+}
+
+namespace Tools {
+	//* Platform specific function for system_uptime (seconds since last restart)
+	double system_uptime();
+}
+
+namespace Shared {
+	//* Initialize platform specific needed variables and check for errors
+	void init();
+
+	extern long coreCount, page_size, clk_tck;
+
+#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
+	struct KvmDeleter {
+		void operator()(kvm_t* handle) {
+			kvm_close(handle);
+		}
+	};
+	using KvmPtr = std::unique_ptr<kvm_t, KvmDeleter>;
+#endif
+}
+
+
+namespace Gpu {
+#ifdef GPU_SUPPORT
+	extern vector<string> box;
+	extern int width, total_height, min_width, min_height;
+	extern vector<int> x_vec, y_vec;
+	extern vector<bool> redraw;
+	extern int shown;
+	extern int count;
+	extern vector<int> shown_panels;
+	extern vector<string> gpu_names;
+	extern vector<int> gpu_b_height_offsets;
+	extern long long gpu_pwr_total_max;
+
+	extern std::unordered_map<string, deque<long long>> shared_gpu_percent; // averages, power/vram total
+
+	const array mem_names { "used"s, "free"s };
+
+	//* Container for process information // TODO
+	/*struct proc_info {
+    unsigned int pid;
+    unsigned long long mem;
+	};*/
+
+	//* Container for supported Gpu::*::collect() functions
+	struct gpu_info_supported {
+		bool gpu_utilization = true,
+		   	 mem_utilization = true,
+				 gpu_clock = true,
+				 mem_clock = true,
+				 pwr_usage = true,
+				 pwr_state = true,
+				 temp_info = true,
+				 mem_total = true,
+				 mem_used = true,
+				 pcie_txrx = true,
+				 encoder_utilization = true,
+				 decoder_utilization = true;
+	};
+
+	//* Per-device container for GPU info
+	struct gpu_info {
+		std::unordered_map<string, deque<long long>> gpu_percent = {
+			{"gpu-totals", {}},
+			{"gpu-vram-totals", {}},
+			{"gpu-pwr-totals", {}},
+		};
+		unsigned int gpu_clock_speed; // MHz
+
+		long long pwr_usage; // mW
+		long long pwr_max_usage = 255000;
+		long long pwr_state;
+
+		deque<long long> temp = {0};
+		long long temp_max = 110;
+
+		long long mem_total = 0;
+		long long mem_used = 0;
+		deque<long long> mem_utilization_percent = {0}; // TODO: properly handle GPUs that can't report some stats
+		long long mem_clock_speed = 0; // MHz
+
+		long long pcie_tx = 0; // KB/s
+		long long pcie_rx = 0;
+
+		long long encoder_utilization = 0;
+		long long decoder_utilization = 0;
+
+		gpu_info_supported supported_functions;
+
+		// vector<proc_info> graphics_processes = {}; // TODO
+		// vector<proc_info> compute_processes = {};
+	};
+
+	namespace Nvml {
+		extern bool shutdown();
+	}
+	namespace Rsmi {
+		extern bool shutdown();
+	}
+
+	//* Collect gpu stats and temperatures
+    auto collect(bool no_update = false) -> vector<gpu_info>&;
+
+	//* Draw contents of gpu box using <gpus> as source
+  	string draw(const gpu_info& gpu, unsigned long index, bool force_redraw, bool data_same);
+#else
+	struct gpu_info {
+		bool supported = false;
+	};
+#endif
+}
+
+namespace Cpu {
+	extern string box;
+	extern int x, y, width, height, min_width, min_height;
+	extern bool shown, redraw, got_sensors, cpu_temp_only, has_battery, supports_watts;
+	extern string cpuName, cpuHz;
+	extern vector<string> available_fields;
+	extern vector<string> available_sensors;
+	extern tuple<int, float, long, string> current_bat;
+	extern std::optional<std::string> container_engine;
+
+	struct cpu_info {
+		std::unordered_map<string, deque<long long>> cpu_percent = {
+			{"total", {}},
+			{"user", {}},
+			{"nice", {}},
+			{"system", {}},
+			{"idle", {}},
+			{"iowait", {}},
+			{"irq", {}},
+			{"softirq", {}},
+			{"steal", {}},
+			{"guest", {}},
+			{"guest_nice", {}}
+		};
+		vector<deque<long long>> core_percent;
+		vector<deque<long long>> temp;
+		long long temp_max = 0;
+		array<double, 3> load_avg;
+		float usage_watts = 0;
+		std::optional<std::vector<std::int32_t>> active_cpus;
+	};
+
+	//* Collect cpu stats and temperatures
+	auto collect(bool no_update = false) -> cpu_info&;
+
+	//* Draw contents of cpu box using <cpu> as source
+    string draw(const cpu_info& cpu, const vector<Gpu::gpu_info>& gpu, bool force_redraw = false, bool data_same = false);
+
+	//* Parse /proc/cpu info for mapping of core ids
+	auto get_core_mapping() -> std::unordered_map<int, int>;
+	extern std::unordered_map<int, int> core_mapping;
+
+	auto get_cpuHz() -> string;
+
+	//* Get battery info from /sys
+	auto get_battery() -> tuple<int, float, long, string>;
+
+	string trim_name(string);
+}
+
+namespace Mem {
+	extern string box;
+	extern int x, y, width, height, min_width, min_height;
+	extern bool has_swap, shown, redraw;
+	const array mem_names { "used"s, "available"s, "cached"s, "free"s };
+	const array swap_names { "swap_used"s, "swap_free"s };
+	extern int disk_ios;
+
+	struct disk_info {
+		std::filesystem::path dev;
+		string name;
+		string fstype{};                // defaults to ""
+		std::filesystem::path stat{};   // defaults to ""
+		int64_t total{};
+		int64_t used{};
+		int64_t free{};
+		int used_percent{};
+		int free_percent{};
+
+		array<int64_t, 3> old_io = {0, 0, 0};
+		deque<long long> io_read = {};
+		deque<long long> io_write = {};
+		deque<long long> io_activity = {};
+	};
+
+	struct mem_info {
+		std::unordered_map<string, uint64_t> stats =
+			{{"used", 0}, {"available", 0}, {"cached", 0}, {"free", 0},
+			{"swap_total", 0}, {"swap_used", 0}, {"swap_free", 0}};
+		std::unordered_map<string, deque<long long>> percent =
+			{{"used", {}}, {"available", {}}, {"cached", {}}, {"free", {}},
+			{"swap_total", {}}, {"swap_used", {}}, {"swap_free", {}}};
+		std::unordered_map<string, disk_info> disks;
+		vector<string> disks_order;
+	};
+
+	//?* Get total system memory
+	uint64_t get_totalMem();
+
+	//* Collect mem & disks stats
+	auto collect(bool no_update = false) -> mem_info&;
+
+	//* Draw contents of mem box using <mem> as source
+	string draw(const mem_info& mem, bool force_redraw = false, bool data_same = false);
+
+}
+
+namespace Net {
+	extern string box;
+	extern int x, y, width, height, min_width, min_height;
+	extern bool shown, redraw;
+	extern string selected_iface;
+	extern vector<string> interfaces;
+	extern bool rescale;
+	extern std::unordered_map<string, uint64_t> graph_max;
+
+	struct net_stat {
+		uint64_t speed{};
+		uint64_t top{};
+		uint64_t total{};
+		uint64_t last{};
+		uint64_t offset{};
+		uint64_t rollover{};
+	};
+
+	struct net_info {
+		std::unordered_map<string, deque<long long>> bandwidth = { {"download", {}}, {"upload", {}} };
+		std::unordered_map<string, net_stat> stat = { {"download", {}}, {"upload", {}} };
+		string ipv4{};      // defaults to ""
+		string ipv6{};      // defaults to ""
+		bool connected{};
+	};
+
+	class IfAddrsPtr {
+		struct ifaddrs* ifaddr;
+		int status;
+	public:
+		IfAddrsPtr() { status = getifaddrs(&ifaddr); }
+		~IfAddrsPtr() noexcept { freeifaddrs(ifaddr); }
+		IfAddrsPtr(const IfAddrsPtr &) = delete;
+		IfAddrsPtr& operator=(IfAddrsPtr& other) = delete;
+		IfAddrsPtr(IfAddrsPtr &&) = delete;
+		IfAddrsPtr& operator=(IfAddrsPtr&& other) = delete;
+		[[nodiscard]] constexpr auto operator()() -> struct ifaddrs* { return ifaddr; }
+		[[nodiscard]] constexpr auto get() -> struct ifaddrs* { return ifaddr; }
+		[[nodiscard]] constexpr auto get_status() const noexcept -> int { return status; };
+	};
+
+	extern std::unordered_map<string, net_info> current_net;
+
+	//* Collect net upload/download stats
+	auto collect(bool no_update=false) -> net_info&;
+
+	//* Draw contents of net box using <net> as source
+	string draw(const net_info& net, bool force_redraw = false, bool data_same = false);
+}
+
+namespace Proc {
+	extern atomic<int> numpids;
+
+	extern string box;
+	extern int x, y, width, height, min_width, min_height;
+	extern bool shown, redraw;
+	extern int select_max;
+	extern atomic<int> detailed_pid;
+	extern int selected_pid, start, selected, collapse, expand, filter_found, selected_depth, toggle_children;
+	extern string selected_name;
+
+	//? Contains the valid sorting options for processes
+	const vector<string> sort_vector = {
+		"pid",
+		"name",
+		"command",
+		"threads",
+		"user",
+		"memory",
+		"cpu direct",
+		"cpu lazy",
+	};
+
+	//? Translation from process state char to explanative string
+	const std::unordered_map<char, string> proc_states = {
+		{'R', "Running"},
+		{'S', "Sleeping"},
+		{'D', "Waiting"},
+		{'Z', "Zombie"},
+		{'T', "Stopped"},
+		{'t', "Tracing"},
+		{'X', "Dead"},
+		{'x', "Dead"},
+		{'K', "Wakekill"},
+		{'W', "Unknown"},
+		{'P', "Parked"}
+	};
+
+	//* Container for process information
+	struct proc_info {
+		size_t pid{};
+		string name{};          // defaults to ""
+		string cmd{};           // defaults to ""
+		string short_cmd{};     // defaults to ""
+		size_t threads{};
+		int name_offset{};
+		string user{};          // defaults to ""
+		uint64_t mem{};
+		double cpu_p{};         // defaults to = 0.0
+		double cpu_c{};         // defaults to = 0.0
+		char state = '0';
+		int64_t p_nice{};
+		uint64_t ppid{};
+		uint64_t cpu_s{};
+		uint64_t cpu_t{};
+		uint64_t death_time{};
+		string prefix{};        // defaults to ""
+		size_t depth{};
+		size_t tree_index{};
+		bool collapsed{};
+		bool filtered{};
+	};
+
+	//* Container for process info box
+	struct detail_container {
+		size_t last_pid{};
+		bool skip_smaps{};
+		proc_info entry;
+		string elapsed, parent, status, io_read, io_write, memory;
+		long long first_mem = -1;
+		deque<long long> cpu_percent;
+		deque<long long> mem_bytes;
+	};
+
+	//? Contains all info for proc detailed box
+	extern detail_container detailed;
+
+	//* Collect and sort process information from /proc
+	auto collect(bool no_update = false) -> vector<proc_info>&;
+
+	//* Update current selection and view, returns -1 if no change otherwise the current selection
+	int selection(const std::string_view cmd_key);
+
+	//* Draw contents of proc box using <plist> as data source
+	string draw(const vector<proc_info>& plist, bool force_redraw = false, bool data_same = false);
+
+	struct tree_proc {
+		std::reference_wrapper<proc_info> entry;
+		vector<tree_proc> children;
+	};
+
+	//* Change priority (nice) of pid, returns true on success otherwise false
+	bool set_priority(pid_t pid, int priority);
+
+	//* Sort vector of proc_info's
+	void proc_sorter(vector<proc_info>& proc_vec, const string& sorting, bool reverse, bool tree = false);
+
+	//* Recursive sort of process tree
+	void tree_sort(vector<tree_proc>& proc_vec, const string& sorting, bool reverse, bool paused,
+					int& c_index, const int index_max, bool collapsed = false);
+
+	auto matches_filter(const proc_info& proc, const std::string& filter) -> bool;
+
+	//* Generate process tree list
+	void _tree_gen(proc_info& cur_proc, vector<proc_info>& in_procs, vector<tree_proc>& out_procs,
+				   int cur_depth, bool collapsed, const string& filter,
+				   bool found = false, bool no_update = false, bool should_filter = false);
+
+	//* Build prefixes for tree view
+	void _collect_prefixes(tree_proc& t, bool is_last, const string &header = "");
+}
+
+/// Detect container engine.
+auto detect_container() -> std::optional<std::string>;

+ 454 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_theme.cpp

@@ -0,0 +1,454 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#include <cmath>
+#include <fstream>
+#include <unistd.h>
+
+#include "btop_tools.hpp"
+#include "btop_config.hpp"
+#include "btop_theme.hpp"
+
+using std::round;
+using std::stoi;
+using std::to_string;
+using std::vector;
+using std::views::iota;
+
+using namespace Tools;
+
+namespace fs = std::filesystem;
+
+string Term::fg, Term::bg;
+string Fx::reset = reset_base;
+
+namespace Theme {
+
+	fs::path theme_dir;
+	fs::path user_theme_dir;
+	fs::path custom_theme_dir;
+	vector<string> themes;
+	std::unordered_map<string, string> colors;
+	std::unordered_map<string, array<int, 3>> rgbs;
+	std::unordered_map<string, array<string, 101>> gradients;
+
+	const std::unordered_map<string, string> Default_theme = {
+		{ "main_bg", "#00" },
+		{ "main_fg", "#cc" },
+		{ "title", "#ee" },
+		{ "hi_fg", "#b54040" },
+		{ "selected_bg", "#6a2f2f" },
+		{ "selected_fg", "#ee" },
+		{ "inactive_fg", "#40" },
+		{ "graph_text", "#60" },
+		{ "meter_bg", "#40" },
+		{ "proc_misc", "#0de756" },
+		{ "cpu_box", "#556d59" },
+		{ "mem_box", "#6c6c4b" },
+		{ "net_box", "#5c588d" },
+		{ "proc_box", "#805252" },
+		{ "div_line", "#30" },
+		{ "temp_start", "#4897d4" },
+		{ "temp_mid", "#5474e8" },
+		{ "temp_end", "#ff40b6" },
+		{ "cpu_start", "#77ca9b" },
+		{ "cpu_mid", "#cbc06c" },
+		{ "cpu_end", "#dc4c4c" },
+		{ "free_start", "#384f21" },
+		{ "free_mid", "#b5e685" },
+		{ "free_end", "#dcff85" },
+		{ "cached_start", "#163350" },
+		{ "cached_mid", "#74e6fc" },
+		{ "cached_end", "#26c5ff" },
+		{ "available_start", "#4e3f0e" },
+		{ "available_mid", "#ffd77a" },
+		{ "available_end", "#ffb814" },
+		{ "used_start", "#592b26" },
+		{ "used_mid", "#d9626d" },
+		{ "used_end", "#ff4769" },
+		{ "download_start", "#291f75" },
+		{ "download_mid", "#4f43a3" },
+		{ "download_end", "#b0a9de" },
+		{ "upload_start", "#620665" },
+		{ "upload_mid", "#7d4180" },
+		{ "upload_end", "#dcafde" },
+		{ "process_start", "#80d0a3" },
+		{ "process_mid", "#dcd179" },
+		{ "process_end", "#d45454" },
+		{ "proc_pause_bg", "#b54040" }
+	};
+
+	const std::unordered_map<string, string> TTY_theme = {
+		{ "main_bg", "\x1b[0;40m" },
+		{ "main_fg", "\x1b[37m" },
+		{ "title", "\x1b[97m" },
+		{ "hi_fg", "\x1b[91m" },
+		{ "selected_bg", "\x1b[41m" },
+		{ "selected_fg", "\x1b[97m" },
+		{ "inactive_fg", "\x1b[90m" },
+		{ "graph_text", "\x1b[90m" },
+		{ "meter_bg", "\x1b[90m" },
+		{ "proc_misc", "\x1b[92m" },
+		{ "cpu_box", "\x1b[32m" },
+		{ "mem_box", "\x1b[33m" },
+		{ "net_box", "\x1b[35m" },
+		{ "proc_box", "\x1b[31m" },
+		{ "div_line", "\x1b[90m" },
+		{ "temp_start", "\x1b[94m" },
+		{ "temp_mid", "\x1b[96m" },
+		{ "temp_end", "\x1b[95m" },
+		{ "cpu_start", "\x1b[92m" },
+		{ "cpu_mid", "\x1b[93m" },
+		{ "cpu_end", "\x1b[91m" },
+		{ "free_start", "\x1b[32m" },
+		{ "free_mid", "" },
+		{ "free_end", "\x1b[92m" },
+		{ "cached_start", "\x1b[36m" },
+		{ "cached_mid", "" },
+		{ "cached_end", "\x1b[96m" },
+		{ "available_start", "\x1b[33m" },
+		{ "available_mid", "" },
+		{ "available_end", "\x1b[93m" },
+		{ "used_start", "\x1b[31m" },
+		{ "used_mid", "" },
+		{ "used_end", "\x1b[91m" },
+		{ "download_start", "\x1b[34m" },
+		{ "download_mid", "" },
+		{ "download_end", "\x1b[94m" },
+		{ "upload_start", "\x1b[35m" },
+		{ "upload_mid", "" },
+		{ "upload_end", "\x1b[95m" },
+		{ "process_start", "\x1b[32m" },
+		{ "process_mid", "\x1b[33m" },
+		{ "process_end", "\x1b[31m" },
+		{ "proc_pause_bg", "\x1b[41m" },
+	};
+
+	namespace {
+		//* Convert 24-bit colors to 256 colors
+		int truecolor_to_256(const int& r, const int& g, const int& b) {
+			//? Use upper 232-255 greyscale values if the downscaled red, green and blue are the same value
+			if (const int red = round((double)r / 11); red == round((double)g / 11) and red == round((double)b / 11)) {
+				return 232 + red;
+			}
+			//? Else use 6x6x6 color cube to calculate approximate colors
+			else {
+				return round((double)r / 51) * 36 + round((double)g / 51) * 6 + round((double)b / 51) + 16;
+			}
+		}
+	}
+
+	string hex_to_color(string hexa, bool t_to_256, const string& depth) {
+		if (hexa.size() > 1) {
+			hexa.erase(0, 1);
+			for (auto& c : hexa) {
+				if (not isxdigit(c)) {
+					Logger::error("Invalid hex value: " + hexa);
+					return "";
+				}
+			}
+			string pre = Fx::e + (depth == "fg" ? "38" : "48") + ";" + (t_to_256 ? "5;" : "2;");
+
+			if (hexa.size() == 2) {
+				int h_int = stoi(hexa, nullptr, 16);
+				if (t_to_256) {
+					return pre + to_string(truecolor_to_256(h_int, h_int, h_int)) + "m";
+				} else {
+					string h_str = to_string(h_int);
+					return pre + h_str + ";" + h_str + ";" + h_str + "m";
+				}
+			}
+			else if (hexa.size() == 6) {
+				if (t_to_256) {
+					return pre + to_string(truecolor_to_256(
+						stoi(hexa.substr(0, 2), nullptr, 16),
+						stoi(hexa.substr(2, 2), nullptr, 16),
+						stoi(hexa.substr(4, 2), nullptr, 16))) + "m";
+				} else {
+					return pre +
+						to_string(stoi(hexa.substr(0, 2), nullptr, 16)) + ";" +
+						to_string(stoi(hexa.substr(2, 2), nullptr, 16)) + ";" +
+						to_string(stoi(hexa.substr(4, 2), nullptr, 16)) + "m";
+				}
+			}
+			else Logger::error("Invalid size of hex value: " + hexa);
+		}
+		else Logger::error("Hex value missing: " + hexa);
+		return "";
+	}
+
+	string dec_to_color(int r, int g, int b, bool t_to_256, const string& depth) {
+		string pre = Fx::e + (depth == "fg" ? "38" : "48") + ";" + (t_to_256 ? "5;" : "2;");
+		r = std::clamp(r, 0, 255);
+		g = std::clamp(g, 0, 255);
+		b = std::clamp(b, 0, 255);
+		if (t_to_256) return pre + to_string(truecolor_to_256(r, g, b)) + "m";
+		else return pre + to_string(r) + ";" + to_string(g) + ";" + to_string(b) + "m";
+	}
+
+	namespace {
+		//* Convert hex color to a array of decimals
+		array<int, 3> hex_to_dec(string hexa) {
+			if (hexa.size() > 1) {
+				hexa.erase(0, 1);
+				for (auto& c : hexa) {
+					if (not isxdigit(c))
+						return array{-1, -1, -1};
+				}
+
+				if (hexa.size() == 2) {
+					int h_int = stoi(hexa, nullptr, 16);
+					return array{h_int, h_int, h_int};
+				}
+				else if (hexa.size() == 6) {
+						return array{
+							stoi(hexa.substr(0, 2), nullptr, 16),
+							stoi(hexa.substr(2, 2), nullptr, 16),
+							stoi(hexa.substr(4, 2), nullptr, 16)
+						};
+				}
+			}
+			return {-1 ,-1 ,-1};
+		}
+
+		//* Generate colors and rgb decimal vectors for the theme
+		void generateColors(const std::unordered_map<string, string>& source) {
+			vector<string> t_rgb;
+			string depth;
+			bool t_to_256 = Config::getB("lowcolor");
+			colors.clear(); rgbs.clear();
+			for (const auto& [name, color] : Default_theme) {
+				if (name == "main_bg" and not Config::getB("theme_background")) {
+						colors[name] = "\x1b[49m";
+						rgbs[name] = {-1, -1, -1};
+						continue;
+				}
+				depth = (name.ends_with("bg") and name != "meter_bg") ? "bg" : "fg";
+				if (source.contains(name)) {
+					if (name == "main_bg" and source.at(name).empty()) {
+						colors[name] = "\x1b[49m";
+						rgbs[name] = {-1, -1, -1};
+						continue;
+					}
+					else if (source.at(name).empty() and (name.ends_with("_mid") or name.ends_with("_end"))) {
+						colors[name] = "";
+						rgbs[name] = {-1, -1, -1};
+						continue;
+					}
+					else if (source.at(name).starts_with('#')) {
+						colors[name] = hex_to_color(source.at(name), t_to_256, depth);
+						rgbs[name] = hex_to_dec(source.at(name));
+					}
+					else if (not source.at(name).empty()) {
+						t_rgb = ssplit(source.at(name));
+						if (t_rgb.size() != 3) {
+							Logger::error("Invalid RGB decimal value: \"" + source.at(name) + "\"");
+						} else {
+							colors[name] = dec_to_color(stoi(t_rgb[0]), stoi(t_rgb[1]), stoi(t_rgb[2]), t_to_256, depth);
+							rgbs[name] = array{stoi(t_rgb[0]), stoi(t_rgb[1]), stoi(t_rgb[2])};
+
+						}
+					}
+				}
+				if (not colors.contains(name) and not is_in(name, "meter_bg", "process_start", "process_mid", "process_end", "graph_text")) {
+					Logger::debug("Missing color value for \"" + name + "\". Using value from default.");
+					colors[name] = hex_to_color(color, t_to_256, depth);
+					rgbs[name] = hex_to_dec(color);
+				}
+			}
+			//? Set fallback values for optional colors not defined in theme file
+			if (not colors.contains("meter_bg")) {
+				colors["meter_bg"] = colors.at("inactive_fg");
+				rgbs["meter_bg"] = rgbs.at("inactive_fg");
+			}
+			if (not colors.contains("process_start")) {
+				colors["process_start"] = colors.at("cpu_start");
+				colors["process_mid"] = colors.at("cpu_mid");
+				colors["process_end"] = colors.at("cpu_end");
+				rgbs["process_start"] = rgbs.at("cpu_start");
+				rgbs["process_mid"] = rgbs.at("cpu_mid");
+				rgbs["process_end"] = rgbs.at("cpu_end");
+			}
+			if (not colors.contains("graph_text")) {
+				colors["graph_text"] = colors.at("inactive_fg");
+				rgbs["graph_text"] = rgbs.at("inactive_fg");
+			}
+		}
+
+		//* Generate color gradients from two or three colors, 101 values indexed 0-100
+		void generateGradients() {
+			gradients.clear();
+			bool t_to_256 = Config::getB("lowcolor");
+
+			//? Insert values for processes greyscale gradient and processes color gradient
+			rgbs.insert({
+				{ "proc_start", 		rgbs["main_fg"]			},
+				{ "proc_mid", 			{-1, -1, -1}			},
+				{ "proc_end", 			rgbs["inactive_fg"]		},
+				{ "proc_color_start", 	rgbs["inactive_fg"]		},
+				{ "proc_color_mid", 	{-1, -1, -1}			},
+				{ "proc_color_end", 	rgbs["process_start"]	},
+			});
+
+			for (const auto& [name, source_arr] : rgbs) {
+				if (not name.ends_with("_start")) continue;
+				const string color_name { rtrim(name, "_start") };
+
+				//? input_colors[start,mid,end][red,green,blue]
+				const array<array<int, 3>, 3> input_colors = {
+					source_arr,
+					rgbs[color_name + "_mid"],
+					rgbs[color_name + "_end"]
+				};
+
+				//? output_colors[red,green,blue][0-100]
+				array<array<int, 3>, 101> output_colors;
+				output_colors[0][0] = -1;
+
+				//? Only start iteration if gradient has an end color defined
+				if (input_colors[2][0] >= 0) {
+
+					//? Split iteration in two passes of 50 + 51 instead of one pass of 101 if gradient has start, mid and end values defined
+					int current_range = (input_colors[1][0] >= 0) ? 50 : 100;
+					for (int rgb : iota(0, 3)) {
+						int start = 0, offset = 0;
+						int end = (current_range == 50) ? 1 : 2;
+						for (int i : iota(0, 101)) {
+							output_colors[i][rgb] = input_colors[start][rgb] + (i - offset) * (input_colors[end][rgb] - input_colors[start][rgb]) / current_range;
+
+							//? Switch source arrays from start->mid to mid->end at 50 passes if mid is defined
+							if (i == current_range) { ++start; ++end; offset = 50; }
+						}
+					}
+				}
+				//? Generate color escape codes for the generated rgb decimals
+				array<string, 101> color_gradient;
+				if (output_colors[0][0] != -1) {
+					for (int y = 0; const auto& [red, green, blue] : output_colors)
+						color_gradient[y++] = dec_to_color(red, green, blue, t_to_256);
+				}
+				else {
+					//? If only start was defined fill array with start color
+					color_gradient.fill(colors[name]);
+				}
+				gradients[color_name] = std::move(color_gradient);
+			}
+		}
+
+		//* Set colors and generate gradients for the TTY theme
+		void generateTTYColors() {
+			rgbs.clear();
+			gradients.clear();
+			colors = TTY_theme;
+			if (not Config::getB("theme_background"))
+				colors["main_bg"] = "\x1b[49m";
+
+			for (const auto& c : colors) {
+				if (not c.first.ends_with("_start")) continue;
+				const string base_name { rtrim(c.first, "_start") };
+				string section = "_start";
+				int split = colors.at(base_name + "_mid").empty() ? 50 : 33;
+				for (int i : iota(0, 101)) {
+					gradients[base_name][i] = colors.at(base_name + section);
+					if (i == split) {
+						section = (split == 33) ? "_mid" : "_end";
+						split *= 2;
+					}
+				}
+			}
+		}
+
+		//* Load a .theme file from disk
+		auto loadFile(const string& filename) {
+			const fs::path filepath = filename;
+			if (not fs::exists(filepath))
+				return Default_theme;
+
+			std::ifstream themefile(filepath);
+			if (themefile.good()) {
+				std::unordered_map<string, string> theme_out;
+				Logger::debug("Loading theme file: " + filename);
+				while (not themefile.bad()) {
+					if (themefile.peek() == '#') {
+						themefile.ignore(SSmax, '\n');
+						continue;
+					}
+					themefile.ignore(SSmax, '[');
+					if (themefile.eof()) break;
+					string name, value;
+					getline(themefile, name, ']');
+					if (not Default_theme.contains(name)) {
+						themefile.ignore(SSmax, '\n');
+						continue;
+					}
+					themefile.ignore(SSmax, '=');
+					themefile >> std::ws;
+					if (themefile.eof()) break;
+					if (themefile.peek() == '"') {
+						themefile.ignore(1);
+						getline(themefile, value, '"');
+						themefile.ignore(SSmax, '\n');
+					}
+					else getline(themefile, value, '\n');
+
+					theme_out[name] = value;
+				}
+				return theme_out;
+			}
+			return Default_theme;
+		}
+	}
+
+	void updateThemes() {
+		themes.clear();
+		themes.push_back("Default");
+		themes.push_back("TTY");
+
+		//? Priority: custom_theme_dir -> user_theme_dir -> theme_dir
+		for (const auto& path : { custom_theme_dir, user_theme_dir, theme_dir } ) {
+			if (path.empty()) continue;
+			for (auto& file : fs::directory_iterator(path)) {
+				if (file.path().extension() == ".theme" and access(file.path().c_str(), R_OK) != -1 and not v_contains(themes, file.path().c_str())) {
+					themes.push_back(file.path().c_str());
+				}
+			}
+		}
+
+	}
+
+	void setTheme() {
+		const auto& theme = Config::getS("color_theme");
+		fs::path theme_path;
+		for (const fs::path p : themes) {
+			if (p == theme or p.stem() == theme or p.filename() == theme) {
+				theme_path = p;
+				break;
+			}
+		}
+		if (theme == "TTY" or Config::getB("tty_mode"))
+			generateTTYColors();
+		else {
+			generateColors((theme == "Default" or theme_path.empty() ? Default_theme : loadFile(theme_path)));
+			generateGradients();
+		}
+		Term::fg = colors.at("main_fg");
+		Term::bg = colors.at("main_bg");
+		Fx::reset = Fx::reset_base + Term::fg + Term::bg;
+	}
+
+}

+ 70 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_theme.hpp

@@ -0,0 +1,70 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#pragma once
+
+#include <array>
+#include <filesystem>
+#include <string>
+#include <vector>
+#include <unordered_map>
+
+using std::array;
+using std::string;
+using std::vector;
+
+namespace Theme {
+	extern std::filesystem::path theme_dir;
+	extern std::filesystem::path user_theme_dir;
+	extern std::filesystem::path custom_theme_dir;
+
+	//* Contains "Default" and "TTY" at indices 0 and 1, otherwise full paths to theme files
+	extern vector<string> themes;
+
+	//* Generate escape sequence for 24-bit or 256 color and return as a string
+	//* Args	hexa: ["#000000"-"#ffffff"] for color, ["#00"-"#ff"] for greyscale
+	//*			t_to_256: [true|false] convert 24bit value to 256 color value
+	//* 		depth: ["fg"|"bg"] for either a foreground color or a background color
+	string hex_to_color(string hexa, bool t_to_256=false, const string& depth="fg");
+
+	//* Generate escape sequence for 24-bit or 256 color and return as a string
+	//* Args	r: [0-255], g: [0-255], b: [0-255]
+	//*			t_to_256: [true|false] convert 24bit value to 256 color value
+	//* 		depth: ["fg"|"bg"] for either a foreground color or a background color
+	string dec_to_color(int r, int g, int b, bool t_to_256=false, const string& depth="fg");
+
+	//* Update list of paths for available themes
+	void updateThemes();
+
+	//* Set current theme from current "color_theme" value in config
+	void setTheme();
+
+	extern std::unordered_map<string, string> colors;
+	extern std::unordered_map<string, array<int, 3>> rgbs;
+	extern std::unordered_map<string, array<string, 101>> gradients;
+
+	//* Return escape code for color <name>
+	inline const string& c(const string& name) { return colors.at(name); }
+
+	//* Return array of escape codes for color gradient <name>
+	inline const array<string, 101>& g(const string& name) { return gradients.at(name); }
+
+	//* Return array of red, green and blue in decimal for color <name>
+	inline const std::array<int, 3>& dec(const string& name) { return rgbs.at(name); }
+
+}

+ 714 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_tools.cpp

@@ -0,0 +1,714 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#include <cmath>
+#include <codecvt>
+#include <ctime>
+#include <filesystem>
+#include <fstream>
+#include <iomanip>
+#include <iostream>
+#include <optional>
+#include <ranges>
+#include <sstream>
+#include <string_view>
+#include <utility>
+
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <termios.h>
+#include <unistd.h>
+
+#include "widechar_width.hpp"
+#include "btop_shared.hpp"
+#include "btop_tools.hpp"
+#include "btop_config.hpp"
+
+using std::cout;
+using std::floor;
+using std::flush;
+using std::max;
+using std::string_view;
+using std::to_string;
+
+using namespace std::literals; // to use operator""s
+
+namespace fs = std::filesystem;
+namespace rng = std::ranges;
+
+//? ------------------------------------------------- NAMESPACES ------------------------------------------------------
+
+//* Collection of escape codes and functions for terminal manipulation
+namespace Term {
+
+	atomic<bool> initialized{};
+	atomic<int> width{};
+	atomic<int> height{};
+	string current_tty;
+
+	namespace {
+		struct termios initial_settings;
+
+		//* Toggle terminal input echo
+		bool echo(bool on=true) {
+			struct termios settings;
+			if (tcgetattr(STDIN_FILENO, &settings)) return false;
+			if (on) settings.c_lflag |= ECHO;
+			else settings.c_lflag &= ~(ECHO);
+			return 0 == tcsetattr(STDIN_FILENO, TCSANOW, &settings);
+		}
+
+		//* Toggle need for return key when reading input
+		bool linebuffered(bool on=true) {
+			struct termios settings;
+			if (tcgetattr(STDIN_FILENO, &settings)) return false;
+			if (on) settings.c_lflag |= ICANON;
+			else {
+				settings.c_lflag &= ~(ICANON);
+				settings.c_cc[VMIN] = 0;
+				settings.c_cc[VTIME] = 0;
+			}
+			if (tcsetattr(STDIN_FILENO, TCSANOW, &settings)) return false;
+			if (on) setlinebuf(stdin);
+			else setbuf(stdin, nullptr);
+			return true;
+		}
+	}
+
+	bool refresh(bool only_check) {
+		// Query dimensions of '/dev/tty' of the 'STDOUT_FILENO' isn't available.
+		// This variable is set in those cases to avoid calls to ioctl
+		constinit static bool uses_dev_tty = false;
+		struct winsize wsize {};
+		if (uses_dev_tty || ioctl(STDOUT_FILENO, TIOCGWINSZ, &wsize) < 0 || (wsize.ws_col == 0 && wsize.ws_row == 0)) {
+			Logger::error(R"(Couldn't determine terminal size of "STDOUT_FILENO"!)");
+			auto dev_tty = open("/dev/tty", O_RDONLY | O_CLOEXEC);
+			if (dev_tty != -1) {
+				ioctl(dev_tty, TIOCGWINSZ, &wsize);
+				close(dev_tty);
+			}
+			else {
+				Logger::error(R"(Couldn't determine terminal size of "/dev/tty"!)");
+				return false;
+			}
+			uses_dev_tty = true;
+		}
+		if (width != wsize.ws_col or height != wsize.ws_row) {
+			if (not only_check) {
+				width = wsize.ws_col;
+				height = wsize.ws_row;
+			}
+			return true;
+		}
+		return false;
+	}
+
+	auto get_min_size(const string& boxes) -> array<int, 2> {
+        bool cpu = boxes.find("cpu") != string::npos;
+        bool mem = boxes.find("mem") != string::npos;
+        bool net = boxes.find("net") != string::npos;
+        bool proc = boxes.find("proc") != string::npos;
+	#ifdef GPU_SUPPORT
+		int gpu = 0;
+        if (Gpu::count > 0)
+        	for (char i = '0'; i <= '5'; i++)
+        		gpu += (boxes.contains("gpu"s + i) ? 1 : 0);
+	#endif
+        int width = 0;
+		if (mem) width = Mem::min_width;
+		else if (net) width = Mem::min_width;
+		width += (proc ? Proc::min_width : 0);
+		if (cpu and width < Cpu::min_width) width = Cpu::min_width;
+	#ifdef GPU_SUPPORT
+		if (gpu != 0 and width < Gpu::min_width) width = Gpu::min_width;
+	#endif
+
+		int height = (cpu ? Cpu::min_height : 0);
+		if (proc) height += Proc::min_height;
+		else height += (mem ? Mem::min_height : 0) + (net ? Net::min_height : 0);
+	#ifdef GPU_SUPPORT
+		for (int i = 0; i < gpu; i++)
+			height += Gpu::gpu_b_height_offsets[i] + 4;
+	#endif
+
+		return { width, height };
+	}
+
+	bool init() {
+		if (not initialized) {
+			initialized = (bool)isatty(STDIN_FILENO);
+			if (initialized) {
+				tcgetattr(STDIN_FILENO, &initial_settings);
+				current_tty = (ttyname(STDIN_FILENO) != nullptr ? static_cast<string>(ttyname(STDIN_FILENO)) : "unknown");
+
+				//? Disable stream sync - this does not seem to work on OpenBSD
+#ifndef __OpenBSD__
+				cout.sync_with_stdio(false);
+#endif
+
+				//? Disable stream ties
+				cout.tie(nullptr);
+				echo(false);
+				linebuffered(false);
+				refresh();
+
+				cout << alt_screen << hide_cursor << mouse_on << flush;
+				Global::resized = false;
+			}
+		}
+		return initialized;
+	}
+
+	void restore() {
+		if (initialized) {
+			tcsetattr(STDIN_FILENO, TCSANOW, &initial_settings);
+			cout << mouse_off << clear << Fx::reset << normal_screen << show_cursor << flush;
+			initialized = false;
+		}
+	}
+}
+
+//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------
+
+// ! Disabled due to issue when compiling with musl, reverted back to using regex
+// namespace Fx {
+// 	string uncolor(const string& s) {
+// 		string out = s;
+// 		for (size_t offset = 0, start_pos = 0, end_pos = 0;;) {
+// 			start_pos = (offset == 0) ? out.find('\x1b') : offset;
+// 			if (start_pos == string::npos)
+// 				break;
+// 			offset = start_pos + 1;
+// 			end_pos = out.find('m', offset);
+// 			if (end_pos == string::npos)
+// 				break;
+// 			else if (auto next_pos = out.find('\x1b', offset); not isdigit(out[end_pos - 1]) or end_pos > next_pos) {
+// 			 	offset = next_pos;
+// 				continue;
+// 			}
+
+// 			out.erase(start_pos, (end_pos - start_pos)+1);
+// 			offset = 0;
+// 		}
+// 		out.shrink_to_fit();
+// 		return out;
+// 	}
+// }
+
+namespace Tools {
+
+	size_t wide_ulen(const std::string_view str) {
+		unsigned int chars = 0;
+		try {
+			std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
+			auto w_str = conv.from_bytes((str.size() > 10000 ? str.substr(0, 10000).data() : str.data()));
+
+			for (auto c : w_str) {
+				chars += utf8::wcwidth(c);
+			}
+		}
+		catch (...) {
+			return ulen(str);
+		}
+
+		return chars;
+	}
+
+	size_t wide_ulen(const std::wstring_view w_str) {
+		unsigned int chars = 0;
+
+		for (auto c : w_str) {
+			chars += utf8::wcwidth(c);
+		}
+
+		return chars;
+	}
+
+	string uresize(string str, const size_t len, bool wide) {
+		if (len < 1 or str.empty())
+			return "";
+
+		if (wide) {
+			try {
+				std::wstring_convert<std::codecvt_utf8<wchar_t>> conv;
+				auto w_str = conv.from_bytes((str.size() > 10000 ? str.substr(0, 10000).c_str() : str.c_str()));
+				while (wide_ulen(w_str) > len)
+					w_str.pop_back();
+				string n_str = conv.to_bytes(w_str);
+				return n_str;
+			}
+			catch (...) {
+				return uresize(str, len, false);
+			}
+		}
+		else {
+			for (size_t x = 0, i = 0; i < str.size(); i++) {
+				if ((static_cast<unsigned char>(str.at(i)) & 0xC0) != 0x80) x++;
+				if (x >= len + 1) {
+					str.resize(i);
+					break;
+				}
+			}
+		}
+		str.shrink_to_fit();
+		return str;
+	}
+
+	string luresize(string str, const size_t len, bool wide) {
+		if (len < 1 or str.empty())
+			return "";
+
+		for (size_t x = 0, last_pos = 0, i = str.size() - 1; i > 0 ; i--) {
+			if (wide and static_cast<unsigned char>(str.at(i)) > 0xef) {
+				x += 2;
+				last_pos = max((size_t)0, i - 1);
+			}
+			else if ((static_cast<unsigned char>(str.at(i)) & 0xC0) != 0x80) {
+				x++;
+				last_pos = i;
+			}
+			if (x >= len) {
+				str = str.substr(last_pos);
+				str.shrink_to_fit();
+				break;
+			}
+		}
+		return str;
+	}
+
+	string s_replace(const string& str, const string& from, const string& to) {
+		string out = str;
+		for (size_t start_pos = out.find(from); start_pos != std::string::npos; start_pos = out.find(from)) {
+			out.replace(start_pos, from.length(), to);
+		}
+		return out;
+	}
+
+	string_view ltrim(string_view str, const string_view t_str) {
+		while (str.starts_with(t_str))
+			str.remove_prefix(t_str.size());
+
+		return str;
+	}
+
+	string_view rtrim(string_view str, const string_view t_str) {
+		while (str.ends_with(t_str))
+			str.remove_suffix(t_str.size());
+
+		return str;
+	}
+
+	string ljust(string str, const size_t x, bool utf, bool wide, bool limit) {
+		if (utf) {
+			if (limit and ulen(str, wide) > x)
+				return uresize(str, x, wide);
+
+			return str + string(max((int)(x - ulen(str, wide)), 0), ' ');
+		}
+		else {
+			if (limit and str.size() > x) {
+				str.resize(x);
+				return str;
+			}
+			return str + string(max((int)(x - str.size()), 0), ' ');
+		}
+	}
+
+	string rjust(string str, const size_t x, bool utf, bool wide, bool limit) {
+		if (utf) {
+			if (limit and ulen(str, wide) > x)
+				return uresize(str, x, wide);
+
+			return string(max((int)(x - ulen(str)), 0), ' ') + str;
+		}
+		else {
+			if (limit and str.size() > x) {
+				str.resize(x);
+				return str;
+			};
+			return string(max((int)(x - str.size()), 0), ' ') + str;
+		}
+	}
+
+	string cjust(string str, const size_t x, bool utf, bool wide, bool limit) {
+		if (utf) {
+			if (limit and ulen(str, wide) > x)
+				return uresize(str, x, wide);
+
+			return string(max((int)ceil((double)(x - ulen(str)) / 2), 0), ' ') + str + string(max((int)floor((double)(x - ulen(str)) / 2), 0), ' ');
+		}
+		else {
+			if (limit and str.size() > x) {
+				str.resize(x);
+				return str;
+			}
+			return string(max((int)ceil((double)(x - str.size()) / 2), 0), ' ') + str + string(max((int)floor((double)(x - str.size()) / 2), 0), ' ');
+		}
+	}
+
+	string trans(const string& str) {
+		std::string_view oldstr{str};
+		string newstr;
+		newstr.reserve(str.size());
+		for (size_t pos; (pos = oldstr.find(' ')) != string::npos;) {
+			newstr.append(oldstr.substr(0, pos));
+			size_t x = 0;
+			while (pos + x < oldstr.size() and oldstr.at(pos + x) == ' ') x++;
+			newstr.append(Mv::r(x));
+			oldstr.remove_prefix(pos + x);
+		}
+		return (newstr.empty()) ? str : newstr + string{oldstr};
+	}
+
+	string sec_to_dhms(size_t seconds, bool no_days, bool no_seconds) {
+		size_t days = seconds / 86400; seconds %= 86400;
+		size_t hours = seconds / 3600; seconds %= 3600;
+		size_t minutes = seconds / 60; seconds %= 60;
+		string out 	= (not no_days and days > 0 ? to_string(days) + "d " : "")
+					+ (hours < 10 ? "0" : "") + to_string(hours) + ':'
+					+ (minutes < 10 ? "0" : "") + to_string(minutes)
+					+ (not no_seconds ? ":" + string(std::cmp_less(seconds, 10) ? "0" : "") + to_string(seconds) : "");
+		return out;
+	}
+
+	string floating_humanizer(uint64_t value, bool shorten, size_t start, bool bit, bool per_second) {
+		string out;
+		const size_t mult = (bit) ? 8 : 1;
+
+		bool mega = Config::getB("base_10_sizes");
+
+		// Bitrates
+	    if(bit && per_second) {
+			const auto& base_10_bitrate = Config::getS("base_10_bitrate");
+			if(base_10_bitrate == "True") {
+				mega = true;
+			} else if(base_10_bitrate == "False") {
+				mega = false;
+			}
+			// Default or "Auto": Uses base_10_sizes for bitrates
+		}
+
+		// taking advantage of type deduction for array creation (since C++17)
+		// combined with string literals (operator""s)
+		static const array mebiUnits_bit {
+			"bit"s, "Kib"s, "Mib"s,
+			"Gib"s, "Tib"s, "Pib"s,
+			"Eib"s, "Zib"s, "Yib"s,
+			"Bib"s, "GEb"s
+		};
+		static const array mebiUnits_byte {
+			"Byte"s, "KiB"s, "MiB"s,
+			"GiB"s, "TiB"s, "PiB"s,
+			"EiB"s, "ZiB"s, "YiB"s,
+			"BiB"s, "GEB"s
+		};
+		static const array megaUnits_bit {
+			"bit"s, "Kb"s, "Mb"s,
+			"Gb"s, "Tb"s, "Pb"s,
+			"Eb"s, "Zb"s, "Yb"s,
+			"Bb"s, "Gb"s
+		};
+		static const array megaUnits_byte {
+			"Byte"s, "KB"s, "MB"s,
+			"GB"s, "TB"s, "PB"s,
+			"EB"s, "ZB"s, "YB"s,
+			"BB"s, "GB"s
+		};
+		const auto& units = (bit) ? ( mega ? megaUnits_bit : mebiUnits_bit) : ( mega ? megaUnits_byte : mebiUnits_byte);
+
+		value *= 100 * mult;
+
+		if (mega) {
+			while (value >= 100000) {
+				value /= 1000;
+				if (value < 100) {
+					out = fmt::format("{}", value);
+					break;
+				}
+				start++;
+			}
+		}
+		else {
+			while (value >= 102400) {
+				value >>= 10;
+				if (value < 100) {
+					out = fmt::format("{}", value);
+					break;
+				}
+				start++;
+			}
+		}
+		if (out.empty()) {
+			out = fmt::format("{}", value);
+			if (not mega and out.size() == 4 and start > 0) {
+				out.pop_back();
+				out.insert(2, ".");
+			}
+			else if (out.size() == 3 and start > 0) {
+				out.insert(1, ".");
+			}
+			else if (out.size() >= 2) {
+				out.resize(out.size() - 2);
+			}
+			if (out.empty()) {
+				out = "0";
+			}
+		}
+
+		if (shorten) {
+			auto f_pos = out.find(".");
+			if (f_pos == 1 and out.size() > 3) {
+				out = fmt::format("{:.1f}", stod(out));
+			}
+			else if (f_pos != string::npos) {
+				out = fmt::format("{:.0f}", stod(out));
+			}
+			if (out.size() > 3) {
+				out = fmt::format("{:d}.0", out[0] - '0');
+				start++;
+			}
+			out.push_back(units[start][0]);
+		}
+		else out += " " + units[start];
+
+		if (per_second) out += (bit) ? "ps" : "/s";
+		return out;
+	}
+
+	std::string operator*(const string& str, int64_t n) {
+		if (n < 1 or str.empty()) {
+			return "";
+		}
+		else if (n == 1) {
+			return str;
+		}
+
+		string new_str;
+		new_str.reserve(str.size() * n);
+
+		for (; n > 0; n--)
+			new_str.append(str);
+
+		return new_str;
+	}
+
+	string strf_time(const string& strf) {
+		auto in_time_t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
+		std::tm bt {};
+		std::stringstream ss;
+		ss << std::put_time(localtime_r(&in_time_t, &bt), strf.c_str());
+		return ss.str();
+	}
+
+	void atomic_wait(const atomic<bool>& atom, bool old) noexcept {
+		while (atom.load(std::memory_order_relaxed) == old ) busy_wait();
+	}
+
+	void atomic_wait_for(const atomic<bool>& atom, bool old, const uint64_t wait_ms) noexcept {
+		const uint64_t start_time = time_ms();
+		while (atom.load(std::memory_order_relaxed) == old and (time_ms() - start_time < wait_ms)) sleep_ms(1);
+	}
+
+	atomic_lock::atomic_lock(atomic<bool>& atom, bool wait) : atom(atom) {
+		if (wait) while (not this->atom.compare_exchange_strong(this->not_true, true));
+		else this->atom.store(true);
+	}
+
+	atomic_lock::~atomic_lock() noexcept {
+		this->atom.store(false);
+	}
+
+	string readfile(const std::filesystem::path& path, const string& fallback) {
+		if (not fs::exists(path)) return fallback;
+		string out;
+		try {
+			std::ifstream file(path);
+			for (string readstr; getline(file, readstr); out += readstr);
+		}
+		catch (const std::exception& e) {
+			Logger::error("readfile() : Exception when reading " + string{path} + " : " + e.what());
+			return fallback;
+		}
+		return (out.empty() ? fallback : out);
+	}
+
+	auto celsius_to(const long long& celsius, const string& scale) -> tuple<long long, string> {
+		if (scale == "celsius")
+			return {celsius, "°C"};
+		else if (scale == "fahrenheit")
+			return {(long long)round((double)celsius * 1.8 + 32), "°F"};
+		else if (scale == "kelvin")
+			return {(long long)round((double)celsius + 273.15), "K "};
+		else if (scale == "rankine")
+			return {(long long)round((double)celsius * 1.8 + 491.67), "°R"};
+		return {0, ""};
+	}
+
+	string hostname() {
+		char host[HOST_NAME_MAX];
+		gethostname(host, HOST_NAME_MAX);
+		host[HOST_NAME_MAX - 1] = '\0';
+		return string{host};
+	}
+
+	string username() {
+		auto user = getenv("LOGNAME");
+		if (user == nullptr or strlen(user) == 0) user = getenv("USER");
+		return (user != nullptr ? user : "");
+	}
+
+	DebugTimer::DebugTimer(string name, bool start, bool delayed_report)
+			: name(std::move(name)), delayed_report(delayed_report) {
+		if (start)
+			this->start();
+	}
+
+	DebugTimer::~DebugTimer() {
+		if (running)
+			this->stop(true);
+		this->force_report();
+	}
+
+	void DebugTimer::start() {
+		if (running) return;
+		running = true;
+		start_time = time_micros();
+	}
+
+	void DebugTimer::stop(bool report) {
+		if (not running) return;
+		running = false;
+		elapsed_time = time_micros() - start_time;
+		if (report) this->report();
+	}
+
+	void DebugTimer::reset(bool restart) {
+		running = false;
+		start_time = 0;
+		elapsed_time = 0;
+		if (restart) this->start();
+	}
+
+	void DebugTimer::stop_rename_reset(const string &new_name, bool report, bool restart) {
+		this->stop(report);
+		name = new_name;
+		this->reset(restart);
+	}
+
+	void DebugTimer::report() {
+		string report_line;
+		if (start_time == 0 and elapsed_time == 0)
+			report_line = fmt::format("DebugTimer::report() warning -> Timer [{}] has not been started!", name);
+		else if (running)
+			report_line = fmt::format(custom_locale, "Timer [{}] (running) currently at {:L} μs", name, time_micros() - start_time);
+		else
+			report_line = fmt::format(custom_locale, "Timer [{}] took {:L} μs", name, elapsed_time);
+
+		if (delayed_report)
+			report_buffer.emplace_back(report_line);
+		else
+			Logger::log_write(log_level, report_line);
+	}
+
+	void DebugTimer::force_report() {
+		if (report_buffer.empty()) return;
+		for (const auto& line : report_buffer)
+			Logger::log_write(log_level, line);
+		report_buffer.clear();
+	}
+
+	uint64_t DebugTimer::elapsed() {
+		if (running)
+			return time_micros() - start_time;
+		return elapsed_time;
+	}
+
+	bool DebugTimer::is_running() {
+		return running;
+	}
+}
+
+namespace Logger {
+	using namespace Tools;
+	std::atomic<bool> busy (false);
+	bool first = true;
+	const string tdf = "%Y/%m/%d (%T) | ";
+
+	size_t loglevel;
+	std::optional<std::filesystem::path> logfile;
+
+	//* Wrapper for lowering privileges if using SUID bit and currently isn't using real userid
+	class lose_priv {
+		int status = -1;
+	public:
+		lose_priv() {
+			if (geteuid() != Global::real_uid) {
+				this->status = seteuid(Global::real_uid);
+			}
+		}
+		~lose_priv() noexcept {
+			if (status == 0) {
+				status = seteuid(Global::set_uid);
+			}
+		}
+		lose_priv(const lose_priv& other) = delete;
+		lose_priv& operator=(const lose_priv& other) = delete;
+		lose_priv(lose_priv&& other) = delete;
+		lose_priv& operator=(lose_priv&& other) = delete;
+	};
+
+	void set(const string& level) {
+		loglevel = v_index(log_levels, level);
+	}
+
+	void log_write(const Level level, const std::string_view msg) {
+		if (loglevel < level or !logfile.has_value()) {
+			return;
+		}
+		auto& log_file = logfile.value();
+		atomic_lock lck(busy, true);
+		lose_priv neutered{};
+		std::error_code ec;
+		try {
+			// NOTE: `exist()` could throw but since we return with an empty logfile we don't care
+			if (fs::exists(log_file) and fs::file_size(log_file, ec) > 1024 << 10 and not ec) {
+				auto old_log = log_file;
+				old_log += ".1";
+
+				if (fs::exists(old_log))
+					fs::remove(old_log, ec);
+
+				if (not ec)
+					fs::rename(log_file, old_log, ec);
+			}
+			if (not ec) {
+				std::ofstream lwrite(log_file, std::ios::app);
+				if (first) {
+					first = false;
+					lwrite << "\n" << strf_time(tdf) << "===> btop++ v." << Global::Version << "\n";
+				}
+				lwrite << strf_time(tdf) << log_levels.at(level) << ": " << msg << "\n";
+			}
+			else log_file.clear();
+		}
+		catch (const std::exception& e) {
+			log_file.clear();
+			throw std::runtime_error("Exception in Logger::log_write() : " + string{e.what()});
+		}
+	}
+}

+ 488 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/btop_tools.hpp

@@ -0,0 +1,488 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#pragma once
+
+#if !defined(NDEBUG)
+# define BTOP_DEBUG
+#endif
+
+#include <algorithm>        // for std::ranges::count_if
+#include <array>
+#include <atomic>
+#include <chrono>
+#include <cstdint>
+#include <filesystem>
+#include <limits.h>
+#include <pthread.h>
+#include <ranges>
+#include <regex>
+#include <string>
+#include <string_view>
+#include <thread>
+#include <tuple>
+#include <unordered_map>
+#include <vector>
+#ifdef BTOP_DEBUG
+#include <source_location>
+#endif
+#ifndef HOST_NAME_MAX
+	#ifdef __APPLE__
+		#define HOST_NAME_MAX 255
+	#else
+		#define HOST_NAME_MAX 64
+	#endif
+#endif
+
+#include "fmt/core.h"
+#include "fmt/format.h"
+
+using std::array;
+using std::atomic;
+using std::string;
+using std::to_string;
+using std::string_view;
+using std::tuple;
+using std::vector;
+using namespace fmt::literals;
+
+//? ------------------------------------------------- NAMESPACES ------------------------------------------------------
+
+//* Collection of escape codes for text style and formatting
+namespace Fx {
+	const string e = "\x1b[";				//* Escape sequence start
+	const string b = e + "1m";				//* Bold on/off
+	const string ub = e + "22m";			//* Bold off
+	const string d = e + "2m";				//* Dark on
+	const string ud = e + "22m";			//* Dark off
+	const string i = e + "3m";				//* Italic on
+	const string ui = e + "23m";			//* Italic off
+	const string ul = e + "4m";				//* Underline on
+	const string uul = e + "24m";			//* Underline off
+	const string bl = e + "5m";				//* Blink on
+	const string ubl = e + "25m";			//* Blink off
+	const string s = e + "9m";				//* Strike/crossed-out on
+	const string us = e + "29m";			//* Strike/crossed-out on/off
+
+	//* Reset foreground/background color and text effects
+	const string reset_base = e + "0m";
+
+	//* Reset text effects and restore theme foregrund and background color
+	extern string reset;
+
+	//* Regex for matching color, style and cursor move escape sequences
+	const std::regex escape_regex("\033\\[\\d+;?\\d?;?\\d*;?\\d*;?\\d*(m|f|s|u|C|D|A|B){1}");
+
+	//* Regex for matching only color and style escape sequences
+	const std::regex color_regex("\033\\[\\d+;?\\d?;?\\d*;?\\d*;?\\d*(m){1}");
+
+	//* Return a string with all colors and text styling removed
+	inline string uncolor(const string& s) { return std::regex_replace(s, color_regex, ""); }
+	// string uncolor(const string& s);
+
+}
+
+//* Collection of escape codes and functions for cursor manipulation
+namespace Mv {
+	//* Move cursor to <line>, <column>
+	inline string to(int line, int col) { return Fx::e + to_string(line) + ';' + to_string(col) + 'f'; }
+
+	//* Move cursor right <x> columns
+	inline string r(int x) { return Fx::e + to_string(x) + 'C'; }
+
+	//* Move cursor left <x> columns
+	inline string l(int x) { return Fx::e + to_string(x) + 'D'; }
+
+	//* Move cursor up x lines
+	inline string u(int x) { return Fx::e + to_string(x) + 'A'; }
+
+	//* Move cursor down x lines
+	inline string d(int x) { return Fx::e + to_string(x) + 'B'; }
+
+	//* Save cursor position
+	const string save = Fx::e + "s";
+
+	//* Restore saved cursor position
+	const string restore = Fx::e + "u";
+}
+
+//* Collection of escape codes and functions for terminal manipulation
+namespace Term {
+	extern atomic<bool> initialized;
+	extern atomic<int> width;
+	extern atomic<int> height;
+	extern string fg, bg, current_tty;
+
+	const string hide_cursor = Fx::e + "?25l";
+	const string show_cursor = Fx::e + "?25h";
+	const string alt_screen = Fx::e + "?1049h";
+	const string normal_screen = Fx::e + "?1049l";
+	const string clear = Fx::e + "2J" + Fx::e + "0;0f";
+	const string clear_end = Fx::e + "0J";
+	const string clear_begin = Fx::e + "1J";
+	const string mouse_on = Fx::e + "?1002h" + Fx::e + "?1015h" + Fx::e + "?1006h"; //? Enable reporting of mouse position on click and release
+	const string mouse_off = Fx::e + "?1002l" + Fx::e + "?1015l" + Fx::e + "?1006l";
+	const string mouse_direct_on = Fx::e + "?1003h"; //? Enable reporting of mouse position at any movement
+	const string mouse_direct_off = Fx::e + "?1003l";
+	const string sync_start = Fx::e + "?2026h"; //? Start of terminal synchronized output
+	const string sync_end = Fx::e + "?2026l"; //? End of terminal synchronized output
+
+	//* Returns true if terminal has been resized and updates width and height
+	bool refresh(bool only_check=false);
+
+	//* Returns an array with the lowest possible width, height with current box config
+	auto get_min_size(const string& boxes) -> array<int, 2>;
+
+	//* Check for a valid tty, save terminal options and set new options
+	bool init();
+
+	//* Restore terminal options
+	void restore();
+}
+
+//* Simple logging implementation
+namespace Logger {
+	const vector<string> log_levels = {
+		"DISABLED",
+		"ERROR",
+		"WARNING",
+		"INFO",
+		"DEBUG",
+	};
+	extern std::optional<std::filesystem::path> logfile;
+
+	enum Level : std::uint8_t {
+		DISABLED = 0,
+		ERROR = 1,
+		WARNING = 2,
+		INFO = 3,
+		DEBUG = 4,
+	};
+
+	//* Set log level, valid arguments: "DISABLED", "ERROR", "WARNING", "INFO" and "DEBUG"
+	void set(const string& level);
+
+	void log_write(const Level level, const std::string_view msg);
+
+	inline void error(const std::string_view msg) {
+		log_write(ERROR, msg);
+	}
+
+	inline void warning(const std::string_view msg) {
+		log_write(WARNING, msg);
+	}
+
+	inline void info(const std::string_view msg) {
+		log_write(INFO, msg);
+	}
+
+	inline void debug(const std::string_view msg) {
+		log_write(DEBUG, msg);
+	}
+}
+
+//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------
+
+namespace Tools {
+	constexpr auto SSmax = std::numeric_limits<std::streamsize>::max();
+
+	class MyNumPunct : public std::numpunct<char> {
+	protected:
+		virtual char do_thousands_sep() const override { return '\''; }
+		virtual std::string do_grouping() const override { return "\03"; }
+	};
+
+	size_t wide_ulen(const std::string_view str);
+	size_t wide_ulen(const std::wstring_view w_str);
+
+	//* Return number of UTF8 characters in a string (wide=true for column size needed on terminal)
+	inline size_t ulen(const std::string_view str, bool wide = false) {
+		return (wide ? wide_ulen(str) : std::ranges::count_if(str, [](char c) { return (static_cast<unsigned char>(c) & 0xC0) != 0x80; }));
+	}
+
+	//* Resize a string consisting of UTF8 characters (only reduces size)
+	string uresize(const string str, const size_t len, bool wide = false);
+
+	//* Resize a string consisting of UTF8 characters from left (only reduces size)
+	string luresize(const string str, const size_t len, bool wide = false);
+
+	//* Replace <from> in <str> with <to> and return new string
+	string s_replace(const string& str, const string& from, const string& to);
+
+	//* Replace ascii control characters with <replacement> in <str> and return new string
+	inline string replace_ascii_control(string str, const char replacement = ' ') {
+		std::ranges::for_each(str, [&replacement](char& c) { if (static_cast<unsigned char>(c) < 0x20) c = replacement; });
+		return str;
+	}
+
+	//* Capitalize <str>
+	inline string capitalize(string str) {
+		str.at(0) = toupper(str.at(0));
+		return str;
+	}
+
+	//* Return <str> with only uppercase characters
+	inline auto str_to_upper(string str) {
+		std::ranges::for_each(str, [](auto& c) { c = ::toupper(c); } );
+		return str;
+	}
+
+	//* Return <str> with only lowercase characters
+	inline auto str_to_lower(string str) {
+		std::ranges::for_each(str, [](char& c) { c = ::tolower(c); } );
+		return str;
+	}
+
+	//* Check if vector <vec> contains value <find_val>
+	template <typename T, typename T2>
+	inline bool v_contains(const vector<T>& vec, const T2& find_val) {
+		return std::ranges::find(vec, find_val) != vec.end();
+	}
+
+	//* Check if string <str> contains string <find_val>, while ignoring case
+	inline bool s_contains_ic(const std::string_view str, const std::string_view find_val) {
+		auto it = std::search(
+			str.begin(), str.end(),
+			find_val.begin(), find_val.end(),
+			[](char ch1, char ch2) { return std::toupper(ch1) == std::toupper(ch2); }
+		);
+		return it != str.end();
+	}
+
+	//* Return index of <find_val> from vector <vec>, returns size of <vec> if <find_val> is not present
+	template <typename T>
+	inline size_t v_index(const vector<T>& vec, const T& find_val) {
+		return std::ranges::distance(vec.begin(), std::ranges::find(vec, find_val));
+	}
+
+	//* Compare <first> with all following values
+	template<typename First, typename ... T>
+	inline bool is_in(const First& first, const T& ... t) {
+		return ((first == t) or ...);
+	}
+
+	//* Return current time since epoch in seconds
+	inline uint64_t time_s() {
+		return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
+	}
+
+	//* Return current time since epoch in milliseconds
+	inline uint64_t time_ms() {
+		return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
+	}
+
+	//* Return current time since epoch in microseconds
+	inline uint64_t time_micros() {
+		return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
+	}
+
+	//* Check if a string is a valid bool value
+	inline bool isbool(const std::string_view str) {
+		return is_in(str, "true", "false", "True", "False");
+	}
+
+	//* Convert string to bool, returning any value not equal to "true" or "True" as false
+	inline bool stobool(const std::string_view str) {
+		return is_in(str, "true", "True");
+	}
+
+	//* Check if a string is a valid integer value (only positive)
+	constexpr bool isint(const std::string_view str) {
+		return std::ranges::all_of(str, ::isdigit);
+	}
+
+	//* Left-trim <t_str> from <str> and return new string
+	string_view ltrim(string_view str, string_view t_str = " ");
+
+	//* Right-trim <t_str> from <str> and return new string
+	string_view rtrim(string_view str, string_view t_str = " ");
+
+	//* Left/right-trim <t_str> from <str> and return new string
+	inline string_view trim(string_view str, string_view t_str = " ") {
+		return ltrim(rtrim(str, t_str), t_str);
+	}
+
+	//* Split <string> at all occurrences of <delim> and return as vector of strings
+	inline std::vector<std::string> ssplit(std::string_view str, char delim = ' ') {
+		std::vector<std::string> result;
+		std::string token;
+		for (char c : str) {
+			if (c == delim) {
+				if (!token.empty()) { result.push_back(token); token.clear(); }
+			} else { token += c; }
+		}
+		if (!token.empty()) result.push_back(token);
+		return result;
+	}
+
+	//* Put current thread to sleep for <ms> milliseconds
+	inline void sleep_ms(const size_t& ms) {
+		std::this_thread::sleep_for(std::chrono::milliseconds(ms));
+	}
+
+	//* Put current thread to sleep for <micros> microseconds
+	inline void sleep_micros(const size_t& micros) {
+		std::this_thread::sleep_for(std::chrono::microseconds(micros));
+	}
+
+	//* Left justify string <str> if <x> is greater than <str> length, limit return size to <x> by default
+	string ljust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true);
+
+	//* Right justify string <str> if <x> is greater than <str> length, limit return size to <x> by default
+	string rjust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true);
+
+	//* Center justify string <str> if <x> is greater than <str> length, limit return size to <x> by default
+	string cjust(string str, const size_t x, bool utf = false, bool wide = false, bool limit = true);
+
+	//* Replace whitespaces " " with escape code for move right
+	string trans(const string& str);
+
+	//* Convert seconds to format "<days>d <hours>:<minutes>:<seconds>" and return string
+	string sec_to_dhms(size_t seconds, bool no_days = false, bool no_seconds = false);
+
+	//* Scales up in steps of 1024 to highest positive value unit and returns string with unit suffixed
+	//* bit=True or defaults to bytes
+	//* start=int to set 1024 multiplier starting unit
+	//* short=True always returns 0 decimals and shortens unit to 1 character
+	string floating_humanizer(uint64_t value, bool shorten = false, size_t start = 0, bool bit = false, bool per_second = false);
+
+	//* Add std::string operator * : Repeat string <str> <n> number of times
+	std::string operator*(const string& str, int64_t n);
+
+	template <typename K, typename T>
+#ifdef BTOP_DEBUG
+	const T& safeVal(const std::unordered_map<K, T>& map, const K& key, const T& fallback = T{}, std::source_location loc = std::source_location::current()) {
+		if (auto it = map.find(key); it != map.end()) {
+			return it->second;
+		} else {
+			Logger::error(fmt::format("safeVal() called with invalid key: [{}] in file: {} on line: {}", key, loc.file_name(), loc.line()));
+			return fallback;
+		}
+	};
+#else
+	const T& safeVal(const std::unordered_map<K, T>& map, const K& key, const T& fallback = T{}) {
+		if (auto it = map.find(key); it != map.end()) {
+			return it->second;
+		} else {
+			Logger::error(fmt::format("safeVal() called with invalid key: [{}] (Compile btop with DEBUG=true for more extensive logging!)", key));
+			return fallback;
+		}
+	};
+#endif
+
+	template <typename T>
+#ifdef BTOP_DEBUG
+	const T& safeVal(const std::vector<T>& vec, const size_t& index, const T& fallback = T{}, std::source_location loc = std::source_location::current()) {
+		if (index < vec.size()) {
+			return vec[index];
+		} else {
+			Logger::error(fmt::format("safeVal() called with invalid index: [{}] in file: {} on line: {}", index, loc.file_name(), loc.line()));
+			return fallback;
+		}
+	};
+#else
+	const T& safeVal(const std::vector<T>& vec, const size_t& index, const T& fallback = T{}) {
+		if (index < vec.size()) {
+			return vec[index];
+		} else {
+			Logger::error(fmt::format("safeVal() called with invalid index: [{}] (Compile btop with DEBUG=true for more extensive logging!)", index));
+			return fallback;
+		}
+	};
+#endif
+
+
+
+	//* Return current time in <strf> format
+	string strf_time(const string& strf);
+
+	string hostname();
+	string username();
+
+	static inline void busy_wait (void) {
+	#if defined __i386__ || defined __x86_64__
+		__builtin_ia32_pause();
+	#elif defined __ia64__
+		__asm volatile("hint @pause" : : : "memory");
+	#elif defined __sparc__ && (defined __arch64__ || defined __sparc_v9__)
+		__asm volatile("membar #LoadLoad" : : : "memory");
+	#else
+		__asm volatile("" : : : "memory");
+	#endif
+	}
+
+	void atomic_wait(const atomic<bool>& atom, bool old = true) noexcept;
+
+	void atomic_wait_for(const atomic<bool>& atom, bool old = true, const uint64_t wait_ms = 0) noexcept;
+
+	//* Sets atomic<bool> to true on construct, sets to false on destruct
+	class atomic_lock {
+		atomic<bool>& atom;
+		bool not_true{};
+	public:
+		explicit atomic_lock(atomic<bool>& atom, bool wait = false);
+		~atomic_lock() noexcept;
+		atomic_lock(const atomic_lock& other) = delete;
+		atomic_lock& operator=(const atomic_lock& other) = delete;
+		atomic_lock(atomic_lock&& other) = delete;
+		atomic_lock& operator=(atomic_lock&& other) = delete;
+	};
+
+	//* Read a complete file and return as a string
+	string readfile(const std::filesystem::path& path, const string& fallback = "");
+
+	//* Convert a celsius value to celsius, fahrenheit, kelvin or rankin and return tuple with new value and unit.
+	auto celsius_to(const long long& celsius, const string& scale) -> tuple<long long, string>;
+}
+
+namespace Tools {
+	//* Creates a named timer that is started on construct (by default) and reports elapsed time in microseconds to Logger::debug() on destruct if running
+	//* Unless delayed_report is set to false, all reporting is buffered and delayed until DebugTimer is destructed or .force_report() is called
+	//* Usage example: Tools::DebugTimer timer(name:"myTimer", [start:true], [delayed_report:true]) // Create timer and start
+	//* timer.stop(); // Stop timer and report elapsed time
+	//* timer.stop_rename_reset("myTimer2"); // Stop timer, report elapsed time, rename timer, reset and restart
+	class DebugTimer {
+		uint64_t start_time{};
+		uint64_t elapsed_time{};
+		bool running{};
+		std::locale custom_locale = std::locale(std::locale::classic(), new Tools::MyNumPunct);
+		vector<string> report_buffer{};
+		string name{};
+		bool delayed_report{};
+		Logger::Level log_level = Logger::DEBUG;
+	public:
+		DebugTimer() = default;
+		explicit DebugTimer(string name, bool start = true, bool delayed_report = true);
+		~DebugTimer();
+		DebugTimer(const DebugTimer& other) = delete;
+		DebugTimer& operator=(const DebugTimer& other) = delete;
+		DebugTimer(DebugTimer&& other) = delete;
+		DebugTimer& operator=(DebugTimer&& other) = delete;
+
+		void start();
+		void stop(bool report = true);
+		void reset(bool restart = true);
+		//* Stops and reports (default), renames timer then resets and restarts (default)
+		void stop_rename_reset(const string& new_name, bool report = true, bool restart = true);
+		void report();
+		void force_report();
+		uint64_t elapsed();
+		bool is_running();
+	};
+
+}

+ 10 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/config.h.in

@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: Apache-2.0
+
+#pragma once
+
+#include <string_view>
+
+constexpr std::string_view GIT_COMMIT        = "@GIT_COMMIT@";
+constexpr std::string_view COMPILER          = "@COMPILER@";
+constexpr std::string_view COMPILER_VERSION  = "@COMPILER_VERSION@";
+constexpr std::string_view CONFIGURE_COMMAND = "@CONFIGURE_COMMAND@";

+ 1356 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/freebsd/btop_collect.cpp

@@ -0,0 +1,1356 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+#include <arpa/inet.h>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <libproc.h>
+// man 3 getifaddrs: "BUGS: If	both <net/if.h>	and <ifaddrs.h>	are being included, <net/if.h> must be included before <ifaddrs.h>"
+#include <net/if.h>
+#include <ifaddrs.h>
+#include <net/if_dl.h>
+#include <net/route.h>
+#include <netdb.h>
+#include <netinet/tcp_fsm.h>
+#include <netinet/in.h> // for inet_ntop stuff
+#include <pwd.h>
+#include <sys/_timeval.h>
+#include <sys/endian.h>
+#include <sys/resource.h>
+#include <sys/socket.h>
+#include <sys/statvfs.h>
+#include <sys/sysctl.h>
+#include <sys/types.h>
+#include <sys/user.h>
+#include <sys/param.h>
+#include <sys/ucred.h>
+#include <sys/mount.h>
+#include <sys/vmmeter.h>
+#include <sys/limits.h>
+#include <vector>
+#include <vm/vm_param.h>
+#include <kvm.h>
+#include <paths.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <devstat.h>
+
+#include <stdexcept>
+#include <cmath>
+#include <fstream>
+#include <numeric>
+#include <ranges>
+#include <regex>
+#include <string>
+#include <memory>
+#include <utility>
+#include <unordered_set>
+
+#include "../btop_config.hpp"
+#include "../btop_shared.hpp"
+#include "../btop_tools.hpp"
+
+using std::clamp, std::string_literals::operator""s, std::cmp_equal, std::cmp_less, std::cmp_greater;
+using std::ifstream, std::numeric_limits, std::streamsize, std::round, std::max, std::min;
+namespace fs = std::filesystem;
+namespace rng = std::ranges;
+using namespace Tools;
+
+//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------
+
+namespace Cpu {
+	vector<long long> core_old_totals;
+	vector<long long> core_old_idles;
+	vector<string> available_fields = {"Auto", "total"};
+	vector<string> available_sensors = {"Auto"};
+	cpu_info current_cpu;
+	bool got_sensors = false, cpu_temp_only = false, supports_watts = false;
+
+	//* Populate found_sensors map
+	bool get_sensors();
+
+	//* Get current cpu clock speed
+	string get_cpuHz();
+
+	//* Search /proc/cpuinfo for a cpu name
+	string get_cpuName();
+
+	struct Sensor {
+		fs::path path;
+		string label;
+		int64_t temp = 0;
+		int64_t high = 0;
+		int64_t crit = 0;
+	};
+
+	string cpu_sensor;
+	vector<string> core_sensors;
+	std::unordered_map<int, int> core_mapping;
+}  // namespace Cpu
+
+namespace Mem {
+	double old_uptime;
+	std::vector<string> zpools;
+
+	void get_zpools();
+}
+
+namespace Shared {
+
+	fs::path passwd_path;
+	uint64_t totalMem;
+	long pageSize, clkTck, coreCount, physicalCoreCount, arg_max;
+	int totalMem_len, kfscale;
+	long bootTime;
+
+	void init() {
+		//? Shared global variables init
+		int mib[2];
+		mib[0] = CTL_HW;
+		mib[1] = HW_NCPU;
+		int ncpu;
+		size_t len = sizeof(ncpu);
+		if (sysctl(mib, 2, &ncpu, &len, nullptr, 0) == -1) {
+			Logger::warning("Could not determine number of cores, defaulting to 1.");
+		} else {
+			coreCount = ncpu;
+		}
+
+		pageSize = sysconf(_SC_PAGE_SIZE);
+		if (pageSize <= 0) {
+			pageSize = 4096;
+			Logger::warning("Could not get system page size. Defaulting to 4096, processes memory usage might be incorrect.");
+		}
+
+		clkTck = sysconf(_SC_CLK_TCK);
+		if (clkTck <= 0) {
+			clkTck = 100;
+			Logger::warning("Could not get system clock ticks per second. Defaulting to 100, processes cpu usage might be incorrect.");
+		}
+
+		int64_t memsize = 0;
+		size_t size = sizeof(memsize);
+		if (sysctlbyname("hw.physmem", &memsize, &size, nullptr, 0) < 0) {
+			Logger::warning("Could not get memory size");
+		}
+		totalMem = memsize;
+
+		struct timeval result;
+		size = sizeof(result);
+		if (sysctlbyname("kern.boottime", &result, &size, nullptr, 0) < 0) {
+			Logger::warning("Could not get boot time");
+		} else {
+			bootTime = result.tv_sec;
+		}
+
+		size = sizeof(kfscale);
+		if (sysctlbyname("kern.fscale", &kfscale, &size, nullptr, 0) == -1) {
+			kfscale = 2048;
+		}
+
+		//* Get maximum length of process arguments
+		arg_max = sysconf(_SC_ARG_MAX);
+
+		//? Init for namespace Cpu
+		Cpu::current_cpu.core_percent.insert(Cpu::current_cpu.core_percent.begin(), Shared::coreCount, {});
+		Cpu::current_cpu.temp.insert(Cpu::current_cpu.temp.begin(), Shared::coreCount + 1, {});
+		Cpu::core_old_totals.insert(Cpu::core_old_totals.begin(), Shared::coreCount, 0);
+		Cpu::core_old_idles.insert(Cpu::core_old_idles.begin(), Shared::coreCount, 0);
+		Logger::debug("Init -> Cpu::collect()");
+		Cpu::collect();
+		for (auto &[field, vec] : Cpu::current_cpu.cpu_percent) {
+			if (not vec.empty() and not v_contains(Cpu::available_fields, field)) Cpu::available_fields.push_back(field);
+		}
+		Logger::debug("Init -> Cpu::get_cpuName()");
+		Cpu::cpuName = Cpu::get_cpuName();
+		Logger::debug("Init -> Cpu::get_sensors()");
+		Cpu::got_sensors = Cpu::get_sensors();
+		Logger::debug("Init -> Cpu::get_core_mapping()");
+		Cpu::core_mapping = Cpu::get_core_mapping();
+
+		//? Init for namespace Mem
+		Mem::old_uptime = system_uptime();
+		Logger::debug("Init -> Mem::collect()");
+		Mem::collect();
+		Logger::debug("Init -> Mem::get_zpools()");
+		Mem::get_zpools();
+	}
+}  // namespace Shared
+
+namespace Cpu {
+	string cpuName;
+	string cpuHz;
+	bool has_battery = true;
+	tuple<int, float, long, string> current_bat;
+
+	const array<string, 10> time_names = {"user", "nice", "system", "idle"};
+
+	std::unordered_map<string, long long> cpu_old = {
+		{"totals", 0},
+		{"idles", 0},
+		{"user", 0},
+		{"nice", 0},
+		{"system", 0},
+		{"idle", 0}
+	};
+
+	string get_cpuName() {
+		string name;
+		char buffer[1024];
+		size_t size = sizeof(buffer);
+		if (sysctlbyname("hw.model", &buffer, &size, nullptr, 0) < 0) {
+			Logger::error("Failed to get CPU name");
+			return name;
+		}
+		return trim_name(string(buffer));
+	}
+
+	bool get_sensors() {
+		got_sensors = false;
+		if (Config::getB("show_coretemp") and Config::getB("check_temp")) {
+			int32_t temp;
+			size_t size = sizeof(temp);
+			if (sysctlbyname("dev.cpu.0.temperature", &temp, &size, nullptr, 0) < 0) {
+				Logger::warning("Could not get temp sensor - maybe you need to load the coretemp module");
+			} else {
+				got_sensors = true;
+				int temp;
+				size_t size = sizeof(temp);
+				sysctlbyname("dev.cpu.0.coretemp.tjmax", &temp, &size, nullptr, 0); //assuming the max temp is same for all cores
+				temp = (temp - 2732) / 10; // since it's an int, it's multiplied by 10, and offset to absolute zero...
+				current_cpu.temp_max = temp;
+			}
+		}
+		return got_sensors;
+	}
+
+	void update_sensors() {
+		int temp = 0;
+		int p_temp = 0;
+		int found = 0;
+		bool got_package = false;
+		size_t size = sizeof(p_temp);
+		if (sysctlbyname("hw.acpi.thermal.tz0.temperature", &p_temp, &size, nullptr, 0) >= 0) {
+			got_package = true;
+			p_temp = (p_temp - 2732) / 10; // since it's an int, it's multiplied by 10, and offset to absolute zero...
+		}
+
+		size = sizeof(temp);
+		for (int i = 0; i < Shared::coreCount; i++) {
+			string s = "dev.cpu." + std::to_string(i) + ".temperature";
+			if (sysctlbyname(s.c_str(), &temp, &size, nullptr, 0) >= 0) {
+				temp = (temp - 2732) / 10;
+				if (not got_package) {
+					p_temp += temp;
+					found++;
+				}
+				if (cmp_less(i + 1, current_cpu.temp.size())) {
+					current_cpu.temp.at(i + 1).push_back(temp);
+					if (current_cpu.temp.at(i + 1).size() > 20)
+						current_cpu.temp.at(i + 1).pop_front();
+				}
+			}
+		}
+
+		if (not got_package) p_temp /= found;
+		current_cpu.temp.at(0).push_back(p_temp);
+		if (current_cpu.temp.at(0).size() > 20)
+			current_cpu.temp.at(0).pop_front();
+
+	}
+
+	string get_cpuHz() {
+		unsigned int freq = 1;
+		size_t size = sizeof(freq);
+
+		if (sysctlbyname("dev.cpu.0.freq", &freq, &size, nullptr, 0) < 0) {
+			return "";
+		}
+		return std::to_string(freq / 1000.0 ).substr(0, 3); // seems to be in MHz
+	}
+
+	auto get_core_mapping() -> std::unordered_map<int, int> {
+		std::unordered_map<int, int> core_map;
+		if (cpu_temp_only) return core_map;
+
+		for (long i = 0; i < Shared::coreCount; i++) {
+			core_map[i] = i;
+		}
+
+		//? If core mapping from cpuinfo was incomplete try to guess remainder, if missing completely, map 0-0 1-1 2-2 etc.
+		if (cmp_less(core_map.size(), Shared::coreCount)) {
+			if (Shared::coreCount % 2 == 0 and (long) core_map.size() == Shared::coreCount / 2) {
+				for (int i = 0, n = 0; i < Shared::coreCount / 2; i++) {
+					if (std::cmp_greater_equal(n, core_sensors.size())) n = 0;
+					core_map[Shared::coreCount / 2 + i] = n++;
+				}
+			} else {
+				core_map.clear();
+				for (int i = 0, n = 0; i < Shared::coreCount; i++) {
+					if (std::cmp_greater_equal(n, core_sensors.size())) n = 0;
+					core_map[i] = n++;
+				}
+			}
+		}
+
+		//? Apply user set custom mapping if any
+		const auto &custom_map = Config::getS("cpu_core_map");
+		if (not custom_map.empty()) {
+			try {
+				for (const auto &split : ssplit(custom_map)) {
+					const auto vals = ssplit(split, ':');
+					if (vals.size() != 2) continue;
+					int change_id = std::stoi(vals.at(0));
+					int new_id = std::stoi(vals.at(1));
+					if (not core_map.contains(change_id) or cmp_greater(new_id, core_sensors.size())) continue;
+					core_map.at(change_id) = new_id;
+				}
+			} catch (...) {
+			}
+		}
+
+		return core_map;
+	}
+
+	auto get_battery() -> tuple<int, float, long, string> {
+		if (not has_battery) return {0, 0, 0, ""};
+
+		long seconds = -1;
+		float watts = -1;
+		uint32_t percent = -1;
+		size_t size = sizeof(percent);
+		string status = "discharging";
+		if (sysctlbyname("hw.acpi.battery.life", &percent, &size, nullptr, 0) < 0) {
+			has_battery = false;
+		} else {
+			has_battery = true;
+			size_t size = sizeof(seconds);
+			if (sysctlbyname("hw.acpi.battery.time", &seconds, &size, nullptr, 0) < 0) {
+				seconds = 0;
+			}
+			size = sizeof(watts);
+			if (sysctlbyname("hw.acpi.battery.rate", &watts, &size, nullptr, 0) < 0) {
+				watts = -1;
+			}
+			int state;
+			size = sizeof(state);
+			if (sysctlbyname("hw.acpi.battery.state", &state, &size, nullptr, 0) < 0) {
+				status = "unknown";
+			} else {
+				if (state == 2) {
+					status = "charging";
+				}
+			}
+			if (percent == 100) {
+				status = "full";
+			}
+		}
+
+		return {percent, watts, seconds, status};
+	}
+
+	auto collect(bool no_update) -> cpu_info & {
+		if (Runner::stopping or (no_update and not current_cpu.cpu_percent.at("total").empty()))
+			return current_cpu;
+		auto &cpu = current_cpu;
+
+		if (getloadavg(cpu.load_avg.data(), cpu.load_avg.size()) < 0) {
+			Logger::error("failed to get load averages");
+		}
+
+		vector<array<long, CPUSTATES>> cpu_time(Shared::coreCount);
+		size_t size = sizeof(long) * CPUSTATES * Shared::coreCount;
+		if (sysctlbyname("kern.cp_times", &cpu_time[0], &size, nullptr, 0) == -1) {
+			Logger::error("failed to get CPU times");
+		}
+		long long global_totals = 0;
+		long long global_idles = 0;
+		vector<long long> times_summed = {0, 0, 0, 0};
+
+		for (long i = 0; i < Shared::coreCount; i++) {
+			vector<long long> times;
+			//? 0=user, 1=nice, 2=system, 3=idle
+			for (int x = 0; const unsigned int c_state : {CP_USER, CP_NICE, CP_SYS, CP_IDLE}) {
+				auto val = cpu_time[i][c_state];
+				times.push_back(val);
+				times_summed.at(x++) += val;
+			}
+			try {
+				//? All values
+				const long long totals = std::accumulate(times.begin(), times.end(), 0ll);
+
+				//? Idle time
+				const long long idles = times.at(3);
+
+				global_totals += totals;
+				global_idles += idles;
+
+				//? Calculate cpu total for each core
+				if (i > Shared::coreCount) break;
+				const long long calc_totals = max(0ll, totals - core_old_totals.at(i));
+				const long long calc_idles = max(0ll, idles - core_old_idles.at(i));
+				core_old_totals.at(i) = totals;
+				core_old_idles.at(i) = idles;
+
+				cpu.core_percent.at(i).push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));
+
+				//? Reduce size if there are more values than needed for graph
+				if (cpu.core_percent.at(i).size() > 40) cpu.core_percent.at(i).pop_front();
+
+			} catch (const std::exception &e) {
+				Logger::error("Cpu::collect() : " + (string)e.what());
+				throw std::runtime_error("collect() : " + (string)e.what());
+			}
+
+		}
+
+		const long long calc_totals = max(1ll, global_totals - cpu_old.at("totals"));
+		const long long calc_idles = max(1ll, global_idles - cpu_old.at("idles"));
+
+		//? Populate cpu.cpu_percent with all fields from syscall
+		for (int ii = 0; const auto &val : times_summed) {
+			cpu.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));
+			cpu_old.at(time_names.at(ii)) = val;
+
+			//? Reduce size if there are more values than needed for graph
+			while (cmp_greater(cpu.cpu_percent.at(time_names.at(ii)).size(), width * 2)) cpu.cpu_percent.at(time_names.at(ii)).pop_front();
+
+			ii++;
+		}
+
+		cpu_old.at("totals") = global_totals;
+		cpu_old.at("idles") = global_idles;
+
+		//? Total usage of cpu
+		cpu.cpu_percent.at("total").push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));
+
+		//? Reduce size if there are more values than needed for graph
+		while (cmp_greater(cpu.cpu_percent.at("total").size(), width * 2)) cpu.cpu_percent.at("total").pop_front();
+
+		if (Config::getB("show_cpu_freq")) {
+			auto hz = get_cpuHz();
+			if (hz != "") {
+				cpuHz = hz;
+			}
+		}
+
+		if (Config::getB("check_temp") and got_sensors)
+			update_sensors();
+
+		if (Config::getB("show_battery") and has_battery)
+			current_bat = get_battery();
+
+		return cpu;
+	}
+}  // namespace Cpu
+
+namespace Mem {
+	bool has_swap = false;
+	vector<string> fstab;
+	fs::file_time_type fstab_time;
+	int disk_ios = 0;
+	vector<string> last_found;
+
+	mem_info current_mem{};
+
+	uint64_t get_totalMem() {
+		return Shared::totalMem;
+	}
+
+	void assign_values(struct disk_info& disk, int64_t readBytes, int64_t writeBytes) {
+		disk_ios++;
+		if (disk.io_read.empty()) {
+			disk.io_read.push_back(0);
+		} else {
+			disk.io_read.push_back(max((int64_t)0, (readBytes - disk.old_io.at(0))));
+		}
+		disk.old_io.at(0) = readBytes;
+		while (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front();
+
+		if (disk.io_write.empty()) {
+			disk.io_write.push_back(0);
+		} else {
+			disk.io_write.push_back(max((int64_t)0, (writeBytes - disk.old_io.at(1))));
+		}
+		disk.old_io.at(1) = writeBytes;
+		while (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front();
+
+		// no io times - need to push something anyway or we'll get an ABORT
+		if (disk.io_activity.empty())
+			disk.io_activity.push_back(0);
+		else
+			disk.io_activity.push_back(clamp((long)round((double)(disk.io_write.back() + disk.io_read.back()) / (1 << 20)), 0l, 100l));
+		while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();
+	}
+
+	class PipeWrapper {
+		public:
+			PipeWrapper(const char *file, const char *mode) {fd = popen(file, mode);}
+			virtual ~PipeWrapper() {if (fd) pclose(fd);}
+			auto operator()() -> FILE* { return fd;};
+		private:
+			FILE *fd;
+	};
+
+	// find all zpools in the system. Do this only at startup.
+	void get_zpools() {
+		std::regex toReplace("\\.");
+		PipeWrapper poolPipe = PipeWrapper("zpool list -H -o name", "r");
+
+		while (not std::feof(poolPipe())) {
+			char poolName[512];
+			size_t len = 512;
+			if (fgets(poolName, len, poolPipe())) {
+				poolName[strcspn(poolName, "\n")] = 0;
+				Logger::debug("zpool found: " + string(poolName));
+				Mem::zpools.push_back(std::regex_replace(poolName, toReplace, "%25"));
+			}
+		}
+	}
+
+	void collect_disk(std::unordered_map<string, disk_info> &disks, std::unordered_map<string, string> &mapping) {
+		// this bit is for 'regular' mounts
+		static struct statinfo cur;
+		long double etime = 0;
+		uint64_t total_bytes_read;
+		uint64_t total_bytes_write;
+
+		static std::unique_ptr<struct devinfo, decltype(std::free)*> curDevInfo (reinterpret_cast<struct devinfo*>(std::calloc(1, sizeof(struct devinfo))), std::free);
+		cur.dinfo = curDevInfo.get();
+
+		if (devstat_getdevs(nullptr, &cur) != -1) {
+			for (int i = 0; i < cur.dinfo->numdevs; i++) {
+				auto d = cur.dinfo->devices[i];
+				string devStatName = "/dev/" + string(d.device_name) + std::to_string(d.unit_number);
+				for (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
+					if (disk.dev.string().rfind(devStatName, 0) == 0 and mapping.contains(disk.dev)) {
+						devstat_compute_statistics(&d, nullptr, etime, DSM_TOTAL_BYTES_READ, &total_bytes_read, DSM_TOTAL_BYTES_WRITE, &total_bytes_write, DSM_NONE);
+						assign_values(disk, total_bytes_read, total_bytes_write);
+						string mountpoint = mapping.at(disk.dev);
+						Logger::debug("dev " + devStatName + " -> " + mountpoint  + " read=" + std::to_string(total_bytes_read) + " write=" + std::to_string(total_bytes_write));
+					}
+				}
+
+			}
+		}
+
+		// this code is for ZFS mounts
+		for (const auto &poolName : Mem::zpools) {
+			char sysCtl[1024];
+			snprintf(sysCtl, sizeof(sysCtl), "sysctl kstat.zfs.%s.dataset | grep -E \'dataset_name|nread|nwritten\'", poolName.c_str());
+			PipeWrapper f = PipeWrapper(sysCtl, "r");
+			if (f()) {
+				char buf[512];
+				size_t len = 512;
+				uint64_t nread = 0, nwritten = 0;
+				while (not std::feof(f())) {
+					if (fgets(buf, len, f())) {
+						char *name = std::strtok(buf, ": \n");
+						char *value = std::strtok(nullptr, ": \n");
+						if (string(name).find("dataset_name") != string::npos) {
+							// create entry if datasetname matches with anything in mapping
+							// relies on the fact that the dataset name is last value in the list
+							// alternatively you could parse the objset-0x... when this changes, you have a new entry
+							string datasetname = string(value);// this is the zfs volume, like 'zroot/usr/home' -> this maps onto the device we get back from getmntinfo(3)
+							if (mapping.contains(datasetname)) {
+								string mountpoint = mapping.at(datasetname);
+								if (disks.contains(mountpoint)) {
+									auto& disk = disks.at(mountpoint);
+									assign_values(disk, nread, nwritten);
+								}
+							}
+						} else if (string(name).find("nread") != string::npos) {
+							nread = atoll(value);
+						} else if (string(name).find("nwritten") != string::npos) {
+							nwritten = atoll(value);
+						}
+					}
+				}
+			}
+		}
+
+	}
+
+	auto collect(bool no_update) -> mem_info & {
+		if (Runner::stopping or (no_update and not current_mem.percent.at("used").empty()))
+			return current_mem;
+
+		auto show_swap = Config::getB("show_swap");
+		auto show_disks = Config::getB("show_disks");
+		auto swap_disk = Config::getB("swap_disk");
+		auto &mem = current_mem;
+		static bool snapped = (getenv("BTOP_SNAPPED") != nullptr);
+
+		int mib[4];
+		u_int memActive, memWire, cachedMem, freeMem;
+		size_t len;
+
+   		len = 4; sysctlnametomib("vm.stats.vm.v_active_count", mib, &len);
+		len = sizeof(memActive);
+		sysctl(mib, 4, &(memActive), &len, nullptr, 0);
+		memActive *= Shared::pageSize;
+
+		len = 4; sysctlnametomib("vm.stats.vm.v_wire_count", mib, &len);
+		len = sizeof(memWire);
+		sysctl(mib, 4, &(memWire), &len, nullptr, 0);
+		memWire *= Shared::pageSize;
+
+		mem.stats.at("used") = memWire + memActive;
+		mem.stats.at("available") = Shared::totalMem - memActive - memWire;
+
+		len = sizeof(cachedMem);
+   		len = 4; sysctlnametomib("vm.stats.vm.v_cache_count", mib, &len);
+   		sysctl(mib, 4, &(cachedMem), &len, nullptr, 0);
+   		cachedMem *= Shared::pageSize;
+   		mem.stats.at("cached") = cachedMem;
+
+		len = sizeof(freeMem);
+   		len = 4; sysctlnametomib("vm.stats.vm.v_free_count", mib, &len);
+   		sysctl(mib, 4, &(freeMem), &len, nullptr, 0);
+   		freeMem *= Shared::pageSize;
+   		mem.stats.at("free") = freeMem;
+
+		if (show_swap) {
+			char buf[_POSIX2_LINE_MAX];
+			Shared::KvmPtr kd {kvm_openfiles(nullptr, _PATH_DEVNULL, nullptr, O_RDONLY, buf)}; 
+   			struct kvm_swap swap[16];
+   			int nswap = kvm_getswapinfo(kd.get(), swap, 16, 0);
+			int totalSwap = 0, usedSwap = 0;
+			for (int i = 0; i < nswap; i++) {
+				totalSwap += swap[i].ksw_total;
+				usedSwap += swap[i].ksw_used;
+			}
+			mem.stats.at("swap_total") = totalSwap * Shared::pageSize;
+			mem.stats.at("swap_used") = usedSwap * Shared::pageSize;
+		}
+
+		if (show_swap and mem.stats.at("swap_total") > 0) {
+			for (const auto &name : swap_names) {
+				mem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / mem.stats.at("swap_total")));
+				while (cmp_greater(mem.percent.at(name).size(), width * 2))
+					mem.percent.at(name).pop_front();
+			}
+			has_swap = true;
+		} else
+			has_swap = false;
+		//? Calculate percentages
+		for (const auto &name : mem_names) {
+			mem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / Shared::totalMem));
+			while (cmp_greater(mem.percent.at(name).size(), width * 2))
+				mem.percent.at(name).pop_front();
+		}
+
+		if (show_disks) {
+			std::unordered_map<string, string> mapping;  // keep mapping from device -> mountpoint, since IOKit doesn't give us the mountpoint
+			double uptime = system_uptime();
+			auto &disks_filter = Config::getS("disks_filter");
+			bool filter_exclude = false;
+			// auto only_physical = Config::getB("only_physical");
+			auto &disks = mem.disks;
+			vector<string> filter;
+			if (not disks_filter.empty()) {
+				filter = ssplit(disks_filter);
+				if (filter.at(0).starts_with("exclude=")) {
+					filter_exclude = true;
+					filter.at(0) = filter.at(0).substr(8);
+				}
+			}
+
+			struct statfs *stfs;
+			int count = getmntinfo(&stfs, MNT_WAIT);
+			vector<string> found;
+			found.reserve(last_found.size());
+			for (int i = 0; i < count; i++) {
+				auto fstype = string(stfs[i].f_fstypename);
+				if (fstype == "autofs" || fstype == "devfs" || fstype == "linprocfs" || fstype == "procfs" || fstype == "tmpfs" || fstype == "linsysfs" ||
+					fstype == "fdesckfs") {
+					// in memory filesystems -> not useful to show
+					continue;
+				}
+
+				std::error_code ec;
+				string mountpoint = stfs[i].f_mntonname;
+				string dev = stfs[i].f_mntfromname;
+				mapping[dev] = mountpoint;
+
+				//? Match filter if not empty
+				if (not filter.empty()) {
+					bool match = v_contains(filter, mountpoint);
+					if ((filter_exclude and match) or (not filter_exclude and not match))
+						continue;
+				}
+
+				found.push_back(mountpoint);
+				if (not disks.contains(mountpoint)) {
+					disks[mountpoint] = disk_info{fs::canonical(dev, ec), fs::path(mountpoint).filename()};
+
+					if (disks.at(mountpoint).dev.empty())
+						disks.at(mountpoint).dev = dev;
+
+					if (disks.at(mountpoint).name.empty())
+						disks.at(mountpoint).name = (mountpoint == "/" ? "root" : mountpoint);
+				}
+
+
+				if (not v_contains(last_found, mountpoint))
+					redraw = true;
+
+				disks.at(mountpoint).free = stfs[i].f_bfree;
+				disks.at(mountpoint).total = stfs[i].f_iosize;
+			}
+
+			//? Remove disks no longer mounted or filtered out
+			if (swap_disk and has_swap) found.push_back("swap");
+			for (auto it = disks.begin(); it != disks.end();) {
+				if (not v_contains(found, it->first))
+					it = disks.erase(it);
+				else
+					it++;
+			}
+			if (found.size() != last_found.size()) redraw = true;
+			last_found = std::move(found);
+
+			//? Get disk/partition stats
+			for (auto &[mountpoint, disk] : disks) {
+				if (std::error_code ec; not fs::exists(mountpoint, ec))
+					continue;
+				struct statvfs vfs;
+				if (statvfs(mountpoint.c_str(), &vfs) < 0) {
+					Logger::warning("Failed to get disk/partition stats with statvfs() for: " + mountpoint);
+					continue;
+				}
+				disk.total = vfs.f_blocks * vfs.f_frsize;
+				disk.free = vfs.f_bfree * vfs.f_frsize;
+				disk.used = disk.total - disk.free;
+				if (disk.total != 0) {
+					disk.used_percent = round((double)disk.used * 100 / disk.total);
+					disk.free_percent = 100 - disk.used_percent;
+				} else {
+					disk.used_percent = 0;
+					disk.free_percent = 0;
+				}
+			}
+
+			//? Setup disks order in UI and add swap if enabled
+			mem.disks_order.clear();
+			if (snapped and disks.contains("/mnt"))
+				mem.disks_order.push_back("/mnt");
+			else if (disks.contains("/"))
+				mem.disks_order.push_back("/");
+			if (swap_disk and has_swap) {
+				mem.disks_order.push_back("swap");
+				if (not disks.contains("swap"))
+					disks["swap"] = {"", "swap"};
+				disks.at("swap").total = mem.stats.at("swap_total");
+				disks.at("swap").used = mem.stats.at("swap_used");
+				disks.at("swap").free = mem.stats.at("swap_free");
+				disks.at("swap").used_percent = mem.percent.at("swap_used").back();
+				disks.at("swap").free_percent = mem.percent.at("swap_free").back();
+			}
+			for (const auto &name : last_found)
+				if (not is_in(name, "/", "swap", "/dev"))
+					mem.disks_order.push_back(name);
+
+			disk_ios = 0;
+			collect_disk(disks, mapping);
+
+			old_uptime = uptime;
+		}
+		return mem;
+	}
+
+}  // namespace Mem
+
+namespace Net {
+	std::unordered_map<string, net_info> current_net;
+	net_info empty_net = {};
+	vector<string> interfaces;
+	string selected_iface;
+	int errors = 0;
+	std::unordered_map<string, uint64_t> graph_max = {{"download", {}}, {"upload", {}}};
+	std::unordered_map<string, array<int, 2>> max_count = {{"download", {}}, {"upload", {}}};
+	bool rescale = true;
+	uint64_t timestamp = 0;
+
+	auto collect(bool no_update) -> net_info & {
+		auto &net = current_net;
+		auto &config_iface = Config::getS("net_iface");
+		auto net_sync = Config::getB("net_sync");
+		auto net_auto = Config::getB("net_auto");
+		auto new_timestamp = time_ms();
+
+		if (not no_update and errors < 3) {
+			//? Get interface list using getifaddrs() wrapper
+			IfAddrsPtr if_addrs {};
+			if (if_addrs.get_status() != 0) {
+				errors++;
+				Logger::error("Net::collect() -> getifaddrs() failed with id " + to_string(if_addrs.get_status()));
+				redraw = true;
+				return empty_net;
+			}
+			int family = 0;
+			static_assert(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN); // 46 >= 16, compile-time assurance.
+			enum { IPBUFFER_MAXSIZE = INET6_ADDRSTRLEN }; // manually using the known biggest value, guarded by the above static_assert
+			char ip[IPBUFFER_MAXSIZE];
+			interfaces.clear();
+			string ipv4, ipv6;
+
+			//? Iteration over all items in getifaddrs() list
+			for (auto *ifa = if_addrs.get(); ifa != nullptr; ifa = ifa->ifa_next) {
+				if (ifa->ifa_addr == nullptr) continue;
+				family = ifa->ifa_addr->sa_family;
+				const auto &iface = ifa->ifa_name;
+				//? Update available interfaces vector and get status of interface
+				if (not v_contains(interfaces, iface)) {
+					interfaces.push_back(iface);
+					net[iface].connected = (ifa->ifa_flags & IFF_RUNNING);
+
+					// An interface can have more than one IP of the same family associated with it,
+					// but we pick only the first one to show in the NET box.
+					// Note: Interfaces without any IPv4 and IPv6 set are still valid and monitorable!
+					net[iface].ipv4.clear();
+					net[iface].ipv6.clear();
+				}
+				//? Get IPv4 address
+				if (family == AF_INET) {
+					if (net[iface].ipv4.empty()) {
+						if (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr)->sin_addr), ip, IPBUFFER_MAXSIZE)) {
+
+							net[iface].ipv4 = ip;
+						} else {
+							int errsv = errno;
+							Logger::error("Net::collect() -> Failed to convert IPv4 to string for iface " + string(iface) + ", errno: " + strerror(errsv));
+						}
+					}
+				}
+				//? Get IPv6 address
+				else if (family == AF_INET6) {
+					if (net[iface].ipv6.empty()) {
+						if (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr)->sin6_addr), ip, IPBUFFER_MAXSIZE)) {
+							net[iface].ipv6 = ip;
+						} else {
+							int errsv = errno;
+							Logger::error("Net::collect() -> Failed to convert IPv6 to string for iface " + string(iface) + ", errno: " + strerror(errsv));
+						}
+					}
+				}  //else, ignoring family==AF_LINK (see man 3 getifaddrs)
+			}
+
+			std::unordered_map<string, std::tuple<uint64_t, uint64_t>> ifstats;
+			int mib[] = {CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, 0};
+			size_t len;
+			if (sysctl(mib, 6, nullptr, &len, nullptr, 0) < 0) {
+				Logger::error("failed getting network interfaces");
+			} else {
+				std::unique_ptr<char[]> buf(new char[len]);
+				if (sysctl(mib, 6, buf.get(), &len, nullptr, 0) < 0) {
+					Logger::error("failed getting network interfaces");
+				} else {
+					char *lim = buf.get() + len;
+					char *next = nullptr;
+					for (next = buf.get(); next < lim;) {
+						struct if_msghdr *ifm = (struct if_msghdr *)next;
+						next += ifm->ifm_msglen;
+						struct if_data ifm_data = ifm->ifm_data;
+						if (ifm->ifm_addrs & RTA_IFP) {
+							struct sockaddr_dl *sdl = (struct sockaddr_dl *)(ifm + 1);
+							char iface[32];
+							strncpy(iface, sdl->sdl_data, sdl->sdl_nlen);
+							iface[sdl->sdl_nlen] = 0;
+							ifstats[iface] = std::tuple(ifm_data.ifi_ibytes, ifm_data.ifi_obytes);
+						}
+					}
+				}
+			}
+
+			//? Get total received and transmitted bytes + device address if no ip was found
+			for (const auto &iface : interfaces) {
+				for (const string dir : {"download", "upload"}) {
+					auto &saved_stat = net.at(iface).stat.at(dir);
+					auto &bandwidth = net.at(iface).bandwidth.at(dir);
+					uint64_t val = dir == "download" ? std::get<0>(ifstats[iface]) : std::get<1>(ifstats[iface]);
+
+					//? Update speed, total and top values
+					if (val < saved_stat.last) {
+						saved_stat.rollover += saved_stat.last;
+						saved_stat.last = 0;
+					}
+					if (cmp_greater((unsigned long long)saved_stat.rollover + (unsigned long long)val, numeric_limits<uint64_t>::max())) {
+						saved_stat.rollover = 0;
+						saved_stat.last = 0;
+					}
+					saved_stat.speed = round((double)(val - saved_stat.last) / ((double)(new_timestamp - timestamp) / 1000));
+					if (saved_stat.speed > saved_stat.top) saved_stat.top = saved_stat.speed;
+					if (saved_stat.offset > val + saved_stat.rollover) saved_stat.offset = 0;
+					saved_stat.total = (val + saved_stat.rollover) - saved_stat.offset;
+					saved_stat.last = val;
+
+					//? Add values to graph
+					bandwidth.push_back(saved_stat.speed);
+					while (cmp_greater(bandwidth.size(), width * 2)) bandwidth.pop_front();
+
+					//? Set counters for auto scaling
+					if (net_auto and selected_iface == iface) {
+						if (saved_stat.speed > graph_max[dir]) {
+							++max_count[dir][0];
+							if (max_count[dir][1] > 0) --max_count[dir][1];
+						} else if (graph_max[dir] > 10 << 10 and saved_stat.speed < graph_max[dir] / 10) {
+							++max_count[dir][1];
+							if (max_count[dir][0] > 0) --max_count[dir][0];
+						}
+					}
+				}
+			}
+
+			//? Clean up net map if needed
+			if (net.size() > interfaces.size()) {
+				for (auto it = net.begin(); it != net.end();) {
+					if (not v_contains(interfaces, it->first))
+						it = net.erase(it);
+					else
+						it++;
+				}
+			}
+
+			timestamp = new_timestamp;
+		}
+		//? Return empty net_info struct if no interfaces was found
+		if (net.empty())
+			return empty_net;
+
+		//? Find an interface to display if selected isn't set or valid
+		if (selected_iface.empty() or not v_contains(interfaces, selected_iface)) {
+			max_count["download"][0] = max_count["download"][1] = max_count["upload"][0] = max_count["upload"][1] = 0;
+			redraw = true;
+			if (net_auto) rescale = true;
+			if (not config_iface.empty() and v_contains(interfaces, config_iface))
+				selected_iface = config_iface;
+			else {
+				//? Sort interfaces by total upload + download bytes
+				auto sorted_interfaces = interfaces;
+				rng::sort(sorted_interfaces, [&](const auto &a, const auto &b) {
+					return cmp_greater(net.at(a).stat["download"].total + net.at(a).stat["upload"].total,
+									   net.at(b).stat["download"].total + net.at(b).stat["upload"].total);
+				});
+				selected_iface.clear();
+				//? Try to set to a connected interface
+				for (const auto &iface : sorted_interfaces) {
+					if (net.at(iface).connected) selected_iface = iface;
+					break;
+				}
+				//? If no interface is connected set to first available
+				if (selected_iface.empty() and not sorted_interfaces.empty())
+					selected_iface = sorted_interfaces.at(0);
+				else if (sorted_interfaces.empty())
+					return empty_net;
+			}
+		}
+
+		//? Calculate max scale for graphs if needed
+		if (net_auto) {
+			bool sync = false;
+			for (const auto &dir : {"download", "upload"}) {
+				for (const auto &sel : {0, 1}) {
+					if (rescale or max_count[dir][sel] >= 5) {
+						const long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5
+														? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5
+														: net[selected_iface].stat[dir].speed);
+						graph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10);
+						max_count[dir][0] = max_count[dir][1] = 0;
+						redraw = true;
+						if (net_sync) sync = true;
+						break;
+					}
+				}
+				//? Sync download/upload graphs if enabled
+				if (sync) {
+					const auto other = (string(dir) == "upload" ? "download" : "upload");
+					graph_max[other] = graph_max[dir];
+					max_count[other][0] = max_count[other][1] = 0;
+					break;
+				}
+			}
+		}
+
+		rescale = false;
+		return net.at(selected_iface);
+	}
+}  // namespace Net
+
+namespace Proc {
+
+	vector<proc_info> current_procs;
+	std::unordered_map<string, string> uid_user;
+	string current_sort;
+	string current_filter;
+	bool current_rev = false;
+	bool is_tree_mode;
+
+	fs::file_time_type passwd_time;
+
+	uint64_t cputimes;
+	int collapse = -1, expand = -1, toggle_children = -1;
+	uint64_t old_cputimes = 0;
+	atomic<int> numpids = 0;
+	int filter_found = 0;
+
+	detail_container detailed;
+	static std::unordered_set<size_t> dead_procs;
+
+	string get_status(char s) {
+		if (s & SRUN) return "Running";
+		if (s & SSLEEP) return "Sleeping";
+		if (s & SIDL) return "Idle";
+		if (s & SSTOP) return "Stopped";
+		if (s & SZOMB) return "Zombie";
+		return "Unknown";
+	}
+
+	//* Get detailed info for selected process
+	void _collect_details(const size_t pid, vector<proc_info> &procs) {
+		if (pid != detailed.last_pid) {
+			detailed = {};
+			detailed.last_pid = pid;
+			detailed.skip_smaps = not Config::getB("proc_info_smaps");
+		}
+
+		//? Copy proc_info for process from proc vector
+		auto p_info = rng::find(procs, pid, &proc_info::pid);
+		detailed.entry = *p_info;
+
+		//? Update cpu percent deque for process cpu graph
+		if (not Config::getB("proc_per_core")) detailed.entry.cpu_p *= Shared::coreCount;
+		detailed.cpu_percent.push_back(clamp((long long)round(detailed.entry.cpu_p), 0ll, 100ll));
+		while (cmp_greater(detailed.cpu_percent.size(), width)) detailed.cpu_percent.pop_front();
+
+		//? Process runtime : current time - start time (both in unix time - seconds since epoch)
+		struct timeval currentTime;
+		gettimeofday(&currentTime, nullptr);
+		// only interested in second granularity, so ignoring tc_usec
+		if (detailed.entry.state != 'X') detailed.elapsed = sec_to_dhms(currentTime.tv_sec - detailed.entry.cpu_s); 
+		else detailed.elapsed = sec_to_dhms(detailed.entry.death_time);
+		if (detailed.elapsed.size() > 8) detailed.elapsed.resize(detailed.elapsed.size() - 3);
+
+		//? Get parent process name
+		if (detailed.parent.empty()) {
+			auto p_entry = rng::find(procs, detailed.entry.ppid, &proc_info::pid);
+			if (p_entry != procs.end()) detailed.parent = p_entry->name;
+		}
+
+		//? Expand process status from single char to explanative string
+		detailed.status = get_status(detailed.entry.state);
+
+		detailed.mem_bytes.push_back(detailed.entry.mem);
+		detailed.memory = floating_humanizer(detailed.entry.mem);
+
+		if (detailed.first_mem == -1 or detailed.first_mem < detailed.mem_bytes.back() / 2 or detailed.first_mem > detailed.mem_bytes.back() * 4) {
+			detailed.first_mem = min((uint64_t)detailed.mem_bytes.back() * 2, Mem::get_totalMem());
+			redraw = true;
+		}
+
+		while (cmp_greater(detailed.mem_bytes.size(), width)) detailed.mem_bytes.pop_front();
+
+		// rusage_info_current rusage;
+		// if (proc_pid_rusage(pid, RUSAGE_INFO_CURRENT, (void **)&rusage) == 0) {
+		// 	// this fails for processes we don't own - same as in Linux
+		// 	detailed.io_read = floating_humanizer(rusage.ri_diskio_bytesread);
+		// 	detailed.io_write = floating_humanizer(rusage.ri_diskio_byteswritten);
+		// }
+	}
+
+	//* Collects and sorts process information from /proc
+	auto collect(bool no_update) -> vector<proc_info> & {
+		const auto &sorting = Config::getS("proc_sorting");
+		auto reverse = Config::getB("proc_reversed");
+		const auto &filter = Config::getS("proc_filter");
+		auto per_core = Config::getB("proc_per_core");
+		auto tree = Config::getB("proc_tree");
+		auto show_detailed = Config::getB("show_detailed");
+		const auto pause_proc_list = Config::getB("pause_proc_list");
+		const size_t detailed_pid = Config::getI("detailed_pid");
+		bool should_filter = current_filter != filter;
+		if (should_filter) current_filter = filter;
+		bool sorted_change = (sorting != current_sort or reverse != current_rev or should_filter);
+		bool tree_mode_change = tree != is_tree_mode;
+		if (sorted_change) {
+			current_sort = sorting;
+			current_rev = reverse;
+		}
+		if (tree_mode_change) is_tree_mode = tree;
+
+		const int cmult = (per_core) ? Shared::coreCount : 1;
+		bool got_detailed = false;
+
+		static vector<size_t> found;
+
+		vector<array<long, CPUSTATES>> cpu_time(Shared::coreCount);
+		size_t size = sizeof(long) * CPUSTATES * Shared::coreCount;
+		if (sysctlbyname("kern.cp_times", &cpu_time[0], &size, nullptr, 0) == -1) {
+			Logger::error("failed to get CPU times");
+		}
+		cputimes = 0;
+		for (const auto core : cpu_time) {
+			for (const unsigned int c_state : {CP_USER, CP_NICE, CP_SYS, CP_IDLE}) {
+				cputimes += core[c_state];
+			}
+		}
+
+		//* Use pids from last update if only changing filter, sorting or tree options
+		if (no_update and not current_procs.empty()) {
+			if (show_detailed and detailed_pid != detailed.last_pid) _collect_details(detailed_pid, current_procs);
+		} else {
+			//* ---------------------------------------------Collection start----------------------------------------------
+
+			should_filter = true;
+			found.clear();
+			struct timeval currentTime;
+			gettimeofday(&currentTime, nullptr);
+			const double timeNow = currentTime.tv_sec + (currentTime.tv_usec / 1'000'000);
+
+			int count = 0;
+			char buf[_POSIX2_LINE_MAX];
+			Shared::KvmPtr kd {kvm_openfiles(nullptr, _PATH_DEVNULL, nullptr, O_RDONLY, buf)};
+   			const struct kinfo_proc* kprocs = kvm_getprocs(kd.get(), KERN_PROC_PROC, 0, &count);
+
+   			for (int i = 0; i < count; i++) {
+	  			const struct kinfo_proc* kproc = &kprocs[i];
+				const size_t pid = (size_t)kproc->ki_pid;
+				if (pid < 1) continue;
+				found.push_back(pid);
+
+				//? Check if pid already exists in current_procs
+				bool no_cache = false;
+				auto find_old = rng::find(current_procs, pid, &proc_info::pid);
+				//? Only add new processes if not paused
+				if (find_old == current_procs.end()) {
+					if (not pause_proc_list) {
+						current_procs.push_back({pid});
+						find_old = current_procs.end() - 1;
+						no_cache = true;
+					}
+					else continue;
+				}
+				else if (dead_procs.contains(pid)) continue;
+
+				auto &new_proc = *find_old;
+
+				//? Get program name, command, username, parent pid, nice and status
+				if (no_cache) {
+					if (string(kproc->ki_comm) == "idle"s) {
+						current_procs.pop_back();
+						found.pop_back();
+						continue;
+					}
+					new_proc.name = kproc->ki_comm;
+					char** argv = kvm_getargv(kd.get(), kproc, 0);
+					if (argv) {
+						for (int i = 0; argv[i] and cmp_less(new_proc.cmd.size(), 1000); i++) {
+							new_proc.cmd += argv[i] + " "s;
+						}
+						if (not new_proc.cmd.empty()) new_proc.cmd.pop_back();
+					}
+					if (new_proc.cmd.empty()) new_proc.cmd = new_proc.name;
+					if (new_proc.cmd.size() > 1000) {
+						new_proc.cmd.resize(1000);
+						new_proc.cmd.shrink_to_fit();
+					}
+					new_proc.ppid = kproc->ki_ppid;
+					new_proc.cpu_s = round(kproc->ki_start.tv_sec);
+					struct passwd *pwd = getpwuid(kproc->ki_uid);
+					if (pwd)
+						new_proc.user = pwd->pw_name;
+				}
+				new_proc.p_nice = kproc->ki_nice;
+				new_proc.state = kproc->ki_stat;
+
+				int cpu_t = 0;
+				cpu_t 	= kproc->ki_rusage.ru_utime.tv_sec * 1'000'000 + kproc->ki_rusage.ru_utime.tv_usec
+						+ kproc->ki_rusage.ru_stime.tv_sec * 1'000'000 + kproc->ki_rusage.ru_stime.tv_usec;
+
+				new_proc.mem = kproc->ki_rssize * Shared::pageSize;
+				new_proc.threads = kproc->ki_numthreads;
+
+				//? Process cpu usage since last update
+				new_proc.cpu_p = clamp((100.0 * kproc->ki_pctcpu / Shared::kfscale) * cmult, 0.0, 100.0 * Shared::coreCount);
+
+				//? Process cumulative cpu usage since process start
+				new_proc.cpu_c = (double)(cpu_t * Shared::clkTck / 1'000'000) / max(1.0, timeNow - new_proc.cpu_s);
+
+				//? Update cached value with latest cpu times
+				new_proc.cpu_t = cpu_t;
+
+				if (show_detailed and not got_detailed and new_proc.pid == detailed_pid) {
+					got_detailed = true;
+				}
+			}
+
+			//? Clear dead processes from current_procs if not paused
+			if (not pause_proc_list) {
+				auto eraser = rng::remove_if(current_procs, [&](const auto& element) { return not v_contains(found, element.pid); });
+				current_procs.erase(eraser.begin(), eraser.end());
+				if (!dead_procs.empty()) dead_procs.clear();
+			}
+			//? Set correct state of dead processes if paused
+			else {
+				for (auto& r : current_procs) {
+					if (rng::find(found, r.pid) == found.end()) {
+						if (r.state != 'X') {
+							struct timeval currentTime;
+							gettimeofday(&currentTime, nullptr);
+							r.death_time = currentTime.tv_sec - r.cpu_s;
+						}
+						r.state = 'X';
+						dead_procs.emplace(r.pid);
+						//? Reset cpu usage for dead processes if paused and option is set
+						if (!Config::getB("keep_dead_proc_usage")) {
+							r.cpu_p = 0.0;
+							r.mem = 0;
+						}
+					}
+				}
+			}
+
+			//? Update the details info box for process if active
+			if (show_detailed and got_detailed) {
+				_collect_details(detailed_pid, current_procs);
+			} else if (show_detailed and not got_detailed and detailed.status != "Dead") {
+				detailed.status = "Dead";
+				redraw = true;
+			}
+
+			old_cputimes = cputimes;
+
+		}
+
+		//* ---------------------------------------------Collection done-----------------------------------------------
+
+		//* Match filter if defined
+		if (should_filter) {
+			filter_found = 0;
+			for (auto& p : current_procs) {
+				if (not tree and not filter.empty()) {
+					if (!matches_filter(p, filter)) {
+						p.filtered = true;
+						filter_found++;
+					} else {
+						p.filtered = false;
+					}
+				} else {
+					p.filtered = false;
+				}
+			}
+		}
+
+		//* Sort processes
+		if ((sorted_change or tree_mode_change) or (not no_update and not pause_proc_list)) {
+			proc_sorter(current_procs, sorting, reverse, tree);
+		}
+
+		//* Generate tree view if enabled
+		if (tree and (not no_update or should_filter or sorted_change)) {
+			bool locate_selection = false;
+
+			if (toggle_children != -1) {
+				auto collapser = rng::find(current_procs, toggle_children, &proc_info::pid);
+				if (collapser != current_procs.end()){
+					for (auto& p : current_procs) {
+						if (p.ppid == collapser->pid) {
+							auto child = rng::find(current_procs, p.pid, &proc_info::pid);
+							if (child != current_procs.end()){
+								child->collapsed = not child->collapsed;
+							}
+						}
+					}
+					if (Config::ints.at("proc_selected") > 0) locate_selection = true;
+				}
+				toggle_children = -1;
+			}
+			
+			if (auto find_pid = (collapse != -1 ? collapse : expand); find_pid != -1) {
+				auto collapser = rng::find(current_procs, find_pid, &proc_info::pid);
+				if (collapser != current_procs.end()) {
+					if (collapse == expand) {
+						collapser->collapsed = not collapser->collapsed;
+					}
+					else if (collapse > -1) {
+						collapser->collapsed = true;
+					}
+					else if (expand > -1) {
+						collapser->collapsed = false;
+					}
+					if (Config::ints.at("proc_selected") > 0) locate_selection = true;
+				}
+				collapse = expand = -1;
+			}
+			if (should_filter or not filter.empty()) filter_found = 0;
+
+			vector<tree_proc> tree_procs;
+			tree_procs.reserve(current_procs.size());
+
+			if (!pause_proc_list) {
+				for (auto& p : current_procs) {
+					if (not v_contains(found, p.ppid)) p.ppid = 0;
+				}
+			}
+
+			//? Stable sort to retain selected sorting among processes with the same parent
+			rng::stable_sort(current_procs, rng::less{}, & proc_info::ppid);
+
+			//? Start recursive iteration over processes with the lowest shared parent pids
+			for (auto& p : rng::equal_range(current_procs, current_procs.at(0).ppid, rng::less{}, &proc_info::ppid)) {
+				_tree_gen(p, current_procs, tree_procs, 0, false, filter, false, no_update, should_filter);
+			}
+
+			//? Recursive sort over tree structure to account for collapsed processes in the tree
+			int index = 0;
+			tree_sort(tree_procs, sorting, reverse, (pause_proc_list and not (sorted_change or tree_mode_change)), index, current_procs.size());
+
+			//? Recursive construction of ASCII tree prefixes.
+			for (auto t = tree_procs.begin(); t != tree_procs.end(); ++t) {
+				_collect_prefixes(*t, t == tree_procs.end() - 1);
+			}
+
+			//? Final sort based on tree index
+			rng::stable_sort(current_procs, rng::less {}, &proc_info::tree_index);
+
+			//? Move current selection/view to the selected process when collapsing/expanding in the tree
+			if (locate_selection) {
+				int loc = rng::find(current_procs, Proc::selected_pid, &proc_info::pid)->tree_index;
+				if (Config::ints.at("proc_start") >= loc or Config::ints.at("proc_start") <= loc - Proc::select_max)
+					Config::ints.at("proc_start") = max(0, loc - 1);
+				Config::ints.at("proc_selected") = loc - Config::ints.at("proc_start") + 1;
+			}
+		}
+
+		numpids = (int)current_procs.size() - filter_found;
+		return current_procs;
+	}
+}  // namespace Proc
+
+namespace Tools {
+	double system_uptime() {
+		struct timeval ts, currTime;
+		std::size_t len = sizeof(ts);
+		int mib[2] = {CTL_KERN, KERN_BOOTTIME};
+		if (sysctl(mib, 2, &ts, &len, nullptr, 0) != -1) {
+			gettimeofday(&currTime, nullptr);
+			return currTime.tv_sec - ts.tv_sec;
+		}
+		return 0.0;
+	}
+}  // namespace Tools

+ 3122 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/btop_collect.cpp

@@ -0,0 +1,3122 @@
+/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+	   http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+indent = tab
+tab-size = 4
+*/
+
+#include <algorithm>
+#include <charconv>
+#include <cmath>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <future>
+#include <iterator>
+#include <numeric>
+#include <optional>
+#include <ranges>
+#include <string_view>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <sqlite3.h>
+
+#include <arpa/inet.h> // for inet_ntop()
+#include <dlfcn.h>
+#include <ifaddrs.h>
+#include <net/if.h>
+#include <netdb.h>
+#include <sys/statvfs.h>
+#include <unistd.h>
+
+#if defined(RSMI_STATIC)
+	#include <rocm_smi/rocm_smi.h>
+#endif
+
+#if !(defined(STATIC_BUILD) && defined(__GLIBC__))
+	#include <pwd.h>
+#endif
+
+#include "../btop_shared.hpp"
+#include "../btop_config.hpp"
+#include "../btop_tools.hpp"
+
+#if defined(GPU_SUPPORT)
+	#define class class_
+extern "C" {
+	#include "./intel_gpu_top/intel_gpu_top.h"
+}
+	#undef class
+#endif
+
+using std::abs;
+using std::clamp;
+using std::cmp_greater;
+using std::cmp_less;
+using std::ifstream;
+using std::max;
+using std::min;
+using std::numeric_limits;
+using std::round;
+using std::streamsize;
+using std::vector;
+using std::future;
+using std::async;
+using std::pair;
+
+
+namespace fs = std::filesystem;
+namespace rng = std::ranges;
+
+using namespace Tools;
+using namespace std::literals; // for operator""s
+using namespace std::chrono_literals;
+
+//? --------------------------------------------------- CHAT HISTORY DB -----------------------------------------------------
+namespace AltData {
+	sqlite3* db = nullptr;
+
+	bool init() {
+		if (db) return true;
+		const char* home = getenv("HOME");
+		if (!home) return false;
+		string path = string(home) + "/.projects/chat-vault/services/chat-vault/output/chat_history.db";
+		return sqlite3_open_v2(path.c_str(), &db, SQLITE_OPEN_READONLY, nullptr) == SQLITE_OK;
+	}
+
+	inline void close() {
+		if (db) { sqlite3_close(db); db = nullptr; }
+	}
+
+	long long query_int(const string& sql) {
+		if (!db && !init()) return 0;
+		sqlite3_stmt* stmt = nullptr;
+		long long result = 0;
+		if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, nullptr) == SQLITE_OK) {
+			if (sqlite3_step(stmt) == SQLITE_ROW) result = sqlite3_column_int64(stmt, 0);
+		}
+		if (stmt) sqlite3_finalize(stmt);
+		return result;
+	}
+
+	std::unordered_map<string, long long> query_map(const string& sql) {
+		std::unordered_map<string, long long> res;
+		if (!db && !init()) return res;
+		sqlite3_stmt* stmt = nullptr;
+		if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, nullptr) == SQLITE_OK) {
+			while (sqlite3_step(stmt) == SQLITE_ROW) {
+				const char* key = (const char*)sqlite3_column_text(stmt, 0);
+				if (key) res[key] = sqlite3_column_int64(stmt, 1);
+			}
+		}
+		if (stmt) sqlite3_finalize(stmt);
+		return res;
+	}
+}
+//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------
+
+namespace
+{
+
+long long get_monotonicTimeUSec()
+{
+	struct timespec time;
+	clock_gettime(CLOCK_MONOTONIC, &time);
+	return time.tv_sec * 1000000 + time.tv_nsec / 1000;
+}
+
+}
+
+namespace Cpu {
+	vector<long long> core_old_totals;
+	vector<long long> core_old_idles;
+	vector<fs::path> core_freq;
+	vector<string> available_fields = {"Auto", "total"};
+	vector<string> available_sensors = {"Auto"};
+	cpu_info current_cpu;
+	bool got_sensors{};
+	bool cpu_temp_only{};
+	bool supports_watts = true;
+
+	//* Populate found_sensors map
+	bool get_sensors();
+
+	//* Get current cpu clock speed
+	string get_cpuHz();
+
+	//* Search /proc/cpuinfo for a cpu name
+	string get_cpuName();
+
+	struct Sensor {
+		fs::path path;
+		int64_t temp{};
+		int64_t crit{};
+	};
+
+	std::unordered_map<string, Sensor> found_sensors;
+	string cpu_sensor;
+	vector<string> core_sensors;
+	std::unordered_map<int, int> core_mapping;
+}
+
+namespace Gpu {
+	vector<gpu_info> gpus;
+#ifdef GPU_SUPPORT
+	//? NVIDIA data collection
+	namespace Nvml {
+		//? NVML defines, structs & typedefs
+		#define NVML_DEVICE_NAME_BUFFER_SIZE        64
+		#define NVML_SUCCESS                         0
+		#define NVML_TEMPERATURE_THRESHOLD_SHUTDOWN  0
+		#define NVML_CLOCK_GRAPHICS                  0
+		#define NVML_CLOCK_MEM                       2
+		#define NVML_TEMPERATURE_GPU                 0
+		#define NVML_PCIE_UTIL_TX_BYTES              0
+		#define NVML_PCIE_UTIL_RX_BYTES              1
+
+		typedef void* nvmlDevice_t; // we won't be accessing any of the underlying struct's properties, so this is fine
+		typedef int nvmlReturn_t, // enums are basically ints
+					nvmlTemperatureThresholds_t,
+					nvmlClockType_t,
+					nvmlPstates_t,
+					nvmlTemperatureSensors_t,
+					nvmlPcieUtilCounter_t;
+
+		struct nvmlUtilization_t {unsigned int gpu, memory;};
+		struct nvmlMemory_t {unsigned long long total, free, used;};
+
+		//? Function pointers
+		const char* (*nvmlErrorString)(nvmlReturn_t);
+		nvmlReturn_t (*nvmlInit)();
+		nvmlReturn_t (*nvmlShutdown)();
+		nvmlReturn_t (*nvmlDeviceGetCount)(unsigned int*);
+		nvmlReturn_t (*nvmlDeviceGetHandleByIndex)(unsigned int, nvmlDevice_t*);
+		nvmlReturn_t (*nvmlDeviceGetName)(nvmlDevice_t, char*, unsigned int);
+		nvmlReturn_t (*nvmlDeviceGetPowerManagementLimit)(nvmlDevice_t, unsigned int*);
+		nvmlReturn_t (*nvmlDeviceGetTemperatureThreshold)(nvmlDevice_t, nvmlTemperatureThresholds_t, unsigned int*);
+		nvmlReturn_t (*nvmlDeviceGetUtilizationRates)(nvmlDevice_t, nvmlUtilization_t*);
+		nvmlReturn_t (*nvmlDeviceGetClockInfo)(nvmlDevice_t, nvmlClockType_t, unsigned int*);
+		nvmlReturn_t (*nvmlDeviceGetPowerUsage)(nvmlDevice_t, unsigned int*);
+		nvmlReturn_t (*nvmlDeviceGetPowerState)(nvmlDevice_t, nvmlPstates_t*);
+		nvmlReturn_t (*nvmlDeviceGetTemperature)(nvmlDevice_t, nvmlTemperatureSensors_t, unsigned int*);
+		nvmlReturn_t (*nvmlDeviceGetMemoryInfo)(nvmlDevice_t, nvmlMemory_t*);
+		nvmlReturn_t (*nvmlDeviceGetPcieThroughput)(nvmlDevice_t, nvmlPcieUtilCounter_t, unsigned int*);
+		nvmlReturn_t (*nvmlDeviceGetEncoderUtilization)(nvmlDevice_t, unsigned int*, unsigned int*);
+		nvmlReturn_t (*nvmlDeviceGetDecoderUtilization)(nvmlDevice_t, unsigned int*, unsigned int*);
+
+		//? Data
+		void* nvml_dl_handle;
+		bool initialized = false;
+		bool init();
+		bool shutdown();
+		template <bool is_init> bool collect(gpu_info* gpus_slice);
+		vector<nvmlDevice_t> devices;
+		unsigned int device_count = 0;
+	}
+
+	//? AMD data collection
+	namespace Rsmi {
+
+	//? RSMI defines, structs & typedefs
+	#define RSMI_DEVICE_NAME_BUFFER_SIZE 128
+
+	#if !defined(RSMI_STATIC)
+		#define RSMI_MAX_NUM_FREQUENCIES_V5  32
+		#define RSMI_MAX_NUM_FREQUENCIES_V6  33
+		#define RSMI_STATUS_SUCCESS           0
+		#define RSMI_MEM_TYPE_VRAM            0
+		#define RSMI_TEMP_CURRENT             0
+		#define RSMI_TEMP_TYPE_EDGE           0
+		#define RSMI_CLK_TYPE_MEM             4
+		#define RSMI_CLK_TYPE_SYS             0
+		#define RSMI_TEMP_MAX                 1
+
+		typedef int rsmi_status_t,
+					rsmi_temperature_metric_t,
+					rsmi_clk_type_t,
+					rsmi_memory_type_t;
+
+		struct rsmi_version_t {uint32_t major,  minor,  patch; const char* build;};
+		struct rsmi_frequencies_t_v5 {uint32_t num_supported, current; uint64_t frequency[RSMI_MAX_NUM_FREQUENCIES_V5];};
+		struct rsmi_frequencies_t_v6 {bool has_deep_sleep; uint32_t num_supported, current; uint64_t frequency[RSMI_MAX_NUM_FREQUENCIES_V6];};
+
+		//? Function pointers
+		rsmi_status_t (*rsmi_init)(uint64_t);
+		rsmi_status_t (*rsmi_shut_down)();
+		rsmi_status_t (*rsmi_version_get)(rsmi_version_t*);
+		rsmi_status_t (*rsmi_num_monitor_devices)(uint32_t*);
+		rsmi_status_t (*rsmi_dev_name_get)(uint32_t, char*, size_t);
+		rsmi_status_t (*rsmi_dev_power_cap_get)(uint32_t, uint32_t, uint64_t*);
+		rsmi_status_t (*rsmi_dev_temp_metric_get)(uint32_t, uint32_t, rsmi_temperature_metric_t, int64_t*);
+		rsmi_status_t (*rsmi_dev_busy_percent_get)(uint32_t, uint32_t*);
+		rsmi_status_t (*rsmi_dev_memory_busy_percent_get)(uint32_t, uint32_t*);
+		rsmi_status_t (*rsmi_dev_gpu_clk_freq_get_v5)(uint32_t, rsmi_clk_type_t, rsmi_frequencies_t_v5*);
+		rsmi_status_t (*rsmi_dev_gpu_clk_freq_get_v6)(uint32_t, rsmi_clk_type_t, rsmi_frequencies_t_v6*);
+		rsmi_status_t (*rsmi_dev_power_ave_get)(uint32_t, uint32_t, uint64_t*);
+		rsmi_status_t (*rsmi_dev_memory_total_get)(uint32_t, rsmi_memory_type_t, uint64_t*);
+		rsmi_status_t (*rsmi_dev_memory_usage_get)(uint32_t, rsmi_memory_type_t, uint64_t*);
+		rsmi_status_t (*rsmi_dev_pci_throughput_get)(uint32_t, uint64_t*, uint64_t*, uint64_t*);
+
+		uint32_t version_major = 0;
+
+		//? Data
+		void* rsmi_dl_handle;
+	#endif
+		bool initialized = false;
+		bool init();
+		bool shutdown();
+		template <bool is_init> bool collect(gpu_info* gpus_slice);
+		uint32_t device_count = 0;
+	}
+
+
+	//? Intel data collection
+	namespace Intel {
+		const char* device = "i915";
+		struct engines *engines = nullptr;
+
+		bool initialized = false;
+		bool init();
+		bool shutdown();
+		template <bool is_init> bool collect(gpu_info* gpus_slice);
+		uint32_t device_count = 0;
+	}
+#endif
+}
+
+namespace Mem {
+	double old_uptime;
+}
+
+namespace Shared {
+
+	fs::path procPath, passwd_path;
+	long pageSize, clkTck, coreCount;
+
+	void init() {
+
+		//? Shared global variables init
+		procPath = (fs::is_directory(fs::path("/proc")) and access("/proc", R_OK) != -1) ? "/proc" : "";
+		if (procPath.empty())
+			throw std::runtime_error("Proc filesystem not found or no permission to read from it!");
+
+		passwd_path = (fs::is_regular_file(fs::path("/etc/passwd")) and access("/etc/passwd", R_OK) != -1) ? "/etc/passwd" : "";
+		if (passwd_path.empty())
+			Logger::warning("Could not read /etc/passwd, will show UID instead of username.");
+
+		coreCount = sysconf(_SC_NPROCESSORS_ONLN);
+		if (coreCount < 1) {
+			coreCount = sysconf(_SC_NPROCESSORS_CONF);
+			if (coreCount < 1) {
+				coreCount = 1;
+				Logger::warning("Could not determine number of cores, defaulting to 1.");
+			}
+		}
+
+		pageSize = sysconf(_SC_PAGE_SIZE);
+		if (pageSize <= 0) {
+			pageSize = 4096;
+			Logger::warning("Could not get system page size. Defaulting to 4096, processes memory usage might be incorrect.");
+		}
+
+		clkTck = sysconf(_SC_CLK_TCK);
+		if (clkTck <= 0) {
+			clkTck = 100;
+			Logger::warning("Could not get system clock ticks per second. Defaulting to 100, processes cpu usage might be incorrect.");
+		}
+
+		//? Init for namespace Cpu
+		Cpu::current_cpu.core_percent.insert(Cpu::current_cpu.core_percent.begin(), Shared::coreCount, {});
+		Cpu::current_cpu.temp.insert(Cpu::current_cpu.temp.begin(), Shared::coreCount + 1, {});
+		Cpu::core_old_totals.insert(Cpu::core_old_totals.begin(), Shared::coreCount, 0);
+		Cpu::core_old_idles.insert(Cpu::core_old_idles.begin(), Shared::coreCount, 0);
+
+		for (int i = 0; i < Shared::coreCount; ++i) {
+			Cpu::core_freq.push_back("/sys/devices/system/cpu/cpufreq/policy" + to_string(i) + "/scaling_cur_freq");
+			if (not fs::exists(Cpu::core_freq.back()) or access(Cpu::core_freq.back().c_str(), R_OK) == -1) {
+				Cpu::core_freq.pop_back();
+			}
+		}
+
+		Cpu::collect();
+		if (Runner::coreNum_reset) Runner::coreNum_reset = false;
+		for (auto& [field, vec] : Cpu::current_cpu.cpu_percent) {
+			if (not vec.empty() and not v_contains(Cpu::available_fields, field)) Cpu::available_fields.push_back(field);
+		}
+		Cpu::cpuName = Cpu::get_cpuName();
+		Cpu::got_sensors = Cpu::get_sensors();
+		for (const auto& [sensor, ignored] : Cpu::found_sensors) {
+			Cpu::available_sensors.push_back(sensor);
+		}
+		Cpu::core_mapping = Cpu::get_core_mapping();
+
+		Cpu::container_engine = detect_container();
+
+		//? Init for namespace Gpu
+	#ifdef GPU_SUPPORT
+		auto shown_gpus = Config::getS("shown_gpus");
+		if (shown_gpus.contains("nvidia")) {
+		    Gpu::Nvml::init();
+		}
+
+		if (shown_gpus.contains("amd")) {
+			Gpu::Rsmi::init();
+		}
+
+		if (shown_gpus.contains("intel")) {
+			Gpu::Intel::init();
+		}
+
+		if (not Gpu::gpu_names.empty()) {
+			for (auto const& [key, _] : Gpu::gpus[0].gpu_percent)
+				Cpu::available_fields.push_back(key);
+			for (auto const& [key, _] : Gpu::shared_gpu_percent)
+				Cpu::available_fields.push_back(key);
+
+			using namespace Gpu;
+			count = gpus.size();
+			gpu_b_height_offsets.resize(gpus.size());
+			for (size_t i = 0; i < gpu_b_height_offsets.size(); ++i)
+				gpu_b_height_offsets[i] = gpus[i].supported_functions.gpu_utilization
+					   + gpus[i].supported_functions.pwr_usage
+					   + (gpus[i].supported_functions.encoder_utilization or gpus[i].supported_functions.decoder_utilization)
+					   + (gpus[i].supported_functions.mem_total or gpus[i].supported_functions.mem_used)
+						* (1 + 2*(gpus[i].supported_functions.mem_total and gpus[i].supported_functions.mem_used) + 2*gpus[i].supported_functions.mem_utilization);
+		}
+	#endif
+
+		//? Init for namespace Mem
+		Mem::old_uptime = system_uptime();
+		Mem::collect();
+
+		Logger::debug("Shared::init() : Initialized.");
+	}
+}
+
+namespace Cpu {
+	string cpuName;
+	string cpuHz;
+	bool has_battery = true;
+	tuple<int, float, long, string> current_bat;
+
+	const array time_names {
+		"user"s, "nice"s, "system"s, "idle"s, "iowait"s,
+		"irq"s, "softirq"s, "steal"s, "guest"s, "guest_nice"s
+	};
+
+	std::unordered_map<string, long long> cpu_old = {
+			{"totals", 0},
+			{"idles", 0},
+			{"user", 0},
+			{"nice", 0},
+			{"system", 0},
+			{"idle", 0},
+			{"iowait", 0},
+			{"irq", 0},
+			{"softirq", 0},
+			{"steal", 0},
+			{"guest", 0},
+			{"guest_nice", 0}
+	};
+
+	string get_cpuName() {
+		string name;
+		ifstream cpuinfo(Shared::procPath / "cpuinfo");
+		if (cpuinfo.good()) {
+			for (string instr; getline(cpuinfo, instr, ':') and not instr.starts_with("model name");)
+				cpuinfo.ignore(SSmax, '\n');
+			if (cpuinfo.bad()) return name;
+			else if (not cpuinfo.eof()) {
+				cpuinfo.ignore(1);
+				getline(cpuinfo, name);
+			}
+			else if (fs::exists("/sys/devices")) {
+				for (const auto& d : fs::directory_iterator("/sys/devices")) {
+					if (string(d.path().filename()).starts_with("arm")) {
+						name = d.path().filename();
+						break;
+					}
+				}
+				if (not name.empty()) {
+					auto name_vec = ssplit(name, '_');
+					if (name_vec.size() < 2) return capitalize(name);
+					else return capitalize(name_vec.at(1)) + (name_vec.size() > 2 ? ' ' + capitalize(name_vec.at(2)) : "");
+				}
+
+			}
+
+			name = trim_name(name);
+		}
+
+		return name;
+	}
+
+	bool get_sensors() {
+		bool got_cpu = false, got_coretemp = false;
+		vector<fs::path> search_paths;
+		try {
+			//? Setup up paths to search for sensors
+			if (fs::exists(fs::path("/sys/class/hwmon")) and access("/sys/class/hwmon", R_OK) != -1) {
+				for (const auto& dir : fs::directory_iterator(fs::path("/sys/class/hwmon"))) {
+					fs::path add_path = fs::canonical(dir.path());
+					if (v_contains(search_paths, add_path) or v_contains(search_paths, add_path / "device")) continue;
+
+					if (std::string_view { add_path.c_str() }.contains("coretemp"))
+						got_coretemp = true;
+
+					for (const auto & file : fs::directory_iterator(add_path)) {
+						if (file.path().filename() == "device") {
+							for (const auto & dev_file : fs::directory_iterator(file.path())) {
+								string dev_filename = dev_file.path().filename();
+								if (dev_filename.starts_with("temp") and dev_filename.ends_with("_input")) {
+									search_paths.push_back(file.path());
+									break;
+								}
+							}
+						}
+
+						string filename = file.path().filename();
+						if (filename.starts_with("temp") and filename.ends_with("_input")) {
+							search_paths.push_back(add_path);
+							break;
+						}
+					}
+				}
+			}
+			if (not got_coretemp and fs::exists(fs::path("/sys/devices/platform/coretemp.0/hwmon"))) {
+				for (auto& d : fs::directory_iterator(fs::path("/sys/devices/platform/coretemp.0/hwmon"))) {
+					fs::path add_path = fs::canonical(d.path());
+
+					for (const auto & file : fs::directory_iterator(add_path)) {
+						string filename = file.path().filename();
+						if (filename.starts_with("temp") and filename.ends_with("_input") and not v_contains(search_paths, add_path)) {
+								search_paths.push_back(add_path);
+								got_coretemp = true;
+								break;
+						}
+					}
+				}
+			}
+			//? Scan any found directories for temperature sensors
+			if (not search_paths.empty()) {
+				for (const auto& path : search_paths) {
+					const string pname = readfile(path / "name", path.filename());
+					for (const auto & file : fs::directory_iterator(path)) {
+						const string file_suffix = "input";
+						const int file_id = atoi(file.path().filename().c_str() + 4); // skip "temp" prefix
+						string file_path = file.path();
+
+						if (!file_path.contains(file_suffix) or file_path.contains("nvme")) {
+							continue;
+						}
+
+						const string basepath = file_path.erase(file_path.find(file_suffix), file_suffix.length());
+						const string label = readfile(fs::path(basepath + "label"), "temp" + to_string(file_id));
+						const string sensor_name = pname + "/" + label;
+						const int64_t temp = stol(readfile(fs::path(basepath + "input"), "0")) / 1000;
+						const int64_t crit = stol(readfile(fs::path(basepath + "crit"), "95000")) / 1000;
+
+						found_sensors[sensor_name] = Sensor { fs::path(basepath + "input"), temp, crit };
+
+						if (not got_cpu and (label.starts_with("Package id") or label.starts_with("Tdie") or label.starts_with("SoC Temperature"))) {
+							got_cpu = true;
+							cpu_sensor = sensor_name;
+						}
+						else if (label.starts_with("Core") or label.starts_with("Tccd")) {
+							got_coretemp = true;
+							if (not v_contains(core_sensors, sensor_name)) core_sensors.push_back(sensor_name);
+						}
+					}
+				}
+			}
+			//? If no good candidate for cpu temp has been found scan /sys/class/thermal
+			if (not got_cpu and fs::exists(fs::path("/sys/class/thermal"))) {
+				const string rootpath = fs::path("/sys/class/thermal/thermal_zone");
+				for (int i = 0; fs::exists(fs::path(rootpath + to_string(i))); i++) {
+					const fs::path basepath = rootpath + to_string(i);
+					if (not fs::exists(basepath / "temp")) continue;
+					const string label = readfile(basepath / "type", "temp" + to_string(i));
+					const string sensor_name = "thermal" + to_string(i) + "/" + label;
+					const int64_t temp = stol(readfile(basepath / "temp", "0")) / 1000;
+
+					int64_t high = 0;
+					int64_t crit = 0;
+					for (int ii = 0; fs::exists(basepath / string("trip_point_" + to_string(ii) + "_temp")); ii++) {
+						const string trip_type = readfile(basepath / string("trip_point_" + to_string(ii) + "_type"));
+						if (not is_in(trip_type, "high", "critical")) continue;
+						auto& val = (trip_type == "high" ? high : crit);
+						val = stol(readfile(basepath / string("trip_point_" + to_string(ii) + "_temp"), "0")) / 1000;
+					}
+					if (high < 1) high = 80;
+					if (crit < 1) crit = 95;
+
+					found_sensors[sensor_name] = Sensor { basepath / "temp", temp, crit };
+				}
+			}
+
+		}
+		catch (...) {}
+
+		if (not got_coretemp or core_sensors.empty()) {
+			cpu_temp_only = true;
+		}
+		else {
+			rng::sort(core_sensors, rng::less{});
+			rng::stable_sort(core_sensors, [](const auto& a, const auto& b){
+				return a.size() < b.size();
+			});
+		}
+
+		if (cpu_sensor.empty() and not found_sensors.empty()) {
+			for (const auto& [name, sensor] : found_sensors) {
+				if (str_to_lower(name).contains("cpu") or str_to_lower(name).contains("k10temp")) {
+					cpu_sensor = name;
+					break;
+				}
+			}
+			if (cpu_sensor.empty()) {
+				cpu_sensor = found_sensors.begin()->first;
+				Logger::warning("No good candidate for cpu sensor found, using random from all found sensors.");
+			}
+		}
+
+		return not found_sensors.empty();
+	}
+
+	static void update_sensors() {
+		if (cpu_sensor.empty()) return;
+
+		const auto& cpu_sensor = (not Config::getS("cpu_sensor").empty() and found_sensors.contains(Config::getS("cpu_sensor")) ? Config::getS("cpu_sensor") : Cpu::cpu_sensor);
+
+		found_sensors.at(cpu_sensor).temp = stol(readfile(found_sensors.at(cpu_sensor).path, "0")) / 1000;
+		current_cpu.temp.at(0).push_back(found_sensors.at(cpu_sensor).temp);
+		current_cpu.temp_max = found_sensors.at(cpu_sensor).crit;
+		if (current_cpu.temp.at(0).size() > 20) current_cpu.temp.at(0).pop_front();
+
+		if (Config::getB("show_coretemp") and not cpu_temp_only) {
+			for (vector<string_view> done; const auto& sensor : core_sensors) {
+				if (v_contains(done, sensor)) continue;
+				found_sensors.at(sensor).temp = stol(readfile(found_sensors.at(sensor).path, "0")) / 1000;
+				done.push_back(sensor);
+			}
+			for (const auto& [core, temp] : core_mapping) {
+				if (cmp_less(core + 1, current_cpu.temp.size()) and cmp_less(temp, core_sensors.size())) {
+					current_cpu.temp.at(core + 1).push_back(found_sensors.at(core_sensors.at(temp)).temp);
+					if (current_cpu.temp.at(core + 1).size() > 20) current_cpu.temp.at(core + 1).pop_front();
+				}
+			}
+		}
+	}
+
+	static string normalize_frequency(double hz) {
+		string str;
+		if (hz > 999999) {
+			str = fmt::format("{:.1f}", hz / 1'000'000);
+			str.resize(3);
+			if (str.back() == '.') str.pop_back();
+			str += " THz";
+		}
+		else if (hz > 999) {
+			str = fmt::format("{:.1f}", hz / 1'000);
+			str.resize(3);
+			if (str.back() == '.') str.pop_back();
+			str += " GHz";
+		}
+		else {
+			str = fmt::format("{:.0f} MHz", hz);
+		}
+		return str;
+	}
+
+	string get_cpuHz() {
+		static int failed{};
+
+		if (failed > 4)
+			return ""s;
+
+		string cpuhz;
+
+		const auto &freq_mode = Config::getS("freq_mode");
+
+		try {
+			double hz = 0.0;
+			// Read frequencies from all CPU cores
+			vector<double> frequencies;
+			for (auto it = Cpu::core_freq.begin(); it != Cpu::core_freq.end(); ) {
+    			if (it->empty()) {
+        			it = Cpu::core_freq.erase(it);
+        			continue;
+    			}
+
+    			double core_hz = stod(readfile(*it, "0.0")) / 1000;
+    			if (core_hz <= 0.0 and ++failed >= 2) {
+        			it = Cpu::core_freq.erase(it);
+    			} else {
+        			frequencies.push_back(core_hz);
+        			if (freq_mode == "first") break;
+        			++it;
+    			}
+ 			}
+
+			if (not frequencies.empty()) {
+				if (freq_mode == "first") {
+					hz = frequencies.front();
+				}
+				if (freq_mode == "average") {
+					hz = std::accumulate(frequencies.begin(), frequencies.end(), 0.0) / static_cast<double>(frequencies.size());
+				}
+				else if (freq_mode == "highest") {
+					hz = *std::max_element(frequencies.begin(), frequencies.end());
+				}
+				else if (freq_mode == "lowest") {
+					hz = *std::min_element(frequencies.begin(), frequencies.end());
+				}
+				else if (freq_mode == "range") {
+					auto [min_hz,max_hz] = std::minmax_element(frequencies.begin(), frequencies.end());
+
+					// Format as range
+					string min_str, max_str;
+					min_str = normalize_frequency(*min_hz);
+					max_str = normalize_frequency(*max_hz);
+
+					return min_str + " - " + max_str;
+				}
+			}
+			//? If freq from /sys failed or is missing try to use /proc/cpuinfo
+			if (hz <= 0.0) {
+				ifstream cpufreq(Shared::procPath / "cpuinfo");
+				if (cpufreq.good()) {
+					while (cpufreq.ignore(SSmax, '\n')) {
+						// peek is caps sensitive so it was skipping 'CPU MHz'. This aims to fix it.
+						if (cpufreq.peek() == 'c' || cpufreq.peek() == 'C') {
+							cpufreq.ignore(SSmax, ' ');
+							if (cpufreq.peek() == 'M') {
+								cpufreq.ignore(SSmax, ':');
+								cpufreq.ignore(1);
+								cpufreq >> hz;
+								break;
+							}
+						}
+					}
+				}
+			}
+
+			if (hz <= 1 or hz >= 999999999)
+				throw std::runtime_error("Failed to read /sys/devices/system/cpu/cpufreq/policy and /proc/cpuinfo.");
+
+			cpuhz = normalize_frequency(hz);
+
+		}
+		catch (const std::exception& e) {
+			if (++failed < 5)
+				return ""s;
+			else {
+				Logger::warning("get_cpuHZ() : " + string{e.what()});
+				return ""s;
+			}
+		}
+
+		return cpuhz;
+	}
+
+	auto get_core_mapping() -> std::unordered_map<int, int> {
+		std::unordered_map<int, int> core_map;
+		if (cpu_temp_only) return core_map;
+
+		//? Try to get core mapping from /proc/cpuinfo
+		ifstream cpuinfo(Shared::procPath / "cpuinfo");
+		if (cpuinfo.good()) {
+			int cpu{};
+			int core{};
+			int n{};
+			for (string instr; cpuinfo >> instr;) {
+				if (instr == "processor") {
+					cpuinfo.ignore(SSmax, ':');
+					cpuinfo >> cpu;
+				}
+				else if (instr.starts_with("core")) {
+					cpuinfo.ignore(SSmax, ':');
+					cpuinfo >> core;
+					if (std::cmp_greater_equal(core, core_sensors.size())) {
+						if (std::cmp_greater_equal(n, core_sensors.size())) n = 0;
+						core_map[cpu] = n++;
+					}
+					else
+						core_map[cpu] = core;
+				}
+				cpuinfo.ignore(SSmax, '\n');
+			}
+		}
+
+		//? If core mapping from cpuinfo was incomplete try to guess remainder, if missing completely, map 0-0 1-1 2-2 etc.
+		if (cmp_less(core_map.size(), Shared::coreCount)) {
+			if (Shared::coreCount % 2 == 0 and (long)core_map.size() == Shared::coreCount / 2) {
+				for (int i = 0, n = 0; i < Shared::coreCount / 2; i++) {
+					if (std::cmp_greater_equal(n, core_sensors.size())) n = 0;
+					core_map[Shared::coreCount / 2 + i] = n++;
+				}
+			}
+			else {
+				core_map.clear();
+				for (int i = 0, n = 0; i < Shared::coreCount; i++) {
+					if (std::cmp_greater_equal(n, core_sensors.size())) n = 0;
+					core_map[i] = n++;
+				}
+			}
+		}
+
+		//? Apply user set custom mapping if any
+		const auto& custom_map = Config::getS("cpu_core_map");
+		if (not custom_map.empty()) {
+			try {
+				for (const auto& split : ssplit(custom_map)) {
+					const auto vals = ssplit(split, ':');
+					if (vals.size() != 2) continue;
+					int change_id = std::stoi(vals.at(0));
+					int new_id = std::stoi(vals.at(1));
+					if (not core_map.contains(change_id) or cmp_greater(new_id, core_sensors.size())) continue;
+					core_map.at(change_id) = new_id;
+				}
+			}
+			catch (...) {}
+		}
+
+		return core_map;
+	}
+
+	struct battery {
+		fs::path base_dir, energy_now, charge_now, energy_full, charge_full, power_now, current_now, voltage_now, status, online;
+		string device_type;
+		bool use_energy_or_charge = true;
+		bool use_power = true;
+	};
+
+	auto get_battery() -> tuple<int, float, long, string> {
+		if (not has_battery) return {0, 0, 0, ""};
+		static string auto_sel;
+		static std::unordered_map<string, battery> batteries;
+
+		//? Get paths to needed files and check for valid values on first run
+		if (batteries.empty() and has_battery) {
+			try {
+				if (fs::exists("/sys/class/power_supply")) {
+					for (const auto& d : fs::directory_iterator("/sys/class/power_supply")) {
+						//? Only consider online power supplies of type Battery or UPS
+						//? see kernel docs for details on the file structure and contents
+						//? https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-power
+						battery new_bat;
+						fs::path bat_dir;
+						try {
+							if (not d.is_directory()
+								or not fs::exists(d.path() / "type")
+								or not fs::exists(d.path() / "present")
+								or stoi(readfile(d.path() / "present")) != 1)
+								continue;
+							string dev_type = readfile(d.path() / "type");
+							if (is_in(dev_type, "Battery", "UPS")) {
+								bat_dir = d.path();
+								new_bat.base_dir = d.path();
+								new_bat.device_type = dev_type;
+							}
+						} catch (...) {
+							//? skip power supplies not conforming to the kernel standard
+							continue;
+						}
+
+						if (fs::exists(bat_dir / "energy_now")) new_bat.energy_now = bat_dir / "energy_now";
+						else if (fs::exists(bat_dir / "charge_now")) new_bat.charge_now = bat_dir / "charge_now";
+						else new_bat.use_energy_or_charge = false;
+
+						if (fs::exists(bat_dir / "energy_full")) new_bat.energy_full = bat_dir / "energy_full";
+						else if (fs::exists(bat_dir / "charge_full")) new_bat.charge_full = bat_dir / "charge_full";
+						else new_bat.use_energy_or_charge = false;
+
+						if (not new_bat.use_energy_or_charge and not fs::exists(bat_dir / "capacity")) {
+							continue;
+						}
+
+						if (fs::exists(bat_dir / "power_now")) {
+							new_bat.power_now = bat_dir / "power_now";
+						}
+						else if ((fs::exists(bat_dir / "current_now")) and (fs::exists(bat_dir / "voltage_now"))) {
+							 new_bat.current_now = bat_dir / "current_now";
+							 new_bat.voltage_now = bat_dir / "voltage_now";
+						}
+						else {
+							new_bat.use_power = false;
+						}
+
+						if (fs::exists(bat_dir / "AC0/online")) new_bat.online = bat_dir / "AC0/online";
+						else if (fs::exists(bat_dir / "AC/online")) new_bat.online = bat_dir / "AC/online";
+
+						batteries[bat_dir.filename()] = new_bat;
+						Config::available_batteries.push_back(bat_dir.filename());
+					}
+				}
+			}
+			catch (...) {
+				batteries.clear();
+			}
+			if (batteries.empty()) {
+				has_battery = false;
+				return {0, 0, 0, ""};
+			}
+		}
+
+		auto& battery_sel = Config::getS("selected_battery");
+
+		if (auto_sel.empty()) {
+			for (auto& [name, bat] : batteries) {
+				if (bat.device_type == "Battery") {
+					auto_sel = name;
+					break;
+				}
+			}
+			if (auto_sel.empty()) auto_sel = batteries.begin()->first;
+		}
+
+		auto& b = (battery_sel != "Auto" and batteries.contains(battery_sel) ? batteries.at(battery_sel) : batteries.at(auto_sel));
+
+		int percent = -1;
+		long seconds = -1;
+		float watts = -1;
+
+		//? Try to get battery percentage
+		if (percent < 0) {
+			try {
+				percent = stoi(readfile(b.base_dir / "capacity", "-1"));
+			}
+			catch (const std::invalid_argument&) { }
+			catch (const std::out_of_range&) { }
+		}
+		if (b.use_energy_or_charge and percent < 0) {
+			try {
+				percent = round(100.0 * stod(readfile(b.energy_now, "-1")) / stod(readfile(b.energy_full, "1")));
+			}
+			catch (const std::invalid_argument&) { }
+			catch (const std::out_of_range&) { }
+		}
+		if (b.use_energy_or_charge and percent < 0) {
+			try {
+				percent = round(100.0 * stod(readfile(b.charge_now, "-1")) / stod(readfile(b.charge_full, "1")));
+			}
+			catch (const std::invalid_argument&) { }
+			catch (const std::out_of_range&) { }
+		}
+		if (percent < 0) {
+			has_battery = false;
+			return {0, 0, 0, ""};
+		}
+
+		//? Get charging/discharging status
+		string status = str_to_lower(readfile(b.base_dir / "status", "unknown"));
+		if (status == "unknown" and not b.online.empty()) {
+			const auto online = readfile(b.online, "0");
+			if (online == "1" and percent < 100) status = "charging";
+			else if (online == "1") status = "full";
+			else status = "discharging";
+		}
+
+		//? Get seconds to empty
+		if (not is_in(status, "charging", "full")) {
+			if (b.use_energy_or_charge ) {
+				if (not b.power_now.empty()) {
+					try {
+						seconds = abs(round(stod(readfile(b.energy_now, "0")) / stod(readfile(b.power_now, "1")) * 3600));
+					}
+					catch (const std::invalid_argument&) { }
+					catch (const std::out_of_range&) { }
+				}
+				else if (not b.current_now.empty()) {
+					try {
+						seconds = abs(round(stod(readfile(b.charge_now, "0")) / stod(readfile(b.current_now, "1")) * 3600));
+					}
+					catch (const std::invalid_argument&) { }
+					catch (const std::out_of_range&) { }
+				}
+			}
+
+			if (seconds < 0 and fs::exists(b.base_dir / "time_to_empty")) {
+				try {
+					seconds = stoll(readfile(b.base_dir / "time_to_empty", "0")) * 60;
+				}
+				catch (const std::invalid_argument&) { }
+				catch (const std::out_of_range&) { }
+			}
+		}
+		//? Or get seconds to full
+		else if(is_in(status, "charging")) {
+			if (b.use_energy_or_charge ) {
+				if (not b.power_now.empty()) {
+					try {
+						seconds = (round(stod(readfile(b.energy_full , "0")) - round(stod(readfile(b.energy_now, "0"))))
+									/ abs(stod(readfile(b.power_now, "1"))) * 3600);
+					}
+					catch (const std::invalid_argument&) { }
+					catch (const std::out_of_range&) { }
+				}
+				else if (not b.current_now.empty()) {
+					try {
+						seconds = (round(stod(readfile(b.charge_full , "0")) - stod(readfile(b.charge_now, "0")))
+									/ std::abs(stod(readfile(b.current_now, "1"))) * 3600);
+					}
+					catch (const std::invalid_argument&) { }
+					catch (const std::out_of_range&) { }
+				}
+			}
+		}
+
+		//? Get power draw
+		if (b.use_power) {
+			if (not b.power_now.empty()) {
+				try {
+					watts = stof(readfile(b.power_now, "-1")) / 1000000.0F;
+				}
+				catch (const std::invalid_argument&) { }
+				catch (const std::out_of_range&) { }
+			}
+			else if (not b.voltage_now.empty() and not b.current_now.empty()) {
+				try {
+					watts = stof(readfile(b.current_now, "-1")) / 1000000.0F * stof(readfile(b.voltage_now, "1")) / 1000000.0F;
+				}
+				catch (const std::invalid_argument&) { }
+				catch (const std::out_of_range&) { }
+			}
+
+		}
+
+		return {percent, watts, seconds, status};
+	}
+
+	long long get_cpuConsumptionUJoules()
+	{
+		long long consumption = -1;
+		const auto rapl_power_usage_path = "/sys/class/powercap/intel-rapl:0/energy_uj";
+		std::ifstream file(rapl_power_usage_path);
+		if(file.good())
+		{
+			file >> consumption;
+		}
+		return consumption;
+	}
+
+	float get_cpuConsumptionWatts()
+	{
+		static long long previous_usage = 0;
+		static long long previous_timestamp = 0;
+
+		if (previous_usage == 0)
+		{
+			previous_usage = get_cpuConsumptionUJoules();
+			previous_timestamp = get_monotonicTimeUSec();
+			supports_watts = (previous_usage > 0);
+			return 0;
+		}
+
+		if (!supports_watts)
+		{
+			return -1;
+		}
+
+		auto current_timestamp = get_monotonicTimeUSec();
+		auto current_usage = get_cpuConsumptionUJoules();
+
+		auto watts = (float)(current_usage - previous_usage) / (float)(current_timestamp - previous_timestamp);
+
+		previous_timestamp = current_timestamp;
+		previous_usage = current_usage;
+
+		return watts;
+	}
+
+    static constexpr auto to_int(std::string_view view) {
+        std::uint32_t value {};
+        std::from_chars(view.data(), view.data() + view.size(), value);
+        return value;
+    }
+
+    static constexpr auto detect_active_cpus() {
+        auto stream = std::ifstream { "/sys/fs/cgroup/cpuset.cpus.effective" };
+        auto buf = std::string { std::istreambuf_iterator<char> { stream }, {} };
+
+        if (buf.empty()) {
+            std::vector<std::int32_t> result;
+            for (int i = 0; i < Shared::coreCount; ++i) result.push_back(i);
+            return result;
+        }
+
+        std::vector<std::int32_t> result;
+        std::stringstream ss(buf);
+        std::string token;
+        while (std::getline(ss, token, ',')) {
+            auto dash = token.find('-');
+            if (dash == std::string::npos) {
+                result.push_back(std::stoi(token));
+            } else {
+                int start = std::stoi(token.substr(0, dash));
+                int end = std::stoi(token.substr(dash + 1));
+                for (int i = start; i <= end; ++i) result.push_back(i);
+            }
+        }
+        return result;
+    }
+
+	auto collect(bool no_update) -> cpu_info& {
+		if (Runner::stopping or (no_update and not current_cpu.cpu_percent.at("total").empty())) return current_cpu;
+		auto& cpu = current_cpu;
+
+		if (Config::getB("show_cpu_freq"))
+			cpuHz = get_cpuHz();
+
+		if (getloadavg(cpu.load_avg.data(), cpu.load_avg.size()) < 0) {
+			Logger::error("failed to get load averages");
+		}
+
+		ifstream cread;
+
+		try {
+			//? Get cpu total times for all cores from /proc/stat
+			string cpu_name;
+			cread.open(Shared::procPath / "stat");
+			int i = 0;
+			int target = Shared::coreCount;
+			for (; i <= target or (cread.good() and cread.peek() == 'c'); i++) {
+				//? Make sure to add zero value for missing core values if at end of file
+				if ((not cread.good() or cread.peek() != 'c') and i <= target) {
+					if (i == 0) throw std::runtime_error("Failed to parse /proc/stat");
+					else {
+						//? Fix container sizes if new cores are detected
+						while (cmp_less(cpu.core_percent.size(), i)) {
+							core_old_totals.push_back(0);
+							core_old_idles.push_back(0);
+							cpu.core_percent.emplace_back();
+						}
+						cpu.core_percent.at(i-1).push_back(0);
+					}
+				}
+				else {
+					if (i == 0) cread.ignore(SSmax, ' ');
+					else {
+						cread >> cpu_name;
+						int cpuNum = std::stoi(cpu_name.substr(3));
+						if (cpuNum >= target - 1) target = cpuNum + (cread.peek() == 'c' ? 2 : 1);
+
+						//? Add zero value for core if core number is missing from /proc/stat
+						while (i - 1 < cpuNum) {
+							//? Fix container sizes if new cores are detected
+							while (cmp_less(cpu.core_percent.size(), i)) {
+								core_old_totals.push_back(0);
+								core_old_idles.push_back(0);
+								cpu.core_percent.emplace_back();
+							}
+							cpu.core_percent[i-1].push_back(0);
+							if (cpu.core_percent.at(i-1).size() > 40) cpu.core_percent.at(i-1).pop_front();
+							i++;
+						}
+					}
+
+					//? 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
+					vector<long long> times;
+					long long total_sum = 0;
+
+					for (uint64_t val; cread >> val; total_sum += val) {
+						times.push_back(val);
+					}
+					cread.clear();
+					if (times.size() < 4) throw std::runtime_error("Malformed /proc/stat");
+
+					//? Subtract fields 8-9 and any future unknown fields
+					const long long totals = max(0ll, total_sum - (times.size() > 8 ? std::accumulate(times.begin() + 8, times.end(), 0ll) : 0));
+
+					//? Add iowait field if present
+					const long long idles = max(0ll, times.at(3) + (times.size() > 4 ? times.at(4) : 0));
+
+					//? Calculate values for totals from first line of stat
+					if (i == 0) {
+						const long long calc_totals = max(1ll, totals - cpu_old.at("totals"));
+						const long long calc_idles = max(0ll, idles - cpu_old.at("idles"));
+						cpu_old.at("totals") = totals;
+						cpu_old.at("idles") = idles;
+
+						//? Total usage of cpu
+						cpu.cpu_percent.at("total").push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));
+
+						//? Reduce size if there are more values than needed for graph
+						while (cmp_greater(cpu.cpu_percent.at("total").size(), width * 2)) cpu.cpu_percent.at("total").pop_front();
+
+						//? Populate cpu.cpu_percent with all fields from stat
+						for (int ii = 0; const auto& val : times) {
+							cpu.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));
+							cpu_old.at(time_names.at(ii)) = val;
+
+							//? Reduce size if there are more values than needed for graph
+							while (cmp_greater(cpu.cpu_percent.at(time_names.at(ii)).size(), width * 2)) cpu.cpu_percent.at(time_names.at(ii)).pop_front();
+
+							if (++ii == 10) break;
+						}
+						continue;
+					}
+					//? Calculate cpu total for each core
+					else {
+						//? Fix container sizes if new cores are detected
+						while (cmp_less(cpu.core_percent.size(), i)) {
+							core_old_totals.push_back(0);
+							core_old_idles.push_back(0);
+							cpu.core_percent.emplace_back();
+						}
+						const long long calc_totals = max(1ll, totals - core_old_totals.at(i-1));
+						const long long calc_idles = max(0ll, idles - core_old_idles.at(i-1));
+						core_old_totals.at(i-1) = totals;
+						core_old_idles.at(i-1) = idles;
+
+						cpu.core_percent.at(i-1).push_back(clamp((long long)round((double)(calc_totals - calc_idles) * 100 / calc_totals), 0ll, 100ll));
+					}
+				}
+
+				//? Reduce size if there are more values than needed for graph
+				if (cpu.core_percent.at(i-1).size() > 40) cpu.core_percent.at(i-1).pop_front();
+			}
+
+			//? Notify main thread to redraw screen if we found more cores than previously detected
+			if (cmp_greater(cpu.core_percent.size(), Shared::coreCount)) {
+				Logger::debug("Changing CPU max corecount from " + to_string(Shared::coreCount) + " to " + to_string(cpu.core_percent.size()) + ".");
+				Runner::coreNum_reset = true;
+				Shared::coreCount = cpu.core_percent.size();
+				while (cmp_less(current_cpu.temp.size(), cpu.core_percent.size() + 1)) current_cpu.temp.push_back({0});
+			}
+
+		}
+		catch (const std::exception& e) {
+			Logger::debug("Cpu::collect() : " + string{e.what()});
+			if (cread.bad()) throw std::runtime_error("Failed to read /proc/stat");
+			else throw std::runtime_error("Cpu::collect() : " + string{e.what()});
+		}
+
+		if (Config::getB("check_temp") and got_sensors)
+			update_sensors();
+
+		if (Config::getB("show_battery") and has_battery)
+			current_bat = get_battery();
+
+		if (Config::getB("show_cpu_watts") and supports_watts)
+			current_cpu.usage_watts = get_cpuConsumptionWatts();
+
+		cpu.active_cpus = std::make_optional(detect_active_cpus());
+
+		return cpu;
+	}
+}
+
+#ifdef GPU_SUPPORT
+namespace Gpu {
+    //? NVIDIA
+    namespace Nvml {
+		bool init() {
+			if (initialized) return false;
+
+			//? Dynamic loading & linking
+			//? Try possible library names for libnvidia-ml.so
+			const array libNvAlts = {
+				"libnvidia-ml.so",
+				"libnvidia-ml.so.1",
+			};
+
+			for (const auto& l : libNvAlts) {
+				nvml_dl_handle = dlopen(l, RTLD_LAZY);
+				if (nvml_dl_handle != nullptr) {
+					break;
+				}
+			}
+ 			if (!nvml_dl_handle) {
+				Logger::info("Failed to load libnvidia-ml.so, NVIDIA GPUs will not be detected: "s + dlerror());
+ 				return false;
+ 			}
+
+			auto load_nvml_sym = [&](const char sym_name[]) {
+				auto sym = dlsym(nvml_dl_handle, sym_name);
+				auto err = dlerror();
+				if (err != nullptr) {
+					Logger::error(string("NVML: Couldn't find function ") + sym_name + ": " + err);
+					return (void*)nullptr;
+				} else return sym;
+			};
+
+            #define LOAD_SYM(NAME)  if ((NAME = (decltype(NAME))load_nvml_sym(#NAME)) == nullptr) return false
+
+		    LOAD_SYM(nvmlErrorString);
+		    LOAD_SYM(nvmlInit);
+		    LOAD_SYM(nvmlShutdown);
+		    LOAD_SYM(nvmlDeviceGetCount);
+		    LOAD_SYM(nvmlDeviceGetHandleByIndex);
+		    LOAD_SYM(nvmlDeviceGetName);
+		    LOAD_SYM(nvmlDeviceGetPowerManagementLimit);
+		    LOAD_SYM(nvmlDeviceGetTemperatureThreshold);
+		    LOAD_SYM(nvmlDeviceGetUtilizationRates);
+		    LOAD_SYM(nvmlDeviceGetClockInfo);
+		    LOAD_SYM(nvmlDeviceGetPowerUsage);
+		    LOAD_SYM(nvmlDeviceGetPowerState);
+		    LOAD_SYM(nvmlDeviceGetTemperature);
+		    LOAD_SYM(nvmlDeviceGetMemoryInfo);
+		    LOAD_SYM(nvmlDeviceGetPcieThroughput);
+			LOAD_SYM(nvmlDeviceGetEncoderUtilization);
+			LOAD_SYM(nvmlDeviceGetDecoderUtilization);
+
+            #undef LOAD_SYM
+
+			//? Function calls
+			nvmlReturn_t result = nvmlInit();
+    		if (result != NVML_SUCCESS) {
+    			Logger::debug(std::string("Failed to initialize NVML, NVIDIA GPUs will not be detected: ") + nvmlErrorString(result));
+    			return false;
+    		}
+
+			//? Device count
+			result = nvmlDeviceGetCount(&device_count);
+    		if (result != NVML_SUCCESS) {
+    			Logger::warning(std::string("NVML: Failed to get device count: ") + nvmlErrorString(result));
+    			return false;
+    		}
+
+			if (device_count > 0) {
+				devices.resize(device_count);
+				gpus.resize(device_count);
+				gpu_names.resize(device_count);
+
+				initialized = true;
+
+				//? Check supported functions & get maximums
+				Nvml::collect<1>(gpus.data());
+
+				return true;
+			} else {initialized = true; shutdown(); return false;}
+		}
+
+		bool shutdown() {
+			if (!initialized) return false;
+			nvmlReturn_t result = nvmlShutdown();
+			if (NVML_SUCCESS == result) {
+				initialized = false;
+				dlclose(nvml_dl_handle);
+			} else Logger::warning(std::string("Failed to shutdown NVML: ") + nvmlErrorString(result));
+
+			return !initialized;
+		}
+
+		template <bool is_init> // collect<1> is called in Nvml::init(), and populates gpus.supported_functions
+		bool collect(gpu_info* gpus_slice) { // raw pointer to vector data, size == device_count
+			if (!initialized) return false;
+
+			nvmlReturn_t result;
+			std::thread pcie_tx_thread, pcie_rx_thread;
+			// DebugTimer nvTotalTimer("Nvidia Total");
+			for (unsigned int i = 0; i < device_count; ++i) {
+				if constexpr(is_init) {
+					//? Device Handle
+    				result = nvmlDeviceGetHandleByIndex(i, devices.data() + i);
+        			if (result != NVML_SUCCESS) {
+    					Logger::warning(std::string("NVML: Failed to get device handle: ") + nvmlErrorString(result));
+						gpus[i].supported_functions = {false, false, false, false, false, false, false, false, false, false};
+    					continue;
+        			}
+
+					//? Device name
+					char name[NVML_DEVICE_NAME_BUFFER_SIZE];
+    				result = nvmlDeviceGetName(devices[i], name, NVML_DEVICE_NAME_BUFFER_SIZE);
+        			if (result != NVML_SUCCESS)
+    					Logger::warning(std::string("NVML: Failed to get device name: ") + nvmlErrorString(result));
+        			else {
+        				gpu_names[i] = string(name);
+        				for (const auto& brand : {"NVIDIA", "Nvidia", "(R)", "(TM)"}) {
+							gpu_names[i] = s_replace(gpu_names[i], brand, "");
+						}
+						gpu_names[i] = trim(gpu_names[i]);
+        			}
+
+    				//? Power usage
+    				unsigned int max_power;
+    				result = nvmlDeviceGetPowerManagementLimit(devices[i], &max_power);
+    				if (result != NVML_SUCCESS)
+						Logger::warning(std::string("NVML: Failed to get maximum GPU power draw, defaulting to 225W: ") + nvmlErrorString(result));
+					else {
+						gpus[i].pwr_max_usage = max_power; // RSMI reports power in microWatts
+						gpu_pwr_total_max += max_power;
+					}
+
+					//? Get temp_max
+					unsigned int temp_max;
+    				result = nvmlDeviceGetTemperatureThreshold(devices[i], NVML_TEMPERATURE_THRESHOLD_SHUTDOWN, &temp_max);
+        			if (result != NVML_SUCCESS)
+    					Logger::warning(std::string("NVML: Failed to get maximum GPU temperature, defaulting to 110°C: ") + nvmlErrorString(result));
+    				else gpus[i].temp_max = (long long)temp_max;
+				}
+
+				//? PCIe link speeds, the data collection takes >=20ms each call so they run on separate threads
+				if (gpus_slice[i].supported_functions.pcie_txrx and (Config::getB("nvml_measure_pcie_speeds") or is_init)) {
+					pcie_tx_thread = std::thread([gpus_slice, i]() {
+						unsigned int tx;
+						nvmlReturn_t result = nvmlDeviceGetPcieThroughput(devices[i], NVML_PCIE_UTIL_TX_BYTES, &tx);
+    					if (result != NVML_SUCCESS) {
+							Logger::warning(std::string("NVML: Failed to get PCIe TX throughput: ") + nvmlErrorString(result));
+							if constexpr(is_init) gpus_slice[i].supported_functions.pcie_txrx = false;
+						} else gpus_slice[i].pcie_tx = (long long)tx;
+					});
+
+					pcie_rx_thread = std::thread([gpus_slice, i]() {
+						unsigned int rx;
+						nvmlReturn_t result = nvmlDeviceGetPcieThroughput(devices[i], NVML_PCIE_UTIL_RX_BYTES, &rx);
+    					if (result != NVML_SUCCESS) {
+							Logger::warning(std::string("NVML: Failed to get PCIe RX throughput: ") + nvmlErrorString(result));
+						} else gpus_slice[i].pcie_rx = (long long)rx;
+					});
+				}
+
+				// DebugTimer nvTimer("Nv utilization");
+				//? GPU & memory utilization
+				if (gpus_slice[i].supported_functions.gpu_utilization) {
+					nvmlUtilization_t utilization;
+					result = nvmlDeviceGetUtilizationRates(devices[i], &utilization);
+    				if (result != NVML_SUCCESS) {
+						Logger::warning(std::string("NVML: Failed to get GPU utilization: ") + nvmlErrorString(result));
+						if constexpr(is_init) gpus_slice[i].supported_functions.gpu_utilization = false;
+						if constexpr(is_init) gpus_slice[i].supported_functions.mem_utilization = false;
+    				} else {
+						gpus_slice[i].gpu_percent.at("gpu-totals").push_back((long long)utilization.gpu);
+						gpus_slice[i].mem_utilization_percent.push_back((long long)utilization.memory);
+    				}
+				}
+
+				// nvTimer.stop_rename_reset("Nv clock");
+				//? Clock speeds
+				if (gpus_slice[i].supported_functions.gpu_clock) {
+					unsigned int gpu_clock;
+					result = nvmlDeviceGetClockInfo(devices[i], NVML_CLOCK_GRAPHICS, &gpu_clock);
+    				if (result != NVML_SUCCESS) {
+						Logger::warning(std::string("NVML: Failed to get GPU clock speed: ") + nvmlErrorString(result));
+						if constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false;
+					} else gpus_slice[i].gpu_clock_speed = (long long)gpu_clock;
+				}
+
+				if (gpus_slice[i].supported_functions.mem_clock) {
+					unsigned int mem_clock;
+					result = nvmlDeviceGetClockInfo(devices[i], NVML_CLOCK_MEM, &mem_clock);
+    				if (result != NVML_SUCCESS) {
+						Logger::warning(std::string("NVML: Failed to get VRAM clock speed: ") + nvmlErrorString(result));
+						if constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false;
+					} else gpus_slice[i].mem_clock_speed = (long long)mem_clock;
+				}
+
+				// nvTimer.stop_rename_reset("Nv power");
+    			//? Power usage & state
+				if (gpus_slice[i].supported_functions.pwr_usage) {
+    				unsigned int power;
+    				result = nvmlDeviceGetPowerUsage(devices[i], &power);
+    				if (result != NVML_SUCCESS) {
+						Logger::warning(std::string("NVML: Failed to get GPU power usage: ") + nvmlErrorString(result));
+						if constexpr(is_init) gpus_slice[i].supported_functions.pwr_usage = false;
+    				} else {
+    					gpus_slice[i].pwr_usage = (long long)power;
+						if (gpus_slice[i].pwr_usage > gpus_slice[i].pwr_max_usage)
+								gpus_slice[i].pwr_max_usage = gpus_slice[i].pwr_usage;
+    					gpus_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));
+    				}
+    			}
+
+				if (gpus_slice[i].supported_functions.pwr_state) {
+					nvmlPstates_t pState;
+    				result = nvmlDeviceGetPowerState(devices[i], &pState);
+    				if (result != NVML_SUCCESS) {
+						Logger::warning(std::string("NVML: Failed to get GPU power state: ") + nvmlErrorString(result));
+						if constexpr(is_init) gpus_slice[i].supported_functions.pwr_state = false;
+    				} else gpus_slice[i].pwr_state = static_cast<int>(pState);
+    			}
+
+				// nvTimer.stop_rename_reset("Nv temp");
+    			//? GPU temperature
+				if (gpus_slice[i].supported_functions.temp_info) {
+    				if (Config::getB("check_temp")) {
+						unsigned int temp;
+						nvmlReturn_t result = nvmlDeviceGetTemperature(devices[i], NVML_TEMPERATURE_GPU, &temp);
+    					if (result != NVML_SUCCESS) {
+							Logger::warning(std::string("NVML: Failed to get GPU temperature: ") + nvmlErrorString(result));
+							if constexpr(is_init) gpus_slice[i].supported_functions.temp_info = false;
+    					} else gpus_slice[i].temp.push_back((long long)temp);
+					}
+				}
+
+				// nvTimer.stop_rename_reset("Nv mem");
+				//? Memory info
+				if (gpus_slice[i].supported_functions.mem_total) {
+					nvmlMemory_t memory;
+					result = nvmlDeviceGetMemoryInfo(devices[i], &memory);
+    				if (result != NVML_SUCCESS) {
+						Logger::warning(std::string("NVML: Failed to get VRAM info: ") + nvmlErrorString(result));
+						if constexpr(is_init) gpus_slice[i].supported_functions.mem_total = false;
+						if constexpr(is_init) gpus_slice[i].supported_functions.mem_used = false;
+					} else {
+						gpus_slice[i].mem_total = memory.total;
+						gpus_slice[i].mem_used = memory.used;
+						//gpu.mem_free = memory.free;
+
+						auto used_percent = (long long)round((double)memory.used * 100.0 / (double)memory.total);
+						gpus_slice[i].gpu_percent.at("gpu-vram-totals").push_back(used_percent);
+					}
+				}
+
+				// nvTimer.stop_rename_reset("Nv enc");
+				//? Encoder info
+				if (gpus_slice[i].supported_functions.encoder_utilization) {
+					unsigned int utilization;
+					unsigned int samplingPeriodUs;
+					result = nvmlDeviceGetEncoderUtilization(devices[i], &utilization, &samplingPeriodUs);
+					if (result != NVML_SUCCESS) {
+						Logger::warning(std::string("NVML: Failed to get encoder utilization: ") + nvmlErrorString(result));
+						if constexpr(is_init) gpus_slice[i].supported_functions.encoder_utilization = false;
+					} else gpus_slice[i].encoder_utilization = (long long)utilization;
+				}
+
+				// nvTimer.stop_rename_reset("Nv dec");
+				//? Decoder info
+				if (gpus_slice[i].supported_functions.decoder_utilization) {
+					unsigned int utilization;
+					unsigned int samplingPeriodUs;
+					result = nvmlDeviceGetDecoderUtilization(devices[i], &utilization, &samplingPeriodUs);
+					if (result != NVML_SUCCESS) {
+						Logger::warning(std::string("NVML: Failed to get decoder utilization: ") + nvmlErrorString(result));
+						if constexpr(is_init) gpus_slice[i].supported_functions.decoder_utilization = false;
+					} else gpus_slice[i].decoder_utilization = (long long)utilization;
+				}
+
+    			//? TODO: Processes using GPU
+    				/*unsigned int proc_info_len;
+    				nvmlProcessInfo_t* proc_info = 0;
+    				result = nvmlDeviceGetComputeRunningProcesses_v3(device, &proc_info_len, proc_info);
+    				if (result != NVML_SUCCESS) {
+						Logger::warning(std::string("NVML: Failed to get compute processes: ") + nvmlErrorString(result));
+    				} else {
+    					for (unsigned int i = 0; i < proc_info_len; ++i)
+    						gpus_slice[i].graphics_processes.push_back({proc_info[i].pid, proc_info[i].usedGpuMemory});
+    				}*/
+
+				// nvTimer.stop_rename_reset("Nv pcie thread join");
+				//? Join PCIE TX/RX threads
+				if 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
+					pcie_tx_thread.join();
+					pcie_rx_thread.join();
+				} else if (gpus_slice[i].supported_functions.pcie_txrx and Config::getB("nvml_measure_pcie_speeds")) {
+					pcie_tx_thread.join();
+					pcie_rx_thread.join();
+				}
+    		}
+
+			return true;
+		}
+    }
+
+	//? AMD
+	namespace Rsmi {
+		bool init() {
+			if (initialized) return false;
+
+			//? Dynamic loading & linking
+		#if !defined(RSMI_STATIC)
+
+			//? Try possible library paths and names for librocm_smi64.so
+			const array libRocAlts = {
+				"/opt/rocm/lib/librocm_smi64.so",
+				"librocm_smi64.so",
+				"librocm_smi64.so.5", // fedora
+				"librocm_smi64.so.1.0", // debian
+				"librocm_smi64.so.6"
+			};
+
+			for (const auto& l : libRocAlts) {
+				rsmi_dl_handle = dlopen(l, RTLD_LAZY);
+				if (rsmi_dl_handle != nullptr) {
+					break;
+				}
+ 			}
+
+			if (!rsmi_dl_handle) {
+				Logger::info("Failed to load librocm_smi64.so, AMD GPUs will not be detected: "s + dlerror());
+				return false;
+			}
+
+			auto load_rsmi_sym = [&](const char sym_name[]) {
+				auto sym = dlsym(rsmi_dl_handle, sym_name);
+				auto err = dlerror();
+				if (err != nullptr) {
+					Logger::error(string("ROCm SMI: Couldn't find function ") + sym_name + ": " + err);
+					return (void*)nullptr;
+				} else return sym;
+			};
+
+            #define LOAD_SYM(NAME)  if ((NAME = (decltype(NAME))load_rsmi_sym(#NAME)) == nullptr) return false
+
+		    LOAD_SYM(rsmi_init);
+		    LOAD_SYM(rsmi_shut_down);
+			LOAD_SYM(rsmi_version_get);
+		    LOAD_SYM(rsmi_num_monitor_devices);
+		    LOAD_SYM(rsmi_dev_name_get);
+		    LOAD_SYM(rsmi_dev_power_cap_get);
+		    LOAD_SYM(rsmi_dev_temp_metric_get);
+		    LOAD_SYM(rsmi_dev_busy_percent_get);
+		    LOAD_SYM(rsmi_dev_memory_busy_percent_get);
+		    LOAD_SYM(rsmi_dev_power_ave_get);
+		    LOAD_SYM(rsmi_dev_memory_total_get);
+		    LOAD_SYM(rsmi_dev_memory_usage_get);
+		    LOAD_SYM(rsmi_dev_pci_throughput_get);
+
+            #undef LOAD_SYM
+        #endif
+
+			//? Function calls
+			rsmi_status_t result = rsmi_init(0);
+			if (result != RSMI_STATUS_SUCCESS) {
+				Logger::debug("Failed to initialize ROCm SMI, AMD GPUs will not be detected");
+				return false;
+			}
+
+		#if !defined(RSMI_STATIC)
+			//? Check version
+			rsmi_version_t version;
+			result = rsmi_version_get(&version);
+			if (result != RSMI_STATUS_SUCCESS) {
+				Logger::warning("ROCm SMI: Failed to get version");
+				return false;
+			} else if (version.major == 5) {
+				if ((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)
+					return false;
+			// 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
+			} else if (version.major == 6 || version.major == 7) {
+				if ((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)
+					return false;
+			} else {
+				Logger::warning("ROCm SMI: Dynamic loading only supported for version 5 and 6");
+				return false;
+			}
+			version_major = version.major;
+		#endif
+
+			//? Device count
+			result = rsmi_num_monitor_devices(&device_count);
+			if (result != RSMI_STATUS_SUCCESS) {
+				Logger::warning("ROCm SMI: Failed to fetch number of devices");
+				return false;
+			}
+
+			if (device_count > 0) {
+				gpus.resize(gpus.size() + device_count);
+				gpu_names.resize(gpus.size() + device_count);
+
+				initialized = true;
+
+				//? Check supported functions & get maximums
+				Rsmi::collect<1>(gpus.data() + Nvml::device_count);
+
+				return true;
+			} else {initialized = true; shutdown(); return false;}
+		}
+
+		bool shutdown() {
+			if (!initialized) return false;
+    		if (rsmi_shut_down() == RSMI_STATUS_SUCCESS) {
+				initialized = false;
+			#if !defined(RSMI_STATIC)
+				dlclose(rsmi_dl_handle);
+			#endif
+			} else Logger::warning("Failed to shutdown ROCm SMI");
+
+			return true;
+		}
+
+		template <bool is_init>
+		bool collect(gpu_info* gpus_slice) { // raw pointer to vector data, size == device_count, offset by Nvml::device_count elements
+			if (!initialized) return false;
+			rsmi_status_t result;
+
+			for (uint32_t i = 0; i < device_count; ++i) {
+				if constexpr(is_init) {
+					//? Device name
+					char name[RSMI_DEVICE_NAME_BUFFER_SIZE];
+    				result = rsmi_dev_name_get(i, name, RSMI_DEVICE_NAME_BUFFER_SIZE);
+        			if (result != RSMI_STATUS_SUCCESS)
+    					Logger::warning("ROCm SMI: Failed to get device name");
+        			else gpu_names[Nvml::device_count + i] = string(name);
+
+    				//? Power usage
+    				uint64_t max_power;
+    				result = rsmi_dev_power_cap_get(i, 0, &max_power);
+    				if (result != RSMI_STATUS_SUCCESS)
+						Logger::warning("ROCm SMI: Failed to get maximum GPU power draw, defaulting to 225W");
+					else {
+						gpus_slice[i].pwr_max_usage = (long long)(max_power/1000); // RSMI reports power in microWatts
+						gpu_pwr_total_max += gpus_slice[i].pwr_max_usage;
+					}
+
+					//? Get temp_max
+					int64_t temp_max;
+    				result = rsmi_dev_temp_metric_get(i, RSMI_TEMP_TYPE_EDGE, RSMI_TEMP_MAX, &temp_max);
+        			if (result != RSMI_STATUS_SUCCESS)
+    					Logger::warning("ROCm SMI: Failed to get maximum GPU temperature, defaulting to 110°C");
+    				else gpus_slice[i].temp_max = (long long)temp_max;
+
+					//? Disable encoder and decoder utilisation on AMD
+					gpus_slice[i].supported_functions.encoder_utilization = false;
+					gpus_slice[i].supported_functions.decoder_utilization = false;
+    			}
+
+				//? GPU utilization
+				if (gpus_slice[i].supported_functions.gpu_utilization) {
+					uint32_t utilization;
+					result = rsmi_dev_busy_percent_get(i, &utilization);
+    				if (result != RSMI_STATUS_SUCCESS) {
+						Logger::warning("ROCm SMI: Failed to get GPU utilization");
+						if constexpr(is_init) gpus_slice[i].supported_functions.gpu_utilization = false;
+    				} else gpus_slice[i].gpu_percent.at("gpu-totals").push_back((long long)utilization);
+				}
+
+				//? Memory utilization
+				if (gpus_slice[i].supported_functions.mem_utilization) {
+					uint32_t utilization;
+					result = rsmi_dev_memory_busy_percent_get(i, &utilization);
+    				if (result != RSMI_STATUS_SUCCESS) {
+						Logger::warning("ROCm SMI: Failed to get VRAM utilization");
+						if constexpr(is_init) gpus_slice[i].supported_functions.mem_utilization = false;
+    				} else gpus_slice[i].mem_utilization_percent.push_back((long long)utilization);
+				}
+			#if !defined(RSMI_STATIC)
+				//? Clock speeds
+				if (gpus_slice[i].supported_functions.gpu_clock) {
+					if (version_major == 5) {
+						rsmi_frequencies_t_v5 frequencies;
+						result = rsmi_dev_gpu_clk_freq_get_v5(i, RSMI_CLK_TYPE_SYS, &frequencies);
+						if (result != RSMI_STATUS_SUCCESS) {
+							Logger::warning("ROCm SMI: Failed to get GPU clock speed: ");
+							if constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false;
+						} else gpus_slice[i].gpu_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz
+					}
+					else if (version_major == 6 || version_major == 7) {
+						rsmi_frequencies_t_v6 frequencies;
+						result = rsmi_dev_gpu_clk_freq_get_v6(i, RSMI_CLK_TYPE_SYS, &frequencies);
+						if (result != RSMI_STATUS_SUCCESS) {
+							Logger::warning("ROCm SMI: Failed to get GPU clock speed: ");
+							if constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false;
+						} else gpus_slice[i].gpu_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz
+					}
+				}
+
+				if (gpus_slice[i].supported_functions.mem_clock) {
+					if (version_major == 5) {
+						rsmi_frequencies_t_v5 frequencies;
+						result = rsmi_dev_gpu_clk_freq_get_v5(i, RSMI_CLK_TYPE_MEM, &frequencies);
+						if (result != RSMI_STATUS_SUCCESS) {
+							Logger::warning("ROCm SMI: Failed to get VRAM clock speed: ");
+							if constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false;
+						} else gpus_slice[i].mem_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz
+					}
+					else if (version_major == 6 || version_major == 7) {
+						rsmi_frequencies_t_v6 frequencies;
+						result = rsmi_dev_gpu_clk_freq_get_v6(i, RSMI_CLK_TYPE_MEM, &frequencies);
+						if (result != RSMI_STATUS_SUCCESS) {
+							Logger::warning("ROCm SMI: Failed to get VRAM clock speed: ");
+							if constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false;
+						} else gpus_slice[i].mem_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz
+					}
+				}
+			#else
+				//? Clock speeds
+				if (gpus_slice[i].supported_functions.gpu_clock) {
+					rsmi_frequencies_t frequencies;
+					result = rsmi_dev_gpu_clk_freq_get(i, RSMI_CLK_TYPE_SYS, &frequencies);
+    				if (result != RSMI_STATUS_SUCCESS) {
+						Logger::warning("ROCm SMI: Failed to get GPU clock speed: ");
+						if constexpr(is_init) gpus_slice[i].supported_functions.gpu_clock = false;
+    				} else gpus_slice[i].gpu_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz
+				}
+
+				if (gpus_slice[i].supported_functions.mem_clock) {
+					rsmi_frequencies_t frequencies;
+					result = rsmi_dev_gpu_clk_freq_get(i, RSMI_CLK_TYPE_MEM, &frequencies);
+    				if (result != RSMI_STATUS_SUCCESS) {
+						Logger::warning("ROCm SMI: Failed to get VRAM clock speed: ");
+						if constexpr(is_init) gpus_slice[i].supported_functions.mem_clock = false;
+    				} else gpus_slice[i].mem_clock_speed = (long long)frequencies.frequency[frequencies.current]/1000000; // Hz to MHz
+				}
+			#endif
+
+    			//? Power usage & state
+				if (gpus_slice[i].supported_functions.pwr_usage) {
+    				uint64_t power;
+    				result = rsmi_dev_power_ave_get(i, 0, &power);
+    				if (result != RSMI_STATUS_SUCCESS) {
+						Logger::warning("ROCm SMI: Failed to get GPU power usage");
+						if constexpr(is_init) gpus_slice[i].supported_functions.pwr_usage = false;
+    				} else {
+							gpus_slice[i].pwr_usage = (long long)power / 1000;
+							if (gpus_slice[i].pwr_usage > gpus_slice[i].pwr_max_usage)
+								gpus_slice[i].pwr_max_usage = gpus_slice[i].pwr_usage;
+							gpus_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));
+						}
+
+					if constexpr(is_init) gpus_slice[i].supported_functions.pwr_state = false;
+				}
+
+    			//? GPU temperature
+				if (gpus_slice[i].supported_functions.temp_info) {
+    				if (Config::getB("check_temp") or is_init) {
+						int64_t temp;
+    					result = rsmi_dev_temp_metric_get(i, RSMI_TEMP_TYPE_EDGE, RSMI_TEMP_CURRENT, &temp);
+        				if (result != RSMI_STATUS_SUCCESS) {
+    						Logger::warning("ROCm SMI: Failed to get GPU temperature");
+							if constexpr(is_init) gpus_slice[i].supported_functions.temp_info = false;
+    					} else gpus_slice[i].temp.push_back((long long)temp/1000);
+    				}
+				}
+
+				//? Memory info
+				if (gpus_slice[i].supported_functions.mem_total) {
+					uint64_t total;
+					result = rsmi_dev_memory_total_get(i, RSMI_MEM_TYPE_VRAM, &total);
+    				if (result != RSMI_STATUS_SUCCESS) {
+						Logger::warning("ROCm SMI: Failed to get total VRAM");
+						if constexpr(is_init) gpus_slice[i].supported_functions.mem_total = false;
+					} else gpus_slice[i].mem_total = total;
+				}
+
+				if (gpus_slice[i].supported_functions.mem_used) {
+					uint64_t used;
+					result = rsmi_dev_memory_usage_get(i, RSMI_MEM_TYPE_VRAM, &used);
+    				if (result != RSMI_STATUS_SUCCESS) {
+						Logger::warning("ROCm SMI: Failed to get VRAM usage");
+						if constexpr(is_init) gpus_slice[i].supported_functions.mem_used = false;
+					} else {
+						gpus_slice[i].mem_used = used;
+						if (gpus_slice[i].supported_functions.mem_total)
+							gpus_slice[i].gpu_percent.at("gpu-vram-totals").push_back((long long)round((double)used * 100.0 / (double)gpus_slice[i].mem_total));
+					}
+				}
+
+				//? PCIe link speeds
+				if (gpus_slice[i].supported_functions.pcie_txrx and Config::getB("rsmi_measure_pcie_speeds")) {
+					uint64_t tx, rx;
+					result = rsmi_dev_pci_throughput_get(i, &tx, &rx, nullptr);
+    				if (result != RSMI_STATUS_SUCCESS) {
+						Logger::warning("ROCm SMI: Failed to get PCIe throughput");
+						if constexpr(is_init) gpus_slice[i].supported_functions.pcie_txrx = false;
+					} else {
+						gpus_slice[i].pcie_tx = (long long)tx;
+						gpus_slice[i].pcie_rx = (long long)rx;
+					}
+				}
+    		}
+
+			return true;
+		}
+	}
+
+	namespace Intel {
+		bool init() {
+			if (initialized) return false;
+
+			char *gpu_path = find_intel_gpu_dir();
+			if (!gpu_path) {
+				Logger::debug("Failed to find Intel GPU sysfs path, Intel GPUs will not be detected");
+				return false;
+			}
+
+			char *gpu_device_id = get_intel_device_id(gpu_path);
+			if (!gpu_device_id) {
+				Logger::debug("Failed to find Intel GPU device ID, Intel GPUs will not be detected");
+				return false;
+			}
+
+			char *gpu_device_name = get_intel_device_name(gpu_device_id);
+			if (!gpu_device_name) {
+				Logger::warning("Failed to find Intel GPU device name in internal database");
+			}
+
+			free(gpu_device_id);
+
+			engines = discover_engines(device);
+			if (!engines) {
+				Logger::debug("Failed to find Intel GPU engines, Intel GPUs will not be detected");
+				return false;
+			}
+
+			int ret = pmu_init(engines);
+			if (ret) {
+				Logger::warning("Intel GPU: Failed to initialize PMU");
+				return false;
+			}
+
+			pmu_sample(engines);
+
+			device_count = 1;
+
+			gpus.resize(gpus.size() + device_count);
+			gpu_names.resize(gpus.size() + device_count);
+
+			if (gpu_device_name) {
+				gpu_names[Nvml::device_count + Rsmi::device_count] = string(gpu_device_name);
+			} else {
+				gpu_names[Nvml::device_count + Rsmi::device_count] = "Intel GPU";
+			}
+
+			free(gpu_device_name);
+
+			initialized = true;
+			Intel::collect<1>(gpus.data() + Nvml::device_count + Rsmi::device_count);
+
+			return true;
+		}
+
+		bool shutdown() {
+			if (!initialized) return false;
+			if (engines) {
+				free_engines(engines);
+				engines = nullptr;
+			}
+			initialized = false;
+			return true;
+		}
+
+		template <bool is_init> bool collect(gpu_info* gpus_slice) {
+			if (!initialized) return false;
+
+			if constexpr(is_init) {
+				gpus_slice->supported_functions = {
+					.gpu_utilization = true,
+					.mem_utilization = false,
+					.gpu_clock = true,
+					.mem_clock = false,
+					.pwr_usage = true,
+					.pwr_state = false,
+					.temp_info = false,
+					.mem_total = false,
+					.mem_used = false,
+					.pcie_txrx = false,
+					.encoder_utilization = false,
+					.decoder_utilization = false
+				};
+
+				gpus_slice->pwr_max_usage = 10'000; //? 10W
+			}
+
+			pmu_sample(engines);
+			double t = (double)(engines->ts.cur - engines->ts.prev) / 1e9;
+
+			double max_util = 0;
+			for (unsigned int i = 0; i < engines->num_engines; i++) {
+				struct engine *engine = &(&engines->engine)[i];
+				double util = pmu_calc(&engine->busy.val, 1e9, t, 100);
+				if (util > max_util) {
+					max_util = util;
+				}
+			}
+			gpus_slice->gpu_percent.at("gpu-totals").push_back((long long)round(max_util));
+
+			double pwr = pmu_calc(&engines->r_gpu.val, 1, t, engines->r_gpu.scale); // in Watts
+			gpus_slice->pwr_usage = (long long)round(pwr * 1000);
+			if (gpus_slice->pwr_usage > gpus_slice->pwr_max_usage)
+				gpus_slice->pwr_max_usage = gpus_slice->pwr_usage;
+
+			gpus_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));
+
+			double freq = pmu_calc(&engines->freq_act.val, 1, t, 1); // in MHz
+			gpus_slice->gpu_clock_speed = (unsigned int)round(freq);
+
+			return true;
+		}
+	}
+
+	//? Collect data from GPU-specific libraries
+	auto collect(bool no_update) -> vector<gpu_info>& {
+		if (Runner::stopping or (no_update and not gpus.empty())) return gpus;
+
+		// DebugTimer gpu_timer("GPU Total");
+
+		//* Collect data
+		Nvml::collect<0>(gpus.data()); // raw pointer to vector data, size == Nvml::device_count
+		Rsmi::collect<0>(gpus.data() + Nvml::device_count); // size = Rsmi::device_count
+		Intel::collect<0>(gpus.data() + Nvml::device_count + Rsmi::device_count); // size = Intel::device_count
+
+		//* Calculate average usage
+		long long avg = 0;
+		long long mem_usage_total = 0;
+		long long mem_total = 0;
+		long long pwr_total = 0;
+		for (auto& gpu : gpus) {
+			if (gpu.supported_functions.gpu_utilization)
+				avg += gpu.gpu_percent.at("gpu-totals").back();
+			if (gpu.supported_functions.mem_used)
+				mem_usage_total += gpu.mem_used;
+			if (gpu.supported_functions.mem_total)
+				mem_total += gpu.mem_total;
+			if (gpu.supported_functions.pwr_usage)
+				mem_total += gpu.pwr_usage;
+
+			//* Trim vectors if there are more values than needed for graphs
+			if (width != 0) {
+				//? GPU & memory utilization
+				while (cmp_greater(gpu.gpu_percent.at("gpu-totals").size(), width * 2)) gpu.gpu_percent.at("gpu-totals").pop_front();
+				while (cmp_greater(gpu.mem_utilization_percent.size(), width)) gpu.mem_utilization_percent.pop_front();
+				//? Power usage
+				while (cmp_greater(gpu.gpu_percent.at("gpu-pwr-totals").size(), width)) gpu.gpu_percent.at("gpu-pwr-totals").pop_front();
+				//? Temperature
+				while (cmp_greater(gpu.temp.size(), 18)) gpu.temp.pop_front();
+				//? Memory usage
+				while (cmp_greater(gpu.gpu_percent.at("gpu-vram-totals").size(), width/2)) gpu.gpu_percent.at("gpu-vram-totals").pop_front();
+			}
+		}
+
+		shared_gpu_percent.at("gpu-average").push_back(avg / gpus.size());
+		if (mem_total != 0)
+			shared_gpu_percent.at("gpu-vram-total").push_back(mem_usage_total / mem_total);
+		if (gpu_pwr_total_max != 0)
+			shared_gpu_percent.at("gpu-pwr-total").push_back(pwr_total / gpu_pwr_total_max);
+
+		if (width != 0) {
+			while (cmp_greater(shared_gpu_percent.at("gpu-average").size(), width * 2)) shared_gpu_percent.at("gpu-average").pop_front();
+			while (cmp_greater(shared_gpu_percent.at("gpu-pwr-total").size(), width * 2)) shared_gpu_percent.at("gpu-pwr-total").pop_front();
+			while (cmp_greater(shared_gpu_percent.at("gpu-vram-total").size(), width * 2)) shared_gpu_percent.at("gpu-vram-total").pop_front();
+		}
+
+		count = gpus.size();
+
+		return gpus;
+	}
+}
+#endif
+
+/// Convert ascii escapes like \040 into chars.
+static auto convert_ascii_escapes(const std::string& input) -> std::string {
+    std::string out;
+    out.reserve(input.size());
+
+    for (std::size_t i = 0; i < input.size(); ++i) {
+        if (input[i] == '\\' &&
+	    	// Peek the next three characters.
+            i + 3 < input.size() &&
+            std::isdigit(input[i + 1]) &&
+            std::isdigit(input[i + 2]) &&
+            std::isdigit(input[i + 3])) {
+
+			// Convert octal chars to decimal int.
+			//   '0' - '0' -> 0, '4' - '0' -> 4, '0' - '0' -> 0.
+			//   0 * 64 (0)
+			//   + 4 * 8 (32)
+			//   + 0
+			//   = 32 (ascii space)
+            int value = ((input[i + 1] - '0') * 64) + ((input[i + 2] - '0') * 8) + (input[i + 3] - '0');
+            out.push_back(static_cast<char>(value));
+            // Consume the three digits.
+            i += 3;
+        } else {
+            out.push_back(input[i]);
+        }
+    }
+    return out;
+}
+
+namespace Mem {
+	bool has_swap{};
+	vector<string> fstab;
+	fs::file_time_type fstab_time;
+	int disk_ios{};
+	vector<string> last_found;
+
+	//?* Find the filepath to the specified ZFS object's stat file
+	fs::path get_zfs_stat_file(const string& device_name, size_t dataset_name_start, bool zfs_hide_datasets);
+
+	//?* Collect total ZFS pool io stats
+	bool zfs_collect_pool_total_stats(struct disk_info &disk);
+
+	mem_info current_mem {};
+
+	uint64_t get_totalMem() {
+		ifstream meminfo(Shared::procPath / "meminfo");
+		int64_t totalMem = 0;
+		if (meminfo.good()) {
+			meminfo.ignore(SSmax, ':');
+			meminfo >> totalMem;
+			totalMem <<= 10;
+		}
+		if (not meminfo.good() or totalMem == 0)
+			throw std::runtime_error("Could not get total memory size from /proc/meminfo");
+
+		return totalMem;
+	}
+
+	auto collect(bool no_update) -> mem_info& {
+		if (Runner::stopping or (no_update and not current_mem.percent.at("used").empty())) return current_mem;
+		auto show_swap = Config::getB("show_swap");
+		auto swap_disk = Config::getB("swap_disk");
+		auto show_disks = Config::getB("show_disks");
+		auto zfs_arc_cached = Config::getB("zfs_arc_cached");
+		auto totalMem = get_totalMem();
+		auto& mem = current_mem;
+
+		mem.stats.at("swap_total") = 0;
+
+		//? Read ZFS ARC info from /proc/spl/kstat/zfs/arcstats
+		uint64_t arc_size = 0, arc_min_size = 0;
+		if (zfs_arc_cached) {
+			ifstream arcstats(Shared::procPath / "spl/kstat/zfs/arcstats");
+			if (arcstats.good()) {
+				for (string label; arcstats >> label;) {
+					if (label == "c_min") {
+						arcstats >> arc_min_size >> arc_min_size; // double read skips type column
+					}
+					else if (label == "size") {
+						arcstats >> arc_size >> arc_size;
+						break;
+					}
+				}
+			}
+			arcstats.close();
+		}
+
+		//? Read memory info from /proc/meminfo
+		ifstream meminfo(Shared::procPath / "meminfo");
+		if (meminfo.good()) {
+			bool got_avail = false;
+			for (string label; meminfo.peek() != 'D' and meminfo >> label;) {
+				if (label == "MemFree:") {
+					meminfo >> mem.stats.at("free");
+					mem.stats.at("free") <<= 10;
+				}
+				else if (label == "MemAvailable:") {
+					meminfo >> mem.stats.at("available");
+					mem.stats.at("available") <<= 10;
+					got_avail = true;
+				}
+				else if (label == "Cached:") {
+					meminfo >> mem.stats.at("cached");
+					mem.stats.at("cached") <<= 10;
+					if (not show_swap and not swap_disk) break;
+				}
+				else if (label == "SwapTotal:") {
+					meminfo >> mem.stats.at("swap_total");
+					mem.stats.at("swap_total") <<= 10;
+				}
+				else if (label == "SwapFree:") {
+					meminfo >> mem.stats.at("swap_free");
+					mem.stats.at("swap_free") <<= 10;
+					break;
+				}
+				meminfo.ignore(SSmax, '\n');
+			}
+			if (not got_avail) mem.stats.at("available") = mem.stats.at("free") + mem.stats.at("cached");
+			if (zfs_arc_cached) {
+				mem.stats.at("cached") += arc_size;
+				// The ARC will not shrink below arc_min_size, so that memory is not available
+				if (arc_size > arc_min_size)
+					mem.stats.at("available") += arc_size - arc_min_size;
+			}
+			mem.stats.at("used") = totalMem - (mem.stats.at("available") <= totalMem ? mem.stats.at("available") : mem.stats.at("free"));
+
+			if (mem.stats.at("swap_total") > 0) mem.stats.at("swap_used") = mem.stats.at("swap_total") - mem.stats.at("swap_free");
+		}
+		else
+			throw std::runtime_error("Failed to read /proc/meminfo");
+
+		meminfo.close();
+
+		//? Calculate percentages
+		for (const auto& name : mem_names) {
+			mem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / totalMem));
+			while (cmp_greater(mem.percent.at(name).size(), width * 2)) mem.percent.at(name).pop_front();
+		}
+
+		if (show_swap and mem.stats.at("swap_total") > 0) {
+			for (const auto& name : swap_names) {
+				mem.percent.at(name).push_back(round((double)mem.stats.at(name) * 100 / mem.stats.at("swap_total")));
+				while (cmp_greater(mem.percent.at(name).size(), width * 2)) mem.percent.at(name).pop_front();
+			}
+			has_swap = true;
+		}
+		else
+			has_swap = false;
+
+		//? Get disks stats
+		if (show_disks) {
+			static vector<string> ignore_list;
+			double uptime = system_uptime();
+			auto free_priv = Config::getB("disk_free_priv");
+			try {
+				auto& disks_filter = Config::getS("disks_filter");
+				bool filter_exclude = false;
+				auto use_fstab = Config::getB("use_fstab");
+				auto only_physical = Config::getB("only_physical");
+				auto zfs_hide_datasets = Config::getB("zfs_hide_datasets");
+				auto& disks = mem.disks;
+				static std::unordered_map<string, future<pair<disk_info, int>>> disks_stats_promises;
+				ifstream diskread;
+
+				vector<string> filter;
+				if (not disks_filter.empty()) {
+					filter = ssplit(disks_filter);
+					if (filter.at(0).starts_with("exclude=")) {
+						filter_exclude = true;
+						filter.at(0) = filter.at(0).substr(8);
+					}
+				}
+
+				//? Get list of "real" filesystems from /proc/filesystems
+				vector<string> fstypes;
+				if (only_physical and not use_fstab) {
+					fstypes = {"zfs", "wslfs", "drvfs"};
+					diskread.open(Shared::procPath / "filesystems");
+					if (diskread.good()) {
+						for (string fstype; diskread >> fstype;) {
+							if (not is_in(fstype, "nodev", "squashfs", "nullfs"))
+								fstypes.push_back(fstype);
+							diskread.ignore(SSmax, '\n');
+						}
+					}
+					else
+						throw std::runtime_error("Failed to read /proc/filesystems");
+					diskread.close();
+				}
+
+				//? Get disk list to use from fstab if enabled
+				if (use_fstab and fs::last_write_time("/etc/fstab") != fstab_time) {
+					fstab.clear();
+					fstab_time = fs::last_write_time("/etc/fstab");
+					diskread.open("/etc/fstab");
+					if (diskread.good()) {
+						for (string instr; diskread >> instr;) {
+							if (not instr.starts_with('#')) {
+								diskread >> instr;
+								#ifdef SNAPPED
+									if (instr == "/") fstab.push_back("/mnt");
+									else if (not is_in(instr, "none", "swap")) fstab.push_back(instr);
+								#else
+									if (not is_in(instr, "none", "swap")) fstab.push_back(instr);
+								#endif
+							}
+							diskread.ignore(SSmax, '\n');
+						}
+					}
+					else
+						throw std::runtime_error("Failed to read /etc/fstab");
+					diskread.close();
+				}
+
+				//? Get mounts from /etc/mtab or /proc/self/mounts
+				diskread.open((fs::exists("/etc/mtab") ? fs::path("/etc/mtab") : Shared::procPath / "self/mounts"));
+				if (diskread.good()) {
+					vector<string> found;
+					found.reserve(last_found.size());
+					string dev, mountpoint, fstype;
+					while (not diskread.eof()) {
+						std::error_code ec;
+						diskread >> dev >> mountpoint >> fstype;
+						diskread.ignore(SSmax, '\n');
+
+						// A mountpoint can ascii escape codes, which will not work with `statvfs`.
+						mountpoint = convert_ascii_escapes(mountpoint);
+
+						if (v_contains(ignore_list, mountpoint) or v_contains(found, mountpoint)) continue;
+
+						//? Match filter if not empty
+						if (not filter.empty()) {
+							bool match = v_contains(filter, mountpoint);
+							if ((filter_exclude and match) or (not filter_exclude and not match))
+								continue;
+						}
+
+						//? Skip ZFS datasets if zfs_hide_datasets option is enabled
+						size_t zfs_dataset_name_start = 0;
+						if (fstype == "zfs" && (zfs_dataset_name_start = dev.find('/')) != std::string::npos && zfs_hide_datasets) continue;
+
+						if ((not use_fstab and not only_physical)
+						or (use_fstab and v_contains(fstab, mountpoint))
+						or (not use_fstab and only_physical and v_contains(fstypes, fstype))) {
+							found.push_back(mountpoint);
+							if (not v_contains(last_found, mountpoint)) redraw = true;
+
+							//? Save mountpoint, name, fstype, dev path and path to /sys/block stat file
+							if (not disks.contains(mountpoint)) {
+								disks[mountpoint] = disk_info{fs::canonical(dev, ec), fs::path(mountpoint).filename(), fstype};
+								if (disks.at(mountpoint).dev.empty()) disks.at(mountpoint).dev = dev;
+								#ifdef SNAPPED
+									if (mountpoint == "/mnt") disks.at(mountpoint).name = "root";
+								#endif
+								if (disks.at(mountpoint).name.empty()) disks.at(mountpoint).name = (mountpoint == "/" ? "root" : mountpoint);
+								string devname = disks.at(mountpoint).dev.filename();
+								int c = 0;
+								while (devname.size() >= 2) {
+									if (fs::exists("/sys/block/" + devname + "/stat", ec) and access(string("/sys/block/" + devname + "/stat").c_str(), R_OK) == 0) {
+										if (c > 0 and fs::exists("/sys/block/" + devname + '/' + disks.at(mountpoint).dev.filename().string() + "/stat", ec))
+											disks.at(mountpoint).stat = "/sys/block/" + devname + '/' + disks.at(mountpoint).dev.filename().string() + "/stat";
+										else
+											disks.at(mountpoint).stat = "/sys/block/" + devname + "/stat";
+										break;
+									//? Set ZFS stat filepath
+									} else if (fstype == "zfs") {
+										disks.at(mountpoint).stat = get_zfs_stat_file(dev, zfs_dataset_name_start, zfs_hide_datasets);
+										if (disks.at(mountpoint).stat.empty()) {
+											Logger::debug("Failed to get ZFS stat file for device " + dev);
+										}
+										break;
+									}
+									devname.resize(devname.size() - 1);
+									c++;
+								}
+							}
+
+							//? If zfs_hide_datasets option was switched, refresh stat filepath
+							if (fstype == "zfs" && ((zfs_hide_datasets && !is_directory(disks.at(mountpoint).stat))
+								|| (!zfs_hide_datasets && is_directory(disks.at(mountpoint).stat)))) {
+								disks.at(mountpoint).stat = get_zfs_stat_file(dev, zfs_dataset_name_start, zfs_hide_datasets);
+								if (disks.at(mountpoint).stat.empty()) {
+									Logger::debug("Failed to get ZFS stat file for device " + dev);
+								}
+							}
+						}
+					}
+
+					//? Remove disks no longer mounted or filtered out
+					if (swap_disk and has_swap) found.push_back("swap");
+					for (auto it = disks.begin(); it != disks.end();) {
+						if (not v_contains(found, it->first))
+							it = disks.erase(it);
+						else
+							it++;
+					}
+					if (found.size() != last_found.size()) redraw = true;
+					last_found = std::move(found);
+				}
+				else
+					throw std::runtime_error("Failed to get mounts from /etc/mtab and /proc/self/mounts");
+				diskread.close();
+
+				//? Get disk/partition stats
+				for (auto it = disks.begin(); it != disks.end(); ) {
+					auto &[mountpoint, disk] = *it;
+					if (v_contains(ignore_list, mountpoint) or disk.name == "swap") {
+						it = disks.erase(it);
+						continue;
+					}
+					if(auto promises_it = disks_stats_promises.find(mountpoint); promises_it != disks_stats_promises.end()){
+						auto& promise = promises_it->second;
+						if(promise.valid() &&
+						   promise.wait_for(0s) == std::future_status::timeout) {
+							++it;
+							continue;
+						}
+						auto promise_res = promises_it->second.get();
+						if(promise_res.second != -1){
+							ignore_list.push_back(mountpoint);
+							Logger::warning("Failed to get disk/partition stats for mount \""+ mountpoint + "\" with statvfs error code: " + to_string(promise_res.second) + ". Ignoring...");
+							it = disks.erase(it);
+							continue;
+						}
+						auto &updated_stats = promise_res.first;
+						disk.total = updated_stats.total;
+						disk.free = updated_stats.free;
+						disk.used = updated_stats.used;
+						disk.used_percent = updated_stats.used_percent;
+						disk.free_percent = updated_stats.free_percent;
+					}
+					disks_stats_promises[mountpoint] = async(std::launch::async, [mountpoint, free_priv]() -> pair<disk_info, int> {
+						struct statvfs vfs;
+						disk_info disk;
+						if (statvfs(mountpoint.c_str(), &vfs) < 0) {
+							return pair{disk, errno};
+						}
+						disk.total = vfs.f_blocks * vfs.f_frsize;
+						disk.free = (free_priv ? vfs.f_bfree : vfs.f_bavail) * vfs.f_frsize;
+						disk.used = disk.total - disk.free;
+						if (disk.total != 0) {
+							disk.used_percent = round((double)disk.used * 100 / disk.total);
+							disk.free_percent = 100 - disk.used_percent;
+						} else {
+							disk.used_percent = 0;
+							disk.free_percent = 0;
+						}
+						return pair{disk, -1};
+					});
+					++it;
+				}
+
+				//? Setup disks order in UI and add swap if enabled
+				mem.disks_order.clear();
+				#ifdef SNAPPED
+					if (disks.contains("/mnt")) mem.disks_order.push_back("/mnt");
+				#else
+					if (disks.contains("/")) mem.disks_order.push_back("/");
+				#endif
+				if (swap_disk and has_swap) {
+					mem.disks_order.push_back("swap");
+					if (not disks.contains("swap")) disks["swap"] = {"", "swap", "swap"};
+					disks.at("swap").total = mem.stats.at("swap_total");
+					disks.at("swap").used = mem.stats.at("swap_used");
+					disks.at("swap").free = mem.stats.at("swap_free");
+					disks.at("swap").used_percent = mem.percent.at("swap_used").back();
+					disks.at("swap").free_percent = mem.percent.at("swap_free").back();
+				}
+				for (const auto& name : last_found)
+					#ifdef SNAPPED
+						if (not is_in(name, "/mnt", "swap")) mem.disks_order.push_back(name);
+					#else
+						if (not is_in(name, "/", "swap")) mem.disks_order.push_back(name);
+					#endif
+
+				//? Get disks IO
+				int64_t sectors_read, sectors_write, io_ticks, io_ticks_temp;
+				disk_ios = 0;
+				for (auto& [ignored, disk] : disks) {
+					if (disk.stat.empty() or access(disk.stat.c_str(), R_OK) != 0) continue;
+					if (disk.fstype == "zfs" && zfs_hide_datasets && zfs_collect_pool_total_stats(disk)) {
+						disk_ios++;
+						continue;
+					}
+					diskread.open(disk.stat);
+					if (diskread.good()) {
+						disk_ios++;
+						//? ZFS Pool Support
+						if (disk.fstype == "zfs") {
+							// skip first three lines
+							for (int i = 0; i < 3; i++) diskread.ignore(numeric_limits<streamsize>::max(), '\n');
+							// skip characters until '4' is reached, indicating data type 4, next value will be out target
+							diskread.ignore(numeric_limits<streamsize>::max(), '4');
+							diskread >> io_ticks;
+
+							// skip characters until '4' is reached, indicating data type 4, next value will be out target
+							diskread.ignore(numeric_limits<streamsize>::max(), '4');
+							diskread >> sectors_write; // nbytes written
+							if (disk.io_write.empty())
+								disk.io_write.push_back(0);
+							else
+								disk.io_write.push_back(max((int64_t)0, (sectors_write - disk.old_io.at(1))));
+							disk.old_io.at(1) = sectors_write;
+							while (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front();
+
+							// skip characters until '4' is reached, indicating data type 4, next value will be out target
+							diskread.ignore(numeric_limits<streamsize>::max(), '4');
+							diskread >> io_ticks_temp;
+							io_ticks += io_ticks_temp;
+
+							// skip characters until '4' is reached, indicating data type 4, next value will be out target
+							diskread.ignore(numeric_limits<streamsize>::max(), '4');
+							diskread >> sectors_read; // nbytes read
+							if (disk.io_read.empty())
+								disk.io_read.push_back(0);
+							else
+								disk.io_read.push_back(max((int64_t)0, (sectors_read - disk.old_io.at(0))));
+							disk.old_io.at(0) = sectors_read;
+							while (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front();
+
+							if (disk.io_activity.empty())
+								disk.io_activity.push_back(0);
+							else
+								disk.io_activity.push_back(max((int64_t)0, (io_ticks - disk.old_io.at(2))));
+							disk.old_io.at(2) = io_ticks;
+							while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();
+						} else {
+							for (int i = 0; i < 2; i++) { diskread >> std::ws; diskread.ignore(SSmax, ' '); }
+							diskread >> sectors_read;
+							if (disk.io_read.empty())
+								disk.io_read.push_back(0);
+							else
+								disk.io_read.push_back(max((int64_t)0, (sectors_read - disk.old_io.at(0)) * 512));
+							disk.old_io.at(0) = sectors_read;
+							while (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front();
+
+							for (int i = 0; i < 3; i++) { diskread >> std::ws; diskread.ignore(SSmax, ' '); }
+							diskread >> sectors_write;
+							if (disk.io_write.empty())
+								disk.io_write.push_back(0);
+							else
+								disk.io_write.push_back(max((int64_t)0, (sectors_write - disk.old_io.at(1)) * 512));
+							disk.old_io.at(1) = sectors_write;
+							while (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front();
+
+							for (int i = 0; i < 2; i++) { diskread >> std::ws; diskread.ignore(SSmax, ' '); }
+							diskread >> io_ticks;
+							if (uptime == old_uptime || disk.io_activity.empty())
+								disk.io_activity.push_back(0);
+							else
+								disk.io_activity.push_back(clamp((long)round((double)(io_ticks - disk.old_io.at(2)) / (uptime - old_uptime) / 10), 0l, 100l));
+							disk.old_io.at(2) = io_ticks;
+							while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();
+						}
+					} else {
+						Logger::debug("Error in Mem::collect() : when opening " + string{disk.stat});
+					}
+					diskread.close();
+				}
+				old_uptime = uptime;
+			}
+			catch (const std::exception& e) {
+				Logger::warning("Error in Mem::collect() : " + string{e.what()});
+			}
+		}
+
+		return mem;
+	}
+
+	fs::path get_zfs_stat_file(const string& device_name, size_t dataset_name_start, bool zfs_hide_datasets) {
+		fs::path zfs_pool_stat_path;
+		if (zfs_hide_datasets) {
+			zfs_pool_stat_path = Shared::procPath / "spl/kstat/zfs" / device_name;
+			if (access(zfs_pool_stat_path.c_str(), R_OK) == 0) {
+				return zfs_pool_stat_path;
+			} else {
+				Logger::debug("Can't access folder: " + zfs_pool_stat_path.string());
+				return "";
+			}
+		}
+
+		ifstream filestream;
+		string filename;
+		string name_compare;
+
+		if (dataset_name_start != std::string::npos) { // device is a dataset
+			zfs_pool_stat_path = Shared::procPath / "spl/kstat/zfs" / device_name.substr(0, dataset_name_start);
+		} else { // device is a pool
+			zfs_pool_stat_path = Shared::procPath / "spl/kstat/zfs" / device_name;
+		}
+
+		// looking through all files that start with 'objset' to find the one containing `device_name` object stats
+		try {
+			for (const auto& file: fs::directory_iterator(zfs_pool_stat_path)) {
+				filename = file.path().filename();
+				if (filename.starts_with("objset")) {
+					filestream.open(file.path());
+					if (filestream.good()) {
+						// skip first two lines
+						for (int i = 0; i < 2; i++) filestream.ignore(numeric_limits<streamsize>::max(), '\n');
+						// skip characters until '7' is reached, indicating data type 7, next value will be object name
+						filestream.ignore(numeric_limits<streamsize>::max(), '7');
+						filestream >> name_compare;
+						if (name_compare == device_name) {
+							filestream.close();
+							if (access(file.path().c_str(), R_OK) == 0) {
+								return file.path();
+							} else {
+								Logger::debug("Can't access file: " + file.path().string());
+								return "";
+							}
+						}
+					}
+					filestream.close();
+				}
+			}
+		}
+		catch (fs::filesystem_error& e) {}
+
+		Logger::debug("Could not read directory: " + zfs_pool_stat_path.string());
+		return "";
+	}
+
+	bool zfs_collect_pool_total_stats(struct disk_info &disk) {
+		ifstream diskread;
+
+		int64_t bytes_read;
+		int64_t bytes_write;
+		int64_t io_ticks;
+		int64_t bytes_read_total{};
+		int64_t bytes_write_total{};
+		int64_t io_ticks_total{};
+		int64_t objects_read{};
+
+		// looking through all files that start with 'objset'
+		for (const auto& file: fs::directory_iterator(disk.stat)) {
+			if ((file.path().filename()).string().starts_with("objset")) {
+				diskread.open(file.path());
+				if (diskread.good()) {
+					try {
+						// skip first three lines
+						for (int i = 0; i < 3; i++) diskread.ignore(numeric_limits<streamsize>::max(), '\n');
+						// skip characters until '4' is reached, indicating data type 4, next value will be out target
+						diskread.ignore(numeric_limits<streamsize>::max(), '4');
+						diskread >> io_ticks;
+						io_ticks_total += io_ticks;
+
+						// skip characters until '4' is reached, indicating data type 4, next value will be out target
+						diskread.ignore(numeric_limits<streamsize>::max(), '4');
+						diskread >> bytes_write;
+						bytes_write_total += bytes_write;
+
+						// skip characters until '4' is reached, indicating data type 4, next value will be out target
+						diskread.ignore(numeric_limits<streamsize>::max(), '4');
+						diskread >> io_ticks;
+						io_ticks_total += io_ticks;
+
+						// skip characters until '4' is reached, indicating data type 4, next value will be out target
+						diskread.ignore(numeric_limits<streamsize>::max(), '4');
+						diskread >> bytes_read;
+						bytes_read_total += bytes_read;
+					} catch (const std::exception& e) {
+						continue;
+					}
+
+					// increment read objects counter if no errors were encountered
+					objects_read++;
+				} else {
+					Logger::debug("Could not read file: " + file.path().string());
+				}
+				diskread.close();
+			}
+		}
+
+		// if for some reason no objects were read
+		if (objects_read == 0) return false;
+
+		if (disk.io_write.empty())
+			disk.io_write.push_back(0);
+		else
+			disk.io_write.push_back(max((int64_t)0, (bytes_write_total - disk.old_io.at(1))));
+		disk.old_io.at(1) = bytes_write_total;
+		while (cmp_greater(disk.io_write.size(), width * 2)) disk.io_write.pop_front();
+
+		if (disk.io_read.empty())
+			disk.io_read.push_back(0);
+		else
+			disk.io_read.push_back(max((int64_t)0, (bytes_read_total - disk.old_io.at(0))));
+		disk.old_io.at(0) = bytes_read_total;
+		while (cmp_greater(disk.io_read.size(), width * 2)) disk.io_read.pop_front();
+
+		if (disk.io_activity.empty())
+			disk.io_activity.push_back(0);
+		else
+			disk.io_activity.push_back(max((int64_t)0, (io_ticks_total - disk.old_io.at(2))));
+		disk.old_io.at(2) = io_ticks_total;
+		while (cmp_greater(disk.io_activity.size(), width * 2)) disk.io_activity.pop_front();
+
+		return true;
+	}
+
+}
+
+namespace Net {
+	std::unordered_map<string, net_info> current_net;
+	net_info empty_net = {};
+	vector<string> interfaces;
+	string selected_iface;
+	int errors{};
+	std::unordered_map<string, uint64_t> graph_max = { {"download", {}}, {"upload", {}} };
+	std::unordered_map<string, array<int, 2>> max_count = { {"download", {}}, {"upload", {}} };
+	bool rescale{true};
+	uint64_t timestamp{};
+
+	auto collect(bool no_update) -> net_info& {
+		if (Runner::stopping) return empty_net;
+		auto& net = current_net;
+		auto& config_iface = Config::getS("net_iface");
+		auto net_sync = Config::getB("net_sync");
+		auto net_auto = Config::getB("net_auto");
+		auto new_timestamp = time_ms();
+
+		if (not no_update and errors < 3) {
+			//? Get interface list using getifaddrs() wrapper
+			IfAddrsPtr if_addrs {};
+			if (if_addrs.get_status() != 0) {
+				errors++;
+				Logger::error("Net::collect() -> getifaddrs() failed with id " + to_string(if_addrs.get_status()));
+				redraw = true;
+				return empty_net;
+			}
+			int family = 0;
+			static_assert(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN); // 46 >= 16, compile-time assurance.
+			enum { IPBUFFER_MAXSIZE = INET6_ADDRSTRLEN }; // manually using the known biggest value, guarded by the above static_assert
+			char ip[IPBUFFER_MAXSIZE];
+			interfaces.clear();
+			string ipv4, ipv6;
+
+			//? Iteration over all items in getifaddrs() list
+			for (auto* ifa = if_addrs.get(); ifa != nullptr; ifa = ifa->ifa_next) {
+				if (ifa->ifa_addr == nullptr) continue;
+				family = ifa->ifa_addr->sa_family;
+				const auto& iface = ifa->ifa_name;
+
+				//? Update available interfaces vector and get status of interface
+				if (not v_contains(interfaces, iface)) {
+					interfaces.push_back(iface);
+					net[iface].connected = (ifa->ifa_flags & IFF_RUNNING);
+
+					// An interface can have more than one IP of the same family associated with it,
+					// but we pick only the first one to show in the NET box.
+					// Note: Interfaces without any IPv4 and IPv6 set are still valid and monitorable!
+					net[iface].ipv4.clear();
+					net[iface].ipv6.clear();
+				}
+
+
+				//? Get IPv4 address
+				if (family == AF_INET) {
+					if (net[iface].ipv4.empty()) {
+						if (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr)->sin_addr), ip, IPBUFFER_MAXSIZE)) {
+							net[iface].ipv4 = ip;
+						} else {
+							int errsv = errno;
+							Logger::error("Net::collect() -> Failed to convert IPv4 to string for iface " + string(iface) + ", errno: " + strerror(errsv));
+						}
+					}
+				}
+				//? Get IPv6 address
+				else if (family == AF_INET6) {
+					if (net[iface].ipv6.empty()) {
+						if (nullptr != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr)->sin6_addr), ip, IPBUFFER_MAXSIZE)) {
+							net[iface].ipv6 = ip;
+						} else {
+							int errsv = errno;
+							Logger::error("Net::collect() -> Failed to convert IPv6 to string for iface " + string(iface) + ", errno: " + strerror(errsv));
+						}
+					}
+				} //else, ignoring family==AF_PACKET (see man 3 getifaddrs) which is the first one in the `for` loop.
+			}
+
+			//? Get total received and transmitted bytes + device address if no ip was found
+			for (const auto& iface : interfaces) {
+				auto& netif = net.at(iface);
+				if (netif.ipv4.empty() and netif.ipv6.empty())
+					netif.ipv4 = readfile("/sys/class/net/" + iface + "/address");
+
+				for (const string dir : {"download", "upload"}) {
+					const fs::path sys_file = "/sys/class/net/" + iface + "/statistics/" + (dir == "download" ? "rx_bytes" : "tx_bytes");
+					auto& saved_stat = netif.stat.at(dir);
+					auto& bandwidth = netif.bandwidth.at(dir);
+
+					uint64_t val{};
+					try { val = stoull(readfile(sys_file, "0")); }
+					catch (const std::invalid_argument&) {}
+					catch (const std::out_of_range&) {}
+
+					//? Update speed, total and top values
+					if (val < saved_stat.last) {
+						saved_stat.rollover += saved_stat.last;
+						saved_stat.last = 0;
+					}
+					if (cmp_greater((unsigned long long)saved_stat.rollover + (unsigned long long)val, numeric_limits<uint64_t>::max())) {
+						saved_stat.rollover = 0;
+						saved_stat.last = 0;
+					}
+					saved_stat.speed = round((double)(val - saved_stat.last) / ((double)(new_timestamp - timestamp) / 1000));
+					if (saved_stat.speed > saved_stat.top) saved_stat.top = saved_stat.speed;
+					if (saved_stat.offset > val + saved_stat.rollover) saved_stat.offset = 0;
+					saved_stat.total = (val + saved_stat.rollover) - saved_stat.offset;
+					saved_stat.last = val;
+
+					//? Add values to graph
+					bandwidth.push_back(saved_stat.speed);
+					while (cmp_greater(bandwidth.size(), width * 2)) bandwidth.pop_front();
+
+					//? Set counters for auto scaling
+					if (net_auto and selected_iface == iface) {
+						if (net_sync and saved_stat.speed < netif.stat.at(dir == "download" ? "upload" : "download").speed) continue;
+						if (saved_stat.speed > graph_max[dir]) {
+							++max_count[dir][0];
+							if (max_count[dir][1] > 0) --max_count[dir][1];
+						}
+						else if (graph_max[dir] > 10 << 10 and saved_stat.speed < graph_max[dir] / 10) {
+							++max_count[dir][1];
+							if (max_count[dir][0] > 0) --max_count[dir][0];
+						}
+
+					}
+				}
+			}
+
+			//? Clean up net map if needed
+			if (net.size() > interfaces.size()) {
+				for (auto it = net.begin(); it != net.end();) {
+					if (not v_contains(interfaces, it->first))
+						it = net.erase(it);
+					else
+						it++;
+				}
+			}
+
+			timestamp = new_timestamp;
+		}
+
+		//? Return empty net_info struct if no interfaces was found
+		if (net.empty())
+			return empty_net;
+
+		//? Find an interface to display if selected isn't set or valid
+		if (selected_iface.empty() or not v_contains(interfaces, selected_iface)) {
+			max_count["download"][0] = max_count["download"][1] = max_count["upload"][0] = max_count["upload"][1] = 0;
+			redraw = true;
+			if (net_auto) rescale = true;
+			if (not config_iface.empty() and v_contains(interfaces, config_iface)) selected_iface = config_iface;
+			else {
+				//? Sort interfaces by total upload + download bytes
+				auto sorted_interfaces = interfaces;
+				rng::sort(sorted_interfaces, [&](const auto& a, const auto& b){
+					return 	cmp_greater(net.at(a).stat["download"].total + net.at(a).stat["upload"].total,
+										net.at(b).stat["download"].total + net.at(b).stat["upload"].total);
+				});
+				selected_iface.clear();
+				//? Try to set to a connected interface
+				for (const auto& iface : sorted_interfaces) {
+					if (net.at(iface).connected) {
+						selected_iface = iface;
+						break;
+					}
+				}
+				//? If no interface is connected set to first available
+				if (selected_iface.empty() and not sorted_interfaces.empty()) selected_iface = sorted_interfaces.at(0);
+				else if (sorted_interfaces.empty()) return empty_net;
+
+			}
+		}
+
+		//? Calculate max scale for graphs if needed
+		if (net_auto) {
+			bool sync = false;
+			for (const auto& dir: {"download", "upload"}) {
+				for (const auto& sel : {0, 1}) {
+					if (rescale or max_count[dir][sel] >= 5) {
+						const long long avg_speed = (net[selected_iface].bandwidth[dir].size() > 5
+							? std::accumulate(net.at(selected_iface).bandwidth.at(dir).rbegin(), net.at(selected_iface).bandwidth.at(dir).rbegin() + 5, 0ll) / 5
+							: net[selected_iface].stat[dir].speed);
+						graph_max[dir] = max(uint64_t(avg_speed * (sel == 0 ? 1.3 : 3.0)), (uint64_t)10 << 10);
+						max_count[dir][0] = max_count[dir][1] = 0;
+						redraw = true;
+						if (net_sync) sync = true;
+						break;
+					}
+				}
+				//? Sync download/upload graphs if enabled
+				if (sync) {
+					const auto other = (string(dir) == "upload" ? "download" : "upload");
+					graph_max[other] = graph_max[dir];
+					max_count[other][0] = max_count[other][1] = 0;
+					break;
+				}
+			}
+		}
+
+		rescale = false;
+		return net.at(selected_iface);
+	}
+}
+
+namespace Proc {
+
+	vector<proc_info> current_procs;
+	std::unordered_map<string, string> uid_user;
+	string current_sort;
+	string current_filter;
+	bool current_rev{};
+	bool is_tree_mode;
+
+	fs::file_time_type passwd_time;
+
+	uint64_t cputimes;
+	int collapse = -1, expand = -1, toggle_children = -1;
+	uint64_t old_cputimes{};
+	atomic<int> numpids{};
+	int filter_found{};
+
+	detail_container detailed;
+	constexpr size_t KTHREADD = 2;
+	static std::unordered_set<size_t> kernels_procs = {KTHREADD};
+	static std::unordered_set<size_t> dead_procs;
+
+	//* Get detailed info for selected process
+	static void _collect_details(const size_t pid, const uint64_t uptime, vector<proc_info>& procs) {
+		fs::path pid_path = Shared::procPath / std::to_string(pid);
+
+		if (pid != detailed.last_pid) {
+			detailed = {};
+			detailed.last_pid = pid;
+			detailed.skip_smaps = not Config::getB("proc_info_smaps");
+		}
+
+		//? Copy proc_info for process from proc vector
+		auto p_info = rng::find(procs, pid, &proc_info::pid);
+		detailed.entry = *p_info;
+
+		//? Update cpu percent deque for process cpu graph
+		if (not Config::getB("proc_per_core")) detailed.entry.cpu_p *= Shared::coreCount;
+		detailed.cpu_percent.push_back(clamp((long long)round(detailed.entry.cpu_p), 0ll, 100ll));
+		while (cmp_greater(detailed.cpu_percent.size(), width)) detailed.cpu_percent.pop_front();
+
+		//? Process runtime
+		if (detailed.entry.state != 'X') detailed.elapsed = sec_to_dhms(uptime - (detailed.entry.cpu_s / Shared::clkTck));
+		else detailed.elapsed = sec_to_dhms(detailed.entry.death_time);
+		if (detailed.elapsed.size() > 8) detailed.elapsed.resize(detailed.elapsed.size() - 3);
+
+		//? Get parent process name
+		if (detailed.parent.empty()) {
+			auto p_entry = rng::find(procs, detailed.entry.ppid, &proc_info::pid);
+			if (p_entry != procs.end()) detailed.parent = p_entry->name;
+		}
+
+		//? Expand process status from single char to explanative string
+		detailed.status = (proc_states.contains(detailed.entry.state)) ? proc_states.at(detailed.entry.state) : "Unknown";
+
+		ifstream d_read;
+		string short_str;
+
+		//? Try to get RSS mem from proc/[pid]/smaps
+		detailed.memory.clear();
+		if (not detailed.skip_smaps and fs::exists(pid_path / "smaps")) {
+			d_read.open(pid_path / "smaps");
+			uint64_t rss = 0;
+			try {
+				while (d_read.good()) {
+					d_read.ignore(SSmax, 'R');
+					if (d_read.peek() == 's') {
+						d_read.ignore(SSmax, ':');
+						getline(d_read, short_str, 'k');
+						rss += stoull(short_str);
+					}
+				}
+				if (rss == detailed.entry.mem >> 10)
+					detailed.skip_smaps = true;
+				else {
+					detailed.mem_bytes.push_back(rss << 10);
+					detailed.memory = floating_humanizer(rss, false, 1);
+				}
+			}
+			catch (const std::invalid_argument&) {}
+			catch (const std::out_of_range&) {}
+			d_read.close();
+		}
+		if (detailed.memory.empty()) {
+			detailed.mem_bytes.push_back(detailed.entry.mem);
+			detailed.memory = floating_humanizer(detailed.entry.mem);
+		}
+		if (detailed.first_mem == -1 or detailed.first_mem < detailed.mem_bytes.back() / 2 or detailed.first_mem > detailed.mem_bytes.back() * 4) {
+			detailed.first_mem = min((uint64_t)detailed.mem_bytes.back() * 2, Mem::get_totalMem());
+			redraw = true;
+		}
+
+		while (cmp_greater(detailed.mem_bytes.size(), width)) detailed.mem_bytes.pop_front();
+
+		//? Get bytes read and written from proc/[pid]/io
+		if (fs::exists(pid_path / "io")) {
+			d_read.open(pid_path / "io");
+			try {
+				string name;
+				while (d_read.good()) {
+					getline(d_read, name, ':');
+					if (name.ends_with("read_bytes")) {
+						getline(d_read, short_str);
+						detailed.io_read = floating_humanizer(stoull(short_str));
+					}
+					else if (name.ends_with("write_bytes")) {
+						getline(d_read, short_str);
+						detailed.io_write = floating_humanizer(stoull(short_str));
+						break;
+					}
+					else
+						d_read.ignore(SSmax, '\n');
+				}
+			}
+			catch (const std::invalid_argument&) {}
+			catch (const std::out_of_range&) {}
+			d_read.close();
+		}
+	}
+
+	//* Collects from chat_history.db
+	auto collect(bool no_update) -> vector<proc_info>& {
+		if (Runner::stopping) return current_procs;
+		if (no_update and not current_procs.empty()) return current_procs;
+
+		current_procs.clear();
+		const auto& filter = Config::getS("proc_filter");
+
+		if (!AltData::init()) {
+			numpids = 0;
+			return current_procs;
+		}
+
+		auto clean_text = [](const string& s) {
+			string out;
+			out.reserve(s.size());
+			auto append_utf8 = [&](char32_t x) {
+				if (x < 0x80) out.push_back(static_cast<char>(x));
+				else if (x < 0x800) {
+					out.push_back(static_cast<char>(0xC0 | (x >> 6)));
+					out.push_back(static_cast<char>(0x80 | (x & 0x3F)));
+				} else if (x < 0x10000) {
+					out.push_back(static_cast<char>(0xE0 | (x >> 12)));
+					out.push_back(static_cast<char>(0x80 | ((x >> 6) & 0x3F)));
+					out.push_back(static_cast<char>(0x80 | (x & 0x3F)));
+				} else {
+					out.push_back(static_cast<char>(0xF0 | (x >> 18)));
+					out.push_back(static_cast<char>(0x80 | ((x >> 12) & 0x3F)));
+					out.push_back(static_cast<char>(0x80 | ((x >> 6) & 0x3F)));
+					out.push_back(static_cast<char>(0x80 | (x & 0x3F)));
+				}
+			};
+
+			// 允许的ASCII符号: . , ! ? : ; ' " / ( ) [ ] + % $ = @ &
+			auto is_allowed_ascii = [](char32_t c) {
+				if (c >= 'a' && c <= 'z') return true;
+				if (c >= 'A' && c <= 'Z') return true;
+				if (c >= '0' && c <= '9') return true;
+				if (c == ' ' || c == '.' || c == ',' || c == '!' || c == '?' ||
+				    c == ':' || c == ';' || c == '\'' || c == '"' ||
+				    c == '/' || c == '(' || c == ')' || c == '[' || c == ']' ||
+				    c == '+' || c == '%' || c == '$' || c == '=' || c == '@' || c == '&')
+					return true;
+				return false;
+			};
+
+			for (size_t i = 0; i < s.size();) {
+				unsigned char c = static_cast<unsigned char>(s[i]);
+				char32_t cp = 0;
+				size_t len = 0;
+				if (c == '\\' && i + 5 < s.size() && s[i + 1] == 'u') {
+					auto hex = s.substr(i + 2, 4);
+					for (char h : hex) {
+						cp <<= 4;
+						if (h >= '0' && h <= '9') cp += h - '0';
+						else if (h >= 'a' && h <= 'f') cp += h - 'a' + 10;
+						else if (h >= 'A' && h <= 'F') cp += h - 'A' + 10;
+					}
+					len = 6;
+				}
+				else if (c < 0x80) { cp = c; len = 1; }
+				else if ((c >> 5) == 0x6 && i + 1 < s.size()) {
+					cp = ((c & 0x1F) << 6) | (static_cast<unsigned char>(s[i + 1]) & 0x3F);
+					len = 2;
+				}
+				else if ((c >> 4) == 0xE && i + 2 < s.size()) {
+					cp = ((c & 0x0F) << 12) | ((static_cast<unsigned char>(s[i + 1]) & 0x3F) << 6) |
+						 (static_cast<unsigned char>(s[i + 2]) & 0x3F);
+					len = 3;
+				}
+				else if ((c >> 3) == 0x1E && i + 3 < s.size()) {
+					cp = ((c & 0x07) << 18) | ((static_cast<unsigned char>(s[i + 1]) & 0x3F) << 12) |
+						 ((static_cast<unsigned char>(s[i + 2]) & 0x3F) << 6) | (static_cast<unsigned char>(s[i + 3]) & 0x3F);
+					len = 4;
+				} else { ++i; continue; }
+				i += len;
+
+				// 换行转空格
+				if (cp == '\n' || cp == '\r' || cp == '\t') {
+					if (!out.empty() && out.back() != ' ') out.push_back(' ');
+					continue;
+				}
+				// ASCII: 只允许白名单字符
+				if (cp < 0x80) {
+					if (is_allowed_ascii(cp)) out.push_back(static_cast<char>(cp));
+					continue;
+				}
+				// CJK 汉字
+				if (cp >= 0x4E00 && cp <= 0x9FFF) { append_utf8(cp); continue; }
+				// 中文标点白名单
+				if (cp == 0x3002 ||  // 。
+				    cp == 0xFF0C ||  // ,
+				    cp == 0xFF01 ||  // !
+				    cp == 0xFF1F ||  // ?
+				    cp == 0xFF1A ||  // :
+				    cp == 0xFF1B ||  // ;
+				    cp == 0xFF08 ||  // (
+				    cp == 0xFF09 ||  // )
+				    cp == 0x3010 ||  // 【
+				    cp == 0x3011 ||  // 】
+				    cp == 0x201C ||  // "
+				    cp == 0x201D ||  // "
+				    cp == 0x2018 ||  // '
+				    cp == 0x2019 ||  // '
+				    cp == 0x3001 ||  // 、
+				    cp == 0x2026)    // …
+				{
+					append_utf8(cp); continue;
+				}
+			}
+
+			string final; bool last_space = true;
+			for (char ch : out) {
+				if (ch == ' ') {
+					if (!last_space) { final += ch; last_space = true; }
+				} else { final += ch; last_space = false; }
+			}
+			return final;
+		};
+
+		// 查询 chat_history.db 的 sessions 表,提取最后一条消息的 content 值
+		string sql = "SELECT file_path, start_time, source, "
+					 "substr(messages, instr(messages, '\"content\": \"') + 13, 800), "
+					 "token_count, session_id "
+					 "FROM sessions ";
+		if (!filter.empty()) sql += "WHERE (source LIKE '%" + filter + "%' OR messages LIKE '%" + filter + "%') ";
+		sql += "ORDER BY start_time DESC LIMIT 500";
+
+		sqlite3_stmt* stmt = nullptr;
+		int row_num = 0;
+		if (sqlite3_prepare_v2(AltData::db, sql.c_str(), -1, &stmt, nullptr) == SQLITE_OK) {
+			while (sqlite3_step(stmt) == SQLITE_ROW) {
+				proc_info p;
+				p.pid = ++row_num;
+
+				// start_time -> short_cmd (显示时间)
+				const char* ts = (const char*)sqlite3_column_text(stmt, 1);
+				if (ts) {
+					string ts_str = ts;
+					size_t t_pos = ts_str.find('T');
+					if (t_pos != string::npos && ts_str.length() > t_pos + 8) p.short_cmd = ts_str.substr(t_pos + 1, 8);
+					else p.short_cmd = ts_str.substr(0, 8);
+				}
+
+				// source -> user/name (claude/codex/gemini/kiro)
+				const char* source = (const char*)sqlite3_column_text(stmt, 2);
+				p.user = source ? source : "";
+				p.name = p.user;
+
+				// messages content -> cmd (消息内容,保留头尾截断中间)
+				const char* content = (const char*)sqlite3_column_text(stmt, 3);
+				string raw = content ? content : "";
+				// 截断:保留前150 + ... + 后150
+				const size_t HEAD = 150, TAIL = 150;
+				if (raw.length() > HEAD + TAIL + 10) {
+					raw = raw.substr(0, HEAD) + " ... " + raw.substr(raw.length() - TAIL);
+				}
+				p.cmd = clean_text(raw);
+				if (p.cmd.empty()) p.cmd = "<empty>";
+
+				// token_count -> threads
+				p.threads = sqlite3_column_int(stmt, 4);
+
+				p.state = 'R';
+				current_procs.push_back(std::move(p));
+			}
+			sqlite3_finalize(stmt);
+		}
+
+		numpids = (int)current_procs.size();
+
+		return current_procs;
+	}
+}
+
+namespace Tools {
+	double system_uptime() {
+		string upstr;
+		ifstream pread(Shared::procPath / "uptime");
+		if (pread.good()) {
+			try {
+				getline(pread, upstr, ' ');
+				pread.close();
+				return stod(upstr);
+			}
+			catch (const std::invalid_argument&) {}
+			catch (const std::out_of_range&) {}
+		}
+        throw std::runtime_error("Failed to get uptime from " + string{Shared::procPath} + "/uptime");
+	}
+}

+ 19 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/CMakeLists.txt

@@ -0,0 +1,19 @@
+enable_language(C)
+
+add_library(igt OBJECT
+  igt_perf.c
+  intel_device_info.c
+  intel_gpu_top.c
+  intel_name_lookup_shim.c
+)
+
+if(BTOP_LTO)
+  # We have checked LTO support already and it's supported :)
+  set_target_properties(igt PROPERTIES INTERPROCEDURAL_OPTIMIZATION ON)
+endif()
+
+# Disable all warnings
+target_compile_options(igt PRIVATE -w)
+
+# Link igt into btop
+target_link_libraries(libbtop $<TARGET_OBJECTS:igt>)

+ 1318 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/drm.h

@@ -0,0 +1,1318 @@
+/*
+ * Header for the Direct Rendering Manager
+ *
+ * Author: Rickard E. (Rik) Faith <faith@valinux.com>
+ *
+ * Acknowledgments:
+ * Dec 1999, Richard Henderson <rth@twiddle.net>, move to generic cmpxchg.
+ */
+
+/*
+ * Copyright 1999 Precision Insight, Inc., Cedar Park, Texas.
+ * Copyright 2000 VA Linux Systems, Inc., Sunnyvale, California.
+ * All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * VA LINUX SYSTEMS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ * OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef _DRM_H_
+#define _DRM_H_
+
+#if   defined(__linux__)
+
+#include <linux/types.h>
+#include <asm/ioctl.h>
+typedef unsigned int drm_handle_t;
+
+#else /* One of the BSDs */
+
+#include <stdint.h>
+#include <sys/ioccom.h>
+#include <sys/types.h>
+typedef int8_t   __s8;
+typedef uint8_t  __u8;
+typedef int16_t  __s16;
+typedef uint16_t __u16;
+typedef int32_t  __s32;
+typedef uint32_t __u32;
+typedef int64_t  __s64;
+typedef uint64_t __u64;
+typedef size_t   __kernel_size_t;
+typedef unsigned long drm_handle_t;
+
+#endif
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+#define DRM_NAME	"drm"	  /**< Name in kernel, /dev, and /proc */
+#define DRM_MIN_ORDER	5	  /**< At least 2^5 bytes = 32 bytes */
+#define DRM_MAX_ORDER	22	  /**< Up to 2^22 bytes = 4MB */
+#define DRM_RAM_PERCENT 10	  /**< How much system ram can we lock? */
+
+#define _DRM_LOCK_HELD	0x80000000U /**< Hardware lock is held */
+#define _DRM_LOCK_CONT	0x40000000U /**< Hardware lock is contended */
+#define _DRM_LOCK_IS_HELD(lock)	   ((lock) & _DRM_LOCK_HELD)
+#define _DRM_LOCK_IS_CONT(lock)	   ((lock) & _DRM_LOCK_CONT)
+#define _DRM_LOCKING_CONTEXT(lock) ((lock) & ~(_DRM_LOCK_HELD|_DRM_LOCK_CONT))
+
+typedef unsigned int drm_context_t;
+typedef unsigned int drm_drawable_t;
+typedef unsigned int drm_magic_t;
+
+/*
+ * Cliprect.
+ *
+ * \warning: If you change this structure, make sure you change
+ * XF86DRIClipRectRec in the server as well
+ *
+ * \note KW: Actually it's illegal to change either for
+ * backwards-compatibility reasons.
+ */
+struct drm_clip_rect {
+	unsigned short x1;
+	unsigned short y1;
+	unsigned short x2;
+	unsigned short y2;
+};
+
+/*
+ * Drawable information.
+ */
+struct drm_drawable_info {
+	unsigned int num_rects;
+	struct drm_clip_rect *rects;
+};
+
+/*
+ * Texture region,
+ */
+struct drm_tex_region {
+	unsigned char next;
+	unsigned char prev;
+	unsigned char in_use;
+	unsigned char padding;
+	unsigned int age;
+};
+
+/*
+ * Hardware lock.
+ *
+ * The lock structure is a simple cache-line aligned integer.  To avoid
+ * processor bus contention on a multiprocessor system, there should not be any
+ * other data stored in the same cache line.
+ */
+struct drm_hw_lock {
+	__volatile__ unsigned int lock;		/**< lock variable */
+	char padding[60];			/**< Pad to cache line */
+};
+
+/*
+ * DRM_IOCTL_VERSION ioctl argument type.
+ *
+ * \sa drmGetVersion().
+ */
+struct drm_version {
+	int version_major;	  /**< Major version */
+	int version_minor;	  /**< Minor version */
+	int version_patchlevel;	  /**< Patch level */
+	__kernel_size_t name_len;	  /**< Length of name buffer */
+	char *name;	  /**< Name of driver */
+	__kernel_size_t date_len;	  /**< Length of date buffer */
+	char *date;	  /**< User-space buffer to hold date */
+	__kernel_size_t desc_len;	  /**< Length of desc buffer */
+	char *desc;	  /**< User-space buffer to hold desc */
+};
+
+/*
+ * DRM_IOCTL_GET_UNIQUE ioctl argument type.
+ *
+ * \sa drmGetBusid() and drmSetBusId().
+ */
+struct drm_unique {
+	__kernel_size_t unique_len;	  /**< Length of unique */
+	char *unique;	  /**< Unique name for driver instantiation */
+};
+
+struct drm_list {
+	int count;		  /**< Length of user-space structures */
+	struct drm_version *version;
+};
+
+struct drm_block {
+	int unused;
+};
+
+/*
+ * DRM_IOCTL_CONTROL ioctl argument type.
+ *
+ * \sa drmCtlInstHandler() and drmCtlUninstHandler().
+ */
+struct drm_control {
+	enum {
+		DRM_ADD_COMMAND,
+		DRM_RM_COMMAND,
+		DRM_INST_HANDLER,
+		DRM_UNINST_HANDLER
+	} func;
+	int irq;
+};
+
+/*
+ * Type of memory to map.
+ */
+enum drm_map_type {
+	_DRM_FRAME_BUFFER = 0,	  /**< WC (no caching), no core dump */
+	_DRM_REGISTERS = 1,	  /**< no caching, no core dump */
+	_DRM_SHM = 2,		  /**< shared, cached */
+	_DRM_AGP = 3,		  /**< AGP/GART */
+	_DRM_SCATTER_GATHER = 4,  /**< Scatter/gather memory for PCI DMA */
+	_DRM_CONSISTENT = 5	  /**< Consistent memory for PCI DMA */
+};
+
+/*
+ * Memory mapping flags.
+ */
+enum drm_map_flags {
+	_DRM_RESTRICTED = 0x01,	     /**< Cannot be mapped to user-virtual */
+	_DRM_READ_ONLY = 0x02,
+	_DRM_LOCKED = 0x04,	     /**< shared, cached, locked */
+	_DRM_KERNEL = 0x08,	     /**< kernel requires access */
+	_DRM_WRITE_COMBINING = 0x10, /**< use write-combining if available */
+	_DRM_CONTAINS_LOCK = 0x20,   /**< SHM page that contains lock */
+	_DRM_REMOVABLE = 0x40,	     /**< Removable mapping */
+	_DRM_DRIVER = 0x80	     /**< Managed by driver */
+};
+
+struct drm_ctx_priv_map {
+	unsigned int ctx_id;	 /**< Context requesting private mapping */
+	void *handle;		 /**< Handle of map */
+};
+
+/*
+ * DRM_IOCTL_GET_MAP, DRM_IOCTL_ADD_MAP and DRM_IOCTL_RM_MAP ioctls
+ * argument type.
+ *
+ * \sa drmAddMap().
+ */
+struct drm_map {
+	unsigned long offset;	 /**< Requested physical address (0 for SAREA)*/
+	unsigned long size;	 /**< Requested physical size (bytes) */
+	enum drm_map_type type;	 /**< Type of memory to map */
+	enum drm_map_flags flags;	 /**< Flags */
+	void *handle;		 /**< User-space: "Handle" to pass to mmap() */
+				 /**< Kernel-space: kernel-virtual address */
+	int mtrr;		 /**< MTRR slot used */
+	/*   Private data */
+};
+
+/*
+ * DRM_IOCTL_GET_CLIENT ioctl argument type.
+ */
+struct drm_client {
+	int idx;		/**< Which client desired? */
+	int auth;		/**< Is client authenticated? */
+	unsigned long pid;	/**< Process ID */
+	unsigned long uid;	/**< User ID */
+	unsigned long magic;	/**< Magic */
+	unsigned long iocs;	/**< Ioctl count */
+};
+
+enum drm_stat_type {
+	_DRM_STAT_LOCK,
+	_DRM_STAT_OPENS,
+	_DRM_STAT_CLOSES,
+	_DRM_STAT_IOCTLS,
+	_DRM_STAT_LOCKS,
+	_DRM_STAT_UNLOCKS,
+	_DRM_STAT_VALUE,	/**< Generic value */
+	_DRM_STAT_BYTE,		/**< Generic byte counter (1024bytes/K) */
+	_DRM_STAT_COUNT,	/**< Generic non-byte counter (1000/k) */
+
+	_DRM_STAT_IRQ,		/**< IRQ */
+	_DRM_STAT_PRIMARY,	/**< Primary DMA bytes */
+	_DRM_STAT_SECONDARY,	/**< Secondary DMA bytes */
+	_DRM_STAT_DMA,		/**< DMA */
+	_DRM_STAT_SPECIAL,	/**< Special DMA (e.g., priority or polled) */
+	_DRM_STAT_MISSED	/**< Missed DMA opportunity */
+	    /* Add to the *END* of the list */
+};
+
+/*
+ * DRM_IOCTL_GET_STATS ioctl argument type.
+ */
+struct drm_stats {
+	unsigned long count;
+	struct {
+		unsigned long value;
+		enum drm_stat_type type;
+	} data[15];
+};
+
+/*
+ * Hardware locking flags.
+ */
+enum drm_lock_flags {
+	_DRM_LOCK_READY = 0x01,	     /**< Wait until hardware is ready for DMA */
+	_DRM_LOCK_QUIESCENT = 0x02,  /**< Wait until hardware quiescent */
+	_DRM_LOCK_FLUSH = 0x04,	     /**< Flush this context's DMA queue first */
+	_DRM_LOCK_FLUSH_ALL = 0x08,  /**< Flush all DMA queues first */
+	/* These *HALT* flags aren't supported yet
+	   -- they will be used to support the
+	   full-screen DGA-like mode. */
+	_DRM_HALT_ALL_QUEUES = 0x10, /**< Halt all current and future queues */
+	_DRM_HALT_CUR_QUEUES = 0x20  /**< Halt all current queues */
+};
+
+/*
+ * DRM_IOCTL_LOCK, DRM_IOCTL_UNLOCK and DRM_IOCTL_FINISH ioctl argument type.
+ *
+ * \sa drmGetLock() and drmUnlock().
+ */
+struct drm_lock {
+	int context;
+	enum drm_lock_flags flags;
+};
+
+/*
+ * DMA flags
+ *
+ * \warning
+ * These values \e must match xf86drm.h.
+ *
+ * \sa drm_dma.
+ */
+enum drm_dma_flags {
+	/* Flags for DMA buffer dispatch */
+	_DRM_DMA_BLOCK = 0x01,	      /**<
+				       * Block until buffer dispatched.
+				       *
+				       * \note The buffer may not yet have
+				       * been processed by the hardware --
+				       * getting a hardware lock with the
+				       * hardware quiescent will ensure
+				       * that the buffer has been
+				       * processed.
+				       */
+	_DRM_DMA_WHILE_LOCKED = 0x02, /**< Dispatch while lock held */
+	_DRM_DMA_PRIORITY = 0x04,     /**< High priority dispatch */
+
+	/* Flags for DMA buffer request */
+	_DRM_DMA_WAIT = 0x10,	      /**< Wait for free buffers */
+	_DRM_DMA_SMALLER_OK = 0x20,   /**< Smaller-than-requested buffers OK */
+	_DRM_DMA_LARGER_OK = 0x40     /**< Larger-than-requested buffers OK */
+};
+
+/*
+ * DRM_IOCTL_ADD_BUFS and DRM_IOCTL_MARK_BUFS ioctl argument type.
+ *
+ * \sa drmAddBufs().
+ */
+struct drm_buf_desc {
+	int count;		 /**< Number of buffers of this size */
+	int size;		 /**< Size in bytes */
+	int low_mark;		 /**< Low water mark */
+	int high_mark;		 /**< High water mark */
+	enum {
+		_DRM_PAGE_ALIGN = 0x01,	/**< Align on page boundaries for DMA */
+		_DRM_AGP_BUFFER = 0x02,	/**< Buffer is in AGP space */
+		_DRM_SG_BUFFER = 0x04,	/**< Scatter/gather memory buffer */
+		_DRM_FB_BUFFER = 0x08,	/**< Buffer is in frame buffer */
+		_DRM_PCI_BUFFER_RO = 0x10 /**< Map PCI DMA buffer read-only */
+	} flags;
+	unsigned long agp_start; /**<
+				  * Start address of where the AGP buffers are
+				  * in the AGP aperture
+				  */
+};
+
+/*
+ * DRM_IOCTL_INFO_BUFS ioctl argument type.
+ */
+struct drm_buf_info {
+	int count;		/**< Entries in list */
+	struct drm_buf_desc *list;
+};
+
+/*
+ * DRM_IOCTL_FREE_BUFS ioctl argument type.
+ */
+struct drm_buf_free {
+	int count;
+	int *list;
+};
+
+/*
+ * Buffer information
+ *
+ * \sa drm_buf_map.
+ */
+struct drm_buf_pub {
+	int idx;		       /**< Index into the master buffer list */
+	int total;		       /**< Buffer size */
+	int used;		       /**< Amount of buffer in use (for DMA) */
+	void *address;	       /**< Address of buffer */
+};
+
+/*
+ * DRM_IOCTL_MAP_BUFS ioctl argument type.
+ */
+struct drm_buf_map {
+	int count;		/**< Length of the buffer list */
+#ifdef __cplusplus
+	void *virt;
+#else
+	void *virtual;		/**< Mmap'd area in user-virtual */
+#endif
+	struct drm_buf_pub *list;	/**< Buffer information */
+};
+
+/*
+ * DRM_IOCTL_DMA ioctl argument type.
+ *
+ * Indices here refer to the offset into the buffer list in drm_buf_get.
+ *
+ * \sa drmDMA().
+ */
+struct drm_dma {
+	int context;			  /**< Context handle */
+	int send_count;			  /**< Number of buffers to send */
+	int *send_indices;	  /**< List of handles to buffers */
+	int *send_sizes;		  /**< Lengths of data to send */
+	enum drm_dma_flags flags;	  /**< Flags */
+	int request_count;		  /**< Number of buffers requested */
+	int request_size;		  /**< Desired size for buffers */
+	int *request_indices;	  /**< Buffer information */
+	int *request_sizes;
+	int granted_count;		  /**< Number of buffers granted */
+};
+
+enum drm_ctx_flags {
+	_DRM_CONTEXT_PRESERVED = 0x01,
+	_DRM_CONTEXT_2DONLY = 0x02
+};
+
+/*
+ * DRM_IOCTL_ADD_CTX ioctl argument type.
+ *
+ * \sa drmCreateContext() and drmDestroyContext().
+ */
+struct drm_ctx {
+	drm_context_t handle;
+	enum drm_ctx_flags flags;
+};
+
+/*
+ * DRM_IOCTL_RES_CTX ioctl argument type.
+ */
+struct drm_ctx_res {
+	int count;
+	struct drm_ctx *contexts;
+};
+
+/*
+ * DRM_IOCTL_ADD_DRAW and DRM_IOCTL_RM_DRAW ioctl argument type.
+ */
+struct drm_draw {
+	drm_drawable_t handle;
+};
+
+/*
+ * DRM_IOCTL_UPDATE_DRAW ioctl argument type.
+ */
+typedef enum {
+	DRM_DRAWABLE_CLIPRECTS
+} drm_drawable_info_type_t;
+
+struct drm_update_draw {
+	drm_drawable_t handle;
+	unsigned int type;
+	unsigned int num;
+	unsigned long long data;
+};
+
+/*
+ * DRM_IOCTL_GET_MAGIC and DRM_IOCTL_AUTH_MAGIC ioctl argument type.
+ */
+struct drm_auth {
+	drm_magic_t magic;
+};
+
+/*
+ * DRM_IOCTL_IRQ_BUSID ioctl argument type.
+ *
+ * \sa drmGetInterruptFromBusID().
+ */
+struct drm_irq_busid {
+	int irq;	/**< IRQ number */
+	int busnum;	/**< bus number */
+	int devnum;	/**< device number */
+	int funcnum;	/**< function number */
+};
+
+enum drm_vblank_seq_type {
+	_DRM_VBLANK_ABSOLUTE = 0x0,	/**< Wait for specific vblank sequence number */
+	_DRM_VBLANK_RELATIVE = 0x1,	/**< Wait for given number of vblanks */
+	/* bits 1-6 are reserved for high crtcs */
+	_DRM_VBLANK_HIGH_CRTC_MASK = 0x0000003e,
+	_DRM_VBLANK_EVENT = 0x4000000,   /**< Send event instead of blocking */
+	_DRM_VBLANK_FLIP = 0x8000000,   /**< Scheduled buffer swap should flip */
+	_DRM_VBLANK_NEXTONMISS = 0x10000000,	/**< If missed, wait for next vblank */
+	_DRM_VBLANK_SECONDARY = 0x20000000,	/**< Secondary display controller */
+	_DRM_VBLANK_SIGNAL = 0x40000000	/**< Send signal instead of blocking, unsupported */
+};
+#define _DRM_VBLANK_HIGH_CRTC_SHIFT 1
+
+#define _DRM_VBLANK_TYPES_MASK (_DRM_VBLANK_ABSOLUTE | _DRM_VBLANK_RELATIVE)
+#define _DRM_VBLANK_FLAGS_MASK (_DRM_VBLANK_EVENT | _DRM_VBLANK_SIGNAL | \
+				_DRM_VBLANK_SECONDARY | _DRM_VBLANK_NEXTONMISS)
+
+struct drm_wait_vblank_request {
+	enum drm_vblank_seq_type type;
+	unsigned int sequence;
+	unsigned long signal;
+};
+
+struct drm_wait_vblank_reply {
+	enum drm_vblank_seq_type type;
+	unsigned int sequence;
+	long tval_sec;
+	long tval_usec;
+};
+
+/*
+ * DRM_IOCTL_WAIT_VBLANK ioctl argument type.
+ *
+ * \sa drmWaitVBlank().
+ */
+union drm_wait_vblank {
+	struct drm_wait_vblank_request request;
+	struct drm_wait_vblank_reply reply;
+};
+
+#define _DRM_PRE_MODESET 1
+#define _DRM_POST_MODESET 2
+
+/*
+ * DRM_IOCTL_MODESET_CTL ioctl argument type
+ *
+ * \sa drmModesetCtl().
+ */
+struct drm_modeset_ctl {
+	__u32 crtc;
+	__u32 cmd;
+};
+
+/*
+ * DRM_IOCTL_AGP_ENABLE ioctl argument type.
+ *
+ * \sa drmAgpEnable().
+ */
+struct drm_agp_mode {
+	unsigned long mode;	/**< AGP mode */
+};
+
+/*
+ * DRM_IOCTL_AGP_ALLOC and DRM_IOCTL_AGP_FREE ioctls argument type.
+ *
+ * \sa drmAgpAlloc() and drmAgpFree().
+ */
+struct drm_agp_buffer {
+	unsigned long size;	/**< In bytes -- will round to page boundary */
+	unsigned long handle;	/**< Used for binding / unbinding */
+	unsigned long type;	/**< Type of memory to allocate */
+	unsigned long physical;	/**< Physical used by i810 */
+};
+
+/*
+ * DRM_IOCTL_AGP_BIND and DRM_IOCTL_AGP_UNBIND ioctls argument type.
+ *
+ * \sa drmAgpBind() and drmAgpUnbind().
+ */
+struct drm_agp_binding {
+	unsigned long handle;	/**< From drm_agp_buffer */
+	unsigned long offset;	/**< In bytes -- will round to page boundary */
+};
+
+/*
+ * DRM_IOCTL_AGP_INFO ioctl argument type.
+ *
+ * \sa drmAgpVersionMajor(), drmAgpVersionMinor(), drmAgpGetMode(),
+ * drmAgpBase(), drmAgpSize(), drmAgpMemoryUsed(), drmAgpMemoryAvail(),
+ * drmAgpVendorId() and drmAgpDeviceId().
+ */
+struct drm_agp_info {
+	int agp_version_major;
+	int agp_version_minor;
+	unsigned long mode;
+	unsigned long aperture_base;	/* physical address */
+	unsigned long aperture_size;	/* bytes */
+	unsigned long memory_allowed;	/* bytes */
+	unsigned long memory_used;
+
+	/* PCI information */
+	unsigned short id_vendor;
+	unsigned short id_device;
+};
+
+/*
+ * DRM_IOCTL_SG_ALLOC ioctl argument type.
+ */
+struct drm_scatter_gather {
+	unsigned long size;	/**< In bytes -- will round to page boundary */
+	unsigned long handle;	/**< Used for mapping / unmapping */
+};
+
+/*
+ * DRM_IOCTL_SET_VERSION ioctl argument type.
+ */
+struct drm_set_version {
+	int drm_di_major;
+	int drm_di_minor;
+	int drm_dd_major;
+	int drm_dd_minor;
+};
+
+/* DRM_IOCTL_GEM_CLOSE ioctl argument type */
+struct drm_gem_close {
+	/** Handle of the object to be closed. */
+	__u32 handle;
+	__u32 pad;
+};
+
+/* DRM_IOCTL_GEM_FLINK ioctl argument type */
+struct drm_gem_flink {
+	/** Handle for the object being named */
+	__u32 handle;
+
+	/** Returned global name */
+	__u32 name;
+};
+
+/* DRM_IOCTL_GEM_OPEN ioctl argument type */
+struct drm_gem_open {
+	/** Name of object being opened */
+	__u32 name;
+
+	/** Returned handle for the object */
+	__u32 handle;
+
+	/** Returned size of the object */
+	__u64 size;
+};
+
+/**
+ * DRM_CAP_DUMB_BUFFER
+ *
+ * If set to 1, the driver supports creating dumb buffers via the
+ * &DRM_IOCTL_MODE_CREATE_DUMB ioctl.
+ */
+#define DRM_CAP_DUMB_BUFFER		0x1
+/**
+ * DRM_CAP_VBLANK_HIGH_CRTC
+ *
+ * If set to 1, the kernel supports specifying a :ref:`CRTC index<crtc_index>`
+ * in the high bits of &drm_wait_vblank_request.type.
+ *
+ * Starting kernel version 2.6.39, this capability is always set to 1.
+ */
+#define DRM_CAP_VBLANK_HIGH_CRTC	0x2
+/**
+ * DRM_CAP_DUMB_PREFERRED_DEPTH
+ *
+ * The preferred bit depth for dumb buffers.
+ *
+ * The bit depth is the number of bits used to indicate the color of a single
+ * pixel excluding any padding. This is different from the number of bits per
+ * pixel. For instance, XRGB8888 has a bit depth of 24 but has 32 bits per
+ * pixel.
+ *
+ * Note that this preference only applies to dumb buffers, it's irrelevant for
+ * other types of buffers.
+ */
+#define DRM_CAP_DUMB_PREFERRED_DEPTH	0x3
+/**
+ * DRM_CAP_DUMB_PREFER_SHADOW
+ *
+ * If set to 1, the driver prefers userspace to render to a shadow buffer
+ * instead of directly rendering to a dumb buffer. For best speed, userspace
+ * should do streaming ordered memory copies into the dumb buffer and never
+ * read from it.
+ *
+ * Note that this preference only applies to dumb buffers, it's irrelevant for
+ * other types of buffers.
+ */
+#define DRM_CAP_DUMB_PREFER_SHADOW	0x4
+/**
+ * DRM_CAP_PRIME
+ *
+ * Bitfield of supported PRIME sharing capabilities. See &DRM_PRIME_CAP_IMPORT
+ * and &DRM_PRIME_CAP_EXPORT.
+ *
+ * Starting from kernel version 6.6, both &DRM_PRIME_CAP_IMPORT and
+ * &DRM_PRIME_CAP_EXPORT are always advertised.
+ *
+ * PRIME buffers are exposed as dma-buf file descriptors.
+ * See :ref:`prime_buffer_sharing`.
+ */
+#define DRM_CAP_PRIME			0x5
+/**
+ * DRM_PRIME_CAP_IMPORT
+ *
+ * If this bit is set in &DRM_CAP_PRIME, the driver supports importing PRIME
+ * buffers via the &DRM_IOCTL_PRIME_FD_TO_HANDLE ioctl.
+ *
+ * Starting from kernel version 6.6, this bit is always set in &DRM_CAP_PRIME.
+ */
+#define  DRM_PRIME_CAP_IMPORT		0x1
+/**
+ * DRM_PRIME_CAP_EXPORT
+ *
+ * If this bit is set in &DRM_CAP_PRIME, the driver supports exporting PRIME
+ * buffers via the &DRM_IOCTL_PRIME_HANDLE_TO_FD ioctl.
+ *
+ * Starting from kernel version 6.6, this bit is always set in &DRM_CAP_PRIME.
+ */
+#define  DRM_PRIME_CAP_EXPORT		0x2
+/**
+ * DRM_CAP_TIMESTAMP_MONOTONIC
+ *
+ * If set to 0, the kernel will report timestamps with ``CLOCK_REALTIME`` in
+ * struct drm_event_vblank. If set to 1, the kernel will report timestamps with
+ * ``CLOCK_MONOTONIC``. See ``clock_gettime(2)`` for the definition of these
+ * clocks.
+ *
+ * Starting from kernel version 2.6.39, the default value for this capability
+ * is 1. Starting kernel version 4.15, this capability is always set to 1.
+ */
+#define DRM_CAP_TIMESTAMP_MONOTONIC	0x6
+/**
+ * DRM_CAP_ASYNC_PAGE_FLIP
+ *
+ * If set to 1, the driver supports &DRM_MODE_PAGE_FLIP_ASYNC.
+ */
+#define DRM_CAP_ASYNC_PAGE_FLIP		0x7
+/**
+ * DRM_CAP_CURSOR_WIDTH
+ *
+ * The ``CURSOR_WIDTH`` and ``CURSOR_HEIGHT`` capabilities return a valid
+ * width x height combination for the hardware cursor. The intention is that a
+ * hardware agnostic userspace can query a cursor plane size to use.
+ *
+ * Note that the cross-driver contract is to merely return a valid size;
+ * drivers are free to attach another meaning on top, eg. i915 returns the
+ * maximum plane size.
+ */
+#define DRM_CAP_CURSOR_WIDTH		0x8
+/**
+ * DRM_CAP_CURSOR_HEIGHT
+ *
+ * See &DRM_CAP_CURSOR_WIDTH.
+ */
+#define DRM_CAP_CURSOR_HEIGHT		0x9
+/**
+ * DRM_CAP_ADDFB2_MODIFIERS
+ *
+ * If set to 1, the driver supports supplying modifiers in the
+ * &DRM_IOCTL_MODE_ADDFB2 ioctl.
+ */
+#define DRM_CAP_ADDFB2_MODIFIERS	0x10
+/**
+ * DRM_CAP_PAGE_FLIP_TARGET
+ *
+ * If set to 1, the driver supports the &DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE and
+ * &DRM_MODE_PAGE_FLIP_TARGET_RELATIVE flags in
+ * &drm_mode_crtc_page_flip_target.flags for the &DRM_IOCTL_MODE_PAGE_FLIP
+ * ioctl.
+ */
+#define DRM_CAP_PAGE_FLIP_TARGET	0x11
+/**
+ * DRM_CAP_CRTC_IN_VBLANK_EVENT
+ *
+ * If set to 1, the kernel supports reporting the CRTC ID in
+ * &drm_event_vblank.crtc_id for the &DRM_EVENT_VBLANK and
+ * &DRM_EVENT_FLIP_COMPLETE events.
+ *
+ * Starting kernel version 4.12, this capability is always set to 1.
+ */
+#define DRM_CAP_CRTC_IN_VBLANK_EVENT	0x12
+/**
+ * DRM_CAP_SYNCOBJ
+ *
+ * If set to 1, the driver supports sync objects. See :ref:`drm_sync_objects`.
+ */
+#define DRM_CAP_SYNCOBJ		0x13
+/**
+ * DRM_CAP_SYNCOBJ_TIMELINE
+ *
+ * If set to 1, the driver supports timeline operations on sync objects. See
+ * :ref:`drm_sync_objects`.
+ */
+#define DRM_CAP_SYNCOBJ_TIMELINE	0x14
+
+/* DRM_IOCTL_GET_CAP ioctl argument type */
+struct drm_get_cap {
+	__u64 capability;
+	__u64 value;
+};
+
+/**
+ * DRM_CLIENT_CAP_STEREO_3D
+ *
+ * If set to 1, the DRM core will expose the stereo 3D capabilities of the
+ * monitor by advertising the supported 3D layouts in the flags of struct
+ * drm_mode_modeinfo. See ``DRM_MODE_FLAG_3D_*``.
+ *
+ * This capability is always supported for all drivers starting from kernel
+ * version 3.13.
+ */
+#define DRM_CLIENT_CAP_STEREO_3D	1
+
+/**
+ * DRM_CLIENT_CAP_UNIVERSAL_PLANES
+ *
+ * If set to 1, the DRM core will expose all planes (overlay, primary, and
+ * cursor) to userspace.
+ *
+ * This capability has been introduced in kernel version 3.15. Starting from
+ * kernel version 3.17, this capability is always supported for all drivers.
+ */
+#define DRM_CLIENT_CAP_UNIVERSAL_PLANES  2
+
+/**
+ * DRM_CLIENT_CAP_ATOMIC
+ *
+ * If set to 1, the DRM core will expose atomic properties to userspace. This
+ * implicitly enables &DRM_CLIENT_CAP_UNIVERSAL_PLANES and
+ * &DRM_CLIENT_CAP_ASPECT_RATIO.
+ *
+ * If the driver doesn't support atomic mode-setting, enabling this capability
+ * will fail with -EOPNOTSUPP.
+ *
+ * This capability has been introduced in kernel version 4.0. Starting from
+ * kernel version 4.2, this capability is always supported for atomic-capable
+ * drivers.
+ */
+#define DRM_CLIENT_CAP_ATOMIC	3
+
+/**
+ * DRM_CLIENT_CAP_ASPECT_RATIO
+ *
+ * If set to 1, the DRM core will provide aspect ratio information in modes.
+ * See ``DRM_MODE_FLAG_PIC_AR_*``.
+ *
+ * This capability is always supported for all drivers starting from kernel
+ * version 4.18.
+ */
+#define DRM_CLIENT_CAP_ASPECT_RATIO    4
+
+/**
+ * DRM_CLIENT_CAP_WRITEBACK_CONNECTORS
+ *
+ * If set to 1, the DRM core will expose special connectors to be used for
+ * writing back to memory the scene setup in the commit. The client must enable
+ * &DRM_CLIENT_CAP_ATOMIC first.
+ *
+ * This capability is always supported for atomic-capable drivers starting from
+ * kernel version 4.19.
+ */
+#define DRM_CLIENT_CAP_WRITEBACK_CONNECTORS	5
+
+/* DRM_IOCTL_SET_CLIENT_CAP ioctl argument type */
+struct drm_set_client_cap {
+	__u64 capability;
+	__u64 value;
+};
+
+#define DRM_RDWR O_RDWR
+#define DRM_CLOEXEC O_CLOEXEC
+struct drm_prime_handle {
+	__u32 handle;
+
+	/** Flags.. only applicable for handle->fd */
+	__u32 flags;
+
+	/** Returned dmabuf file descriptor */
+	__s32 fd;
+};
+
+struct drm_syncobj_create {
+	__u32 handle;
+#define DRM_SYNCOBJ_CREATE_SIGNALED (1 << 0)
+	__u32 flags;
+};
+
+struct drm_syncobj_destroy {
+	__u32 handle;
+	__u32 pad;
+};
+
+#define DRM_SYNCOBJ_FD_TO_HANDLE_FLAGS_IMPORT_SYNC_FILE (1 << 0)
+#define DRM_SYNCOBJ_HANDLE_TO_FD_FLAGS_EXPORT_SYNC_FILE (1 << 0)
+struct drm_syncobj_handle {
+	__u32 handle;
+	__u32 flags;
+
+	__s32 fd;
+	__u32 pad;
+};
+
+struct drm_syncobj_transfer {
+	__u32 src_handle;
+	__u32 dst_handle;
+	__u64 src_point;
+	__u64 dst_point;
+	__u32 flags;
+	__u32 pad;
+};
+
+#define DRM_SYNCOBJ_WAIT_FLAGS_WAIT_ALL (1 << 0)
+#define DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT (1 << 1)
+#define DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE (1 << 2) /* wait for time point to become available */
+struct drm_syncobj_wait {
+	__u64 handles;
+	/* absolute timeout */
+	__s64 timeout_nsec;
+	__u32 count_handles;
+	__u32 flags;
+	__u32 first_signaled; /* only valid when not waiting all */
+	__u32 pad;
+};
+
+struct drm_syncobj_timeline_wait {
+	__u64 handles;
+	/* wait on specific timeline point for every handles*/
+	__u64 points;
+	/* absolute timeout */
+	__s64 timeout_nsec;
+	__u32 count_handles;
+	__u32 flags;
+	__u32 first_signaled; /* only valid when not waiting all */
+	__u32 pad;
+};
+
+/**
+ * struct drm_syncobj_eventfd
+ * @handle: syncobj handle.
+ * @flags: Zero to wait for the point to be signalled, or
+ *         &DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE to wait for a fence to be
+ *         available for the point.
+ * @point: syncobj timeline point (set to zero for binary syncobjs).
+ * @fd: Existing eventfd to sent events to.
+ * @pad: Must be zero.
+ *
+ * Register an eventfd to be signalled by a syncobj. The eventfd counter will
+ * be incremented by one.
+ */
+struct drm_syncobj_eventfd {
+	__u32 handle;
+	__u32 flags;
+	__u64 point;
+	__s32 fd;
+	__u32 pad;
+};
+
+
+struct drm_syncobj_array {
+	__u64 handles;
+	__u32 count_handles;
+	__u32 pad;
+};
+
+#define DRM_SYNCOBJ_QUERY_FLAGS_LAST_SUBMITTED (1 << 0) /* last available point on timeline syncobj */
+struct drm_syncobj_timeline_array {
+	__u64 handles;
+	__u64 points;
+	__u32 count_handles;
+	__u32 flags;
+};
+
+
+/* Query current scanout sequence number */
+struct drm_crtc_get_sequence {
+	__u32 crtc_id;		/* requested crtc_id */
+	__u32 active;		/* return: crtc output is active */
+	__u64 sequence;		/* return: most recent vblank sequence */
+	__s64 sequence_ns;	/* return: most recent time of first pixel out */
+};
+
+/* Queue event to be delivered at specified sequence. Time stamp marks
+ * when the first pixel of the refresh cycle leaves the display engine
+ * for the display
+ */
+#define DRM_CRTC_SEQUENCE_RELATIVE		0x00000001	/* sequence is relative to current */
+#define DRM_CRTC_SEQUENCE_NEXT_ON_MISS		0x00000002	/* Use next sequence if we've missed */
+
+struct drm_crtc_queue_sequence {
+	__u32 crtc_id;
+	__u32 flags;
+	__u64 sequence;		/* on input, target sequence. on output, actual sequence */
+	__u64 user_data;	/* user data passed to event */
+};
+
+#if defined(__cplusplus)
+}
+#endif
+
+#include "drm_mode.h"
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+#define DRM_IOCTL_BASE			'd'
+#define DRM_IO(nr)			_IO(DRM_IOCTL_BASE,nr)
+#define DRM_IOR(nr,type)		_IOR(DRM_IOCTL_BASE,nr,type)
+#define DRM_IOW(nr,type)		_IOW(DRM_IOCTL_BASE,nr,type)
+#define DRM_IOWR(nr,type)		_IOWR(DRM_IOCTL_BASE,nr,type)
+
+#define DRM_IOCTL_VERSION		DRM_IOWR(0x00, struct drm_version)
+#define DRM_IOCTL_GET_UNIQUE		DRM_IOWR(0x01, struct drm_unique)
+#define DRM_IOCTL_GET_MAGIC		DRM_IOR( 0x02, struct drm_auth)
+#define DRM_IOCTL_IRQ_BUSID		DRM_IOWR(0x03, struct drm_irq_busid)
+#define DRM_IOCTL_GET_MAP               DRM_IOWR(0x04, struct drm_map)
+#define DRM_IOCTL_GET_CLIENT            DRM_IOWR(0x05, struct drm_client)
+#define DRM_IOCTL_GET_STATS             DRM_IOR( 0x06, struct drm_stats)
+#define DRM_IOCTL_SET_VERSION		DRM_IOWR(0x07, struct drm_set_version)
+#define DRM_IOCTL_MODESET_CTL           DRM_IOW(0x08, struct drm_modeset_ctl)
+/**
+ * DRM_IOCTL_GEM_CLOSE - Close a GEM handle.
+ *
+ * GEM handles are not reference-counted by the kernel. User-space is
+ * responsible for managing their lifetime. For example, if user-space imports
+ * the same memory object twice on the same DRM file description, the same GEM
+ * handle is returned by both imports, and user-space needs to ensure
+ * &DRM_IOCTL_GEM_CLOSE is performed once only. The same situation can happen
+ * when a memory object is allocated, then exported and imported again on the
+ * same DRM file description. The &DRM_IOCTL_MODE_GETFB2 IOCTL is an exception
+ * and always returns fresh new GEM handles even if an existing GEM handle
+ * already refers to the same memory object before the IOCTL is performed.
+ */
+#define DRM_IOCTL_GEM_CLOSE		DRM_IOW (0x09, struct drm_gem_close)
+#define DRM_IOCTL_GEM_FLINK		DRM_IOWR(0x0a, struct drm_gem_flink)
+#define DRM_IOCTL_GEM_OPEN		DRM_IOWR(0x0b, struct drm_gem_open)
+#define DRM_IOCTL_GET_CAP		DRM_IOWR(0x0c, struct drm_get_cap)
+#define DRM_IOCTL_SET_CLIENT_CAP	DRM_IOW( 0x0d, struct drm_set_client_cap)
+
+#define DRM_IOCTL_SET_UNIQUE		DRM_IOW( 0x10, struct drm_unique)
+#define DRM_IOCTL_AUTH_MAGIC		DRM_IOW( 0x11, struct drm_auth)
+#define DRM_IOCTL_BLOCK			DRM_IOWR(0x12, struct drm_block)
+#define DRM_IOCTL_UNBLOCK		DRM_IOWR(0x13, struct drm_block)
+#define DRM_IOCTL_CONTROL		DRM_IOW( 0x14, struct drm_control)
+#define DRM_IOCTL_ADD_MAP		DRM_IOWR(0x15, struct drm_map)
+#define DRM_IOCTL_ADD_BUFS		DRM_IOWR(0x16, struct drm_buf_desc)
+#define DRM_IOCTL_MARK_BUFS		DRM_IOW( 0x17, struct drm_buf_desc)
+#define DRM_IOCTL_INFO_BUFS		DRM_IOWR(0x18, struct drm_buf_info)
+#define DRM_IOCTL_MAP_BUFS		DRM_IOWR(0x19, struct drm_buf_map)
+#define DRM_IOCTL_FREE_BUFS		DRM_IOW( 0x1a, struct drm_buf_free)
+
+#define DRM_IOCTL_RM_MAP		DRM_IOW( 0x1b, struct drm_map)
+
+#define DRM_IOCTL_SET_SAREA_CTX		DRM_IOW( 0x1c, struct drm_ctx_priv_map)
+#define DRM_IOCTL_GET_SAREA_CTX 	DRM_IOWR(0x1d, struct drm_ctx_priv_map)
+
+#define DRM_IOCTL_SET_MASTER            DRM_IO(0x1e)
+#define DRM_IOCTL_DROP_MASTER           DRM_IO(0x1f)
+
+#define DRM_IOCTL_ADD_CTX		DRM_IOWR(0x20, struct drm_ctx)
+#define DRM_IOCTL_RM_CTX		DRM_IOWR(0x21, struct drm_ctx)
+#define DRM_IOCTL_MOD_CTX		DRM_IOW( 0x22, struct drm_ctx)
+#define DRM_IOCTL_GET_CTX		DRM_IOWR(0x23, struct drm_ctx)
+#define DRM_IOCTL_SWITCH_CTX		DRM_IOW( 0x24, struct drm_ctx)
+#define DRM_IOCTL_NEW_CTX		DRM_IOW( 0x25, struct drm_ctx)
+#define DRM_IOCTL_RES_CTX		DRM_IOWR(0x26, struct drm_ctx_res)
+#define DRM_IOCTL_ADD_DRAW		DRM_IOWR(0x27, struct drm_draw)
+#define DRM_IOCTL_RM_DRAW		DRM_IOWR(0x28, struct drm_draw)
+#define DRM_IOCTL_DMA			DRM_IOWR(0x29, struct drm_dma)
+#define DRM_IOCTL_LOCK			DRM_IOW( 0x2a, struct drm_lock)
+#define DRM_IOCTL_UNLOCK		DRM_IOW( 0x2b, struct drm_lock)
+#define DRM_IOCTL_FINISH		DRM_IOW( 0x2c, struct drm_lock)
+
+/**
+ * DRM_IOCTL_PRIME_HANDLE_TO_FD - Convert a GEM handle to a DMA-BUF FD.
+ *
+ * User-space sets &drm_prime_handle.handle with the GEM handle to export and
+ * &drm_prime_handle.flags, and gets back a DMA-BUF file descriptor in
+ * &drm_prime_handle.fd.
+ *
+ * The export can fail for any driver-specific reason, e.g. because export is
+ * not supported for this specific GEM handle (but might be for others).
+ *
+ * Support for exporting DMA-BUFs is advertised via &DRM_PRIME_CAP_EXPORT.
+ */
+#define DRM_IOCTL_PRIME_HANDLE_TO_FD    DRM_IOWR(0x2d, struct drm_prime_handle)
+/**
+ * DRM_IOCTL_PRIME_FD_TO_HANDLE - Convert a DMA-BUF FD to a GEM handle.
+ *
+ * User-space sets &drm_prime_handle.fd with a DMA-BUF file descriptor to
+ * import, and gets back a GEM handle in &drm_prime_handle.handle.
+ * &drm_prime_handle.flags is unused.
+ *
+ * If an existing GEM handle refers to the memory object backing the DMA-BUF,
+ * that GEM handle is returned. Therefore user-space which needs to handle
+ * arbitrary DMA-BUFs must have a user-space lookup data structure to manually
+ * reference-count duplicated GEM handles. For more information see
+ * &DRM_IOCTL_GEM_CLOSE.
+ *
+ * The import can fail for any driver-specific reason, e.g. because import is
+ * only supported for DMA-BUFs allocated on this DRM device.
+ *
+ * Support for importing DMA-BUFs is advertised via &DRM_PRIME_CAP_IMPORT.
+ */
+#define DRM_IOCTL_PRIME_FD_TO_HANDLE    DRM_IOWR(0x2e, struct drm_prime_handle)
+
+#define DRM_IOCTL_AGP_ACQUIRE		DRM_IO(  0x30)
+#define DRM_IOCTL_AGP_RELEASE		DRM_IO(  0x31)
+#define DRM_IOCTL_AGP_ENABLE		DRM_IOW( 0x32, struct drm_agp_mode)
+#define DRM_IOCTL_AGP_INFO		DRM_IOR( 0x33, struct drm_agp_info)
+#define DRM_IOCTL_AGP_ALLOC		DRM_IOWR(0x34, struct drm_agp_buffer)
+#define DRM_IOCTL_AGP_FREE		DRM_IOW( 0x35, struct drm_agp_buffer)
+#define DRM_IOCTL_AGP_BIND		DRM_IOW( 0x36, struct drm_agp_binding)
+#define DRM_IOCTL_AGP_UNBIND		DRM_IOW( 0x37, struct drm_agp_binding)
+
+#define DRM_IOCTL_SG_ALLOC		DRM_IOWR(0x38, struct drm_scatter_gather)
+#define DRM_IOCTL_SG_FREE		DRM_IOW( 0x39, struct drm_scatter_gather)
+
+#define DRM_IOCTL_WAIT_VBLANK		DRM_IOWR(0x3a, union drm_wait_vblank)
+
+#define DRM_IOCTL_CRTC_GET_SEQUENCE	DRM_IOWR(0x3b, struct drm_crtc_get_sequence)
+#define DRM_IOCTL_CRTC_QUEUE_SEQUENCE	DRM_IOWR(0x3c, struct drm_crtc_queue_sequence)
+
+#define DRM_IOCTL_UPDATE_DRAW		DRM_IOW(0x3f, struct drm_update_draw)
+
+#define DRM_IOCTL_MODE_GETRESOURCES	DRM_IOWR(0xA0, struct drm_mode_card_res)
+#define DRM_IOCTL_MODE_GETCRTC		DRM_IOWR(0xA1, struct drm_mode_crtc)
+#define DRM_IOCTL_MODE_SETCRTC		DRM_IOWR(0xA2, struct drm_mode_crtc)
+#define DRM_IOCTL_MODE_CURSOR		DRM_IOWR(0xA3, struct drm_mode_cursor)
+#define DRM_IOCTL_MODE_GETGAMMA		DRM_IOWR(0xA4, struct drm_mode_crtc_lut)
+#define DRM_IOCTL_MODE_SETGAMMA		DRM_IOWR(0xA5, struct drm_mode_crtc_lut)
+#define DRM_IOCTL_MODE_GETENCODER	DRM_IOWR(0xA6, struct drm_mode_get_encoder)
+#define DRM_IOCTL_MODE_GETCONNECTOR	DRM_IOWR(0xA7, struct drm_mode_get_connector)
+#define DRM_IOCTL_MODE_ATTACHMODE	DRM_IOWR(0xA8, struct drm_mode_mode_cmd) /* deprecated (never worked) */
+#define DRM_IOCTL_MODE_DETACHMODE	DRM_IOWR(0xA9, struct drm_mode_mode_cmd) /* deprecated (never worked) */
+
+#define DRM_IOCTL_MODE_GETPROPERTY	DRM_IOWR(0xAA, struct drm_mode_get_property)
+#define DRM_IOCTL_MODE_SETPROPERTY	DRM_IOWR(0xAB, struct drm_mode_connector_set_property)
+#define DRM_IOCTL_MODE_GETPROPBLOB	DRM_IOWR(0xAC, struct drm_mode_get_blob)
+#define DRM_IOCTL_MODE_GETFB		DRM_IOWR(0xAD, struct drm_mode_fb_cmd)
+#define DRM_IOCTL_MODE_ADDFB		DRM_IOWR(0xAE, struct drm_mode_fb_cmd)
+/**
+ * DRM_IOCTL_MODE_RMFB - Remove a framebuffer.
+ *
+ * This removes a framebuffer previously added via ADDFB/ADDFB2. The IOCTL
+ * argument is a framebuffer object ID.
+ *
+ * Warning: removing a framebuffer currently in-use on an enabled plane will
+ * disable that plane. The CRTC the plane is linked to may also be disabled
+ * (depending on driver capabilities).
+ */
+#define DRM_IOCTL_MODE_RMFB		DRM_IOWR(0xAF, unsigned int)
+#define DRM_IOCTL_MODE_PAGE_FLIP	DRM_IOWR(0xB0, struct drm_mode_crtc_page_flip)
+#define DRM_IOCTL_MODE_DIRTYFB		DRM_IOWR(0xB1, struct drm_mode_fb_dirty_cmd)
+
+#define DRM_IOCTL_MODE_CREATE_DUMB DRM_IOWR(0xB2, struct drm_mode_create_dumb)
+#define DRM_IOCTL_MODE_MAP_DUMB    DRM_IOWR(0xB3, struct drm_mode_map_dumb)
+#define DRM_IOCTL_MODE_DESTROY_DUMB    DRM_IOWR(0xB4, struct drm_mode_destroy_dumb)
+#define DRM_IOCTL_MODE_GETPLANERESOURCES DRM_IOWR(0xB5, struct drm_mode_get_plane_res)
+#define DRM_IOCTL_MODE_GETPLANE	DRM_IOWR(0xB6, struct drm_mode_get_plane)
+#define DRM_IOCTL_MODE_SETPLANE	DRM_IOWR(0xB7, struct drm_mode_set_plane)
+#define DRM_IOCTL_MODE_ADDFB2		DRM_IOWR(0xB8, struct drm_mode_fb_cmd2)
+#define DRM_IOCTL_MODE_OBJ_GETPROPERTIES	DRM_IOWR(0xB9, struct drm_mode_obj_get_properties)
+#define DRM_IOCTL_MODE_OBJ_SETPROPERTY	DRM_IOWR(0xBA, struct drm_mode_obj_set_property)
+#define DRM_IOCTL_MODE_CURSOR2		DRM_IOWR(0xBB, struct drm_mode_cursor2)
+#define DRM_IOCTL_MODE_ATOMIC		DRM_IOWR(0xBC, struct drm_mode_atomic)
+#define DRM_IOCTL_MODE_CREATEPROPBLOB	DRM_IOWR(0xBD, struct drm_mode_create_blob)
+#define DRM_IOCTL_MODE_DESTROYPROPBLOB	DRM_IOWR(0xBE, struct drm_mode_destroy_blob)
+
+#define DRM_IOCTL_SYNCOBJ_CREATE	DRM_IOWR(0xBF, struct drm_syncobj_create)
+#define DRM_IOCTL_SYNCOBJ_DESTROY	DRM_IOWR(0xC0, struct drm_syncobj_destroy)
+#define DRM_IOCTL_SYNCOBJ_HANDLE_TO_FD	DRM_IOWR(0xC1, struct drm_syncobj_handle)
+#define DRM_IOCTL_SYNCOBJ_FD_TO_HANDLE	DRM_IOWR(0xC2, struct drm_syncobj_handle)
+#define DRM_IOCTL_SYNCOBJ_WAIT		DRM_IOWR(0xC3, struct drm_syncobj_wait)
+#define DRM_IOCTL_SYNCOBJ_RESET		DRM_IOWR(0xC4, struct drm_syncobj_array)
+#define DRM_IOCTL_SYNCOBJ_SIGNAL	DRM_IOWR(0xC5, struct drm_syncobj_array)
+
+#define DRM_IOCTL_MODE_CREATE_LEASE	DRM_IOWR(0xC6, struct drm_mode_create_lease)
+#define DRM_IOCTL_MODE_LIST_LESSEES	DRM_IOWR(0xC7, struct drm_mode_list_lessees)
+#define DRM_IOCTL_MODE_GET_LEASE	DRM_IOWR(0xC8, struct drm_mode_get_lease)
+#define DRM_IOCTL_MODE_REVOKE_LEASE	DRM_IOWR(0xC9, struct drm_mode_revoke_lease)
+
+#define DRM_IOCTL_SYNCOBJ_TIMELINE_WAIT	DRM_IOWR(0xCA, struct drm_syncobj_timeline_wait)
+#define DRM_IOCTL_SYNCOBJ_QUERY		DRM_IOWR(0xCB, struct drm_syncobj_timeline_array)
+#define DRM_IOCTL_SYNCOBJ_TRANSFER	DRM_IOWR(0xCC, struct drm_syncobj_transfer)
+#define DRM_IOCTL_SYNCOBJ_TIMELINE_SIGNAL	DRM_IOWR(0xCD, struct drm_syncobj_timeline_array)
+
+/**
+ * DRM_IOCTL_MODE_GETFB2 - Get framebuffer metadata.
+ *
+ * This queries metadata about a framebuffer. User-space fills
+ * &drm_mode_fb_cmd2.fb_id as the input, and the kernels fills the rest of the
+ * struct as the output.
+ *
+ * If the client is DRM master or has &CAP_SYS_ADMIN, &drm_mode_fb_cmd2.handles
+ * will be filled with GEM buffer handles. Fresh new GEM handles are always
+ * returned, even if another GEM handle referring to the same memory object
+ * already exists on the DRM file description. The caller is responsible for
+ * removing the new handles, e.g. via the &DRM_IOCTL_GEM_CLOSE IOCTL. The same
+ * new handle will be returned for multiple planes in case they use the same
+ * memory object. Planes are valid until one has a zero handle -- this can be
+ * used to compute the number of planes.
+ *
+ * Otherwise, &drm_mode_fb_cmd2.handles will be zeroed and planes are valid
+ * until one has a zero &drm_mode_fb_cmd2.pitches.
+ *
+ * If the framebuffer has a format modifier, &DRM_MODE_FB_MODIFIERS will be set
+ * in &drm_mode_fb_cmd2.flags and &drm_mode_fb_cmd2.modifier will contain the
+ * modifier. Otherwise, user-space must ignore &drm_mode_fb_cmd2.modifier.
+ *
+ * To obtain DMA-BUF FDs for each plane without leaking GEM handles, user-space
+ * can export each handle via &DRM_IOCTL_PRIME_HANDLE_TO_FD, then immediately
+ * close each unique handle via &DRM_IOCTL_GEM_CLOSE, making sure to not
+ * double-close handles which are specified multiple times in the array.
+ */
+#define DRM_IOCTL_MODE_GETFB2		DRM_IOWR(0xCE, struct drm_mode_fb_cmd2)
+
+#define DRM_IOCTL_SYNCOBJ_EVENTFD	DRM_IOWR(0xCF, struct drm_syncobj_eventfd)
+
+/*
+ * Device specific ioctls should only be in their respective headers
+ * The device specific ioctl range is from 0x40 to 0x9f.
+ * Generic IOCTLS restart at 0xA0.
+ *
+ * \sa drmCommandNone(), drmCommandRead(), drmCommandWrite(), and
+ * drmCommandReadWrite().
+ */
+#define DRM_COMMAND_BASE                0x40
+#define DRM_COMMAND_END			0xA0
+
+/**
+ * struct drm_event - Header for DRM events
+ * @type: event type.
+ * @length: total number of payload bytes (including header).
+ *
+ * This struct is a header for events written back to user-space on the DRM FD.
+ * A read on the DRM FD will always only return complete events: e.g. if the
+ * read buffer is 100 bytes large and there are two 64 byte events pending,
+ * only one will be returned.
+ *
+ * Event types 0 - 0x7fffffff are generic DRM events, 0x80000000 and
+ * up are chipset specific. Generic DRM events include &DRM_EVENT_VBLANK,
+ * &DRM_EVENT_FLIP_COMPLETE and &DRM_EVENT_CRTC_SEQUENCE.
+ */
+struct drm_event {
+	__u32 type;
+	__u32 length;
+};
+
+/**
+ * DRM_EVENT_VBLANK - vertical blanking event
+ *
+ * This event is sent in response to &DRM_IOCTL_WAIT_VBLANK with the
+ * &_DRM_VBLANK_EVENT flag set.
+ *
+ * The event payload is a struct drm_event_vblank.
+ */
+#define DRM_EVENT_VBLANK 0x01
+/**
+ * DRM_EVENT_FLIP_COMPLETE - page-flip completion event
+ *
+ * This event is sent in response to an atomic commit or legacy page-flip with
+ * the &DRM_MODE_PAGE_FLIP_EVENT flag set.
+ *
+ * The event payload is a struct drm_event_vblank.
+ */
+#define DRM_EVENT_FLIP_COMPLETE 0x02
+/**
+ * DRM_EVENT_CRTC_SEQUENCE - CRTC sequence event
+ *
+ * This event is sent in response to &DRM_IOCTL_CRTC_QUEUE_SEQUENCE.
+ *
+ * The event payload is a struct drm_event_crtc_sequence.
+ */
+#define DRM_EVENT_CRTC_SEQUENCE	0x03
+
+struct drm_event_vblank {
+	struct drm_event base;
+	__u64 user_data;
+	__u32 tv_sec;
+	__u32 tv_usec;
+	__u32 sequence;
+	__u32 crtc_id; /* 0 on older kernels that do not support this */
+};
+
+/* Event delivered at sequence. Time stamp marks when the first pixel
+ * of the refresh cycle leaves the display engine for the display
+ */
+struct drm_event_crtc_sequence {
+	struct drm_event	base;
+	__u64			user_data;
+	__s64			time_ns;
+	__u64			sequence;
+};
+
+/* typedef area */
+typedef struct drm_clip_rect drm_clip_rect_t;
+typedef struct drm_drawable_info drm_drawable_info_t;
+typedef struct drm_tex_region drm_tex_region_t;
+typedef struct drm_hw_lock drm_hw_lock_t;
+typedef struct drm_version drm_version_t;
+typedef struct drm_unique drm_unique_t;
+typedef struct drm_list drm_list_t;
+typedef struct drm_block drm_block_t;
+typedef struct drm_control drm_control_t;
+typedef enum drm_map_type drm_map_type_t;
+typedef enum drm_map_flags drm_map_flags_t;
+typedef struct drm_ctx_priv_map drm_ctx_priv_map_t;
+typedef struct drm_map drm_map_t;
+typedef struct drm_client drm_client_t;
+typedef enum drm_stat_type drm_stat_type_t;
+typedef struct drm_stats drm_stats_t;
+typedef enum drm_lock_flags drm_lock_flags_t;
+typedef struct drm_lock drm_lock_t;
+typedef enum drm_dma_flags drm_dma_flags_t;
+typedef struct drm_buf_desc drm_buf_desc_t;
+typedef struct drm_buf_info drm_buf_info_t;
+typedef struct drm_buf_free drm_buf_free_t;
+typedef struct drm_buf_pub drm_buf_pub_t;
+typedef struct drm_buf_map drm_buf_map_t;
+typedef struct drm_dma drm_dma_t;
+typedef union drm_wait_vblank drm_wait_vblank_t;
+typedef struct drm_agp_mode drm_agp_mode_t;
+typedef enum drm_ctx_flags drm_ctx_flags_t;
+typedef struct drm_ctx drm_ctx_t;
+typedef struct drm_ctx_res drm_ctx_res_t;
+typedef struct drm_draw drm_draw_t;
+typedef struct drm_update_draw drm_update_draw_t;
+typedef struct drm_auth drm_auth_t;
+typedef struct drm_irq_busid drm_irq_busid_t;
+typedef enum drm_vblank_seq_type drm_vblank_seq_type_t;
+
+typedef struct drm_agp_buffer drm_agp_buffer_t;
+typedef struct drm_agp_binding drm_agp_binding_t;
+typedef struct drm_agp_info drm_agp_info_t;
+typedef struct drm_scatter_gather drm_scatter_gather_t;
+typedef struct drm_set_version drm_set_version_t;
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif

+ 1318 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/drm_mode.h

@@ -0,0 +1,1318 @@
+/*
+ * Copyright (c) 2007 Dave Airlie <airlied@linux.ie>
+ * Copyright (c) 2007 Jakob Bornecrantz <wallbraker@gmail.com>
+ * Copyright (c) 2008 Red Hat Inc.
+ * Copyright (c) 2007-2008 Tungsten Graphics, Inc., Cedar Park, TX., USA
+ * Copyright (c) 2007-2008 Intel Corporation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ */
+
+#ifndef _DRM_MODE_H
+#define _DRM_MODE_H
+
+#include "drm.h"
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+/**
+ * DOC: overview
+ *
+ * DRM exposes many UAPI and structure definition to have a consistent
+ * and standardized interface with user.
+ * Userspace can refer to these structure definitions and UAPI formats
+ * to communicate to driver
+ */
+
+#define DRM_CONNECTOR_NAME_LEN	32
+#define DRM_DISPLAY_MODE_LEN	32
+#define DRM_PROP_NAME_LEN	32
+
+#define DRM_MODE_TYPE_BUILTIN	(1<<0) /* deprecated */
+#define DRM_MODE_TYPE_CLOCK_C	((1<<1) | DRM_MODE_TYPE_BUILTIN) /* deprecated */
+#define DRM_MODE_TYPE_CRTC_C	((1<<2) | DRM_MODE_TYPE_BUILTIN) /* deprecated */
+#define DRM_MODE_TYPE_PREFERRED	(1<<3)
+#define DRM_MODE_TYPE_DEFAULT	(1<<4) /* deprecated */
+#define DRM_MODE_TYPE_USERDEF	(1<<5)
+#define DRM_MODE_TYPE_DRIVER	(1<<6)
+
+#define DRM_MODE_TYPE_ALL	(DRM_MODE_TYPE_PREFERRED |	\
+				 DRM_MODE_TYPE_USERDEF |	\
+				 DRM_MODE_TYPE_DRIVER)
+
+/* Video mode flags */
+/* bit compatible with the xrandr RR_ definitions (bits 0-13)
+ *
+ * ABI warning: Existing userspace really expects
+ * the mode flags to match the xrandr definitions. Any
+ * changes that don't match the xrandr definitions will
+ * likely need a new client cap or some other mechanism
+ * to avoid breaking existing userspace. This includes
+ * allocating new flags in the previously unused bits!
+ */
+#define DRM_MODE_FLAG_PHSYNC			(1<<0)
+#define DRM_MODE_FLAG_NHSYNC			(1<<1)
+#define DRM_MODE_FLAG_PVSYNC			(1<<2)
+#define DRM_MODE_FLAG_NVSYNC			(1<<3)
+#define DRM_MODE_FLAG_INTERLACE			(1<<4)
+#define DRM_MODE_FLAG_DBLSCAN			(1<<5)
+#define DRM_MODE_FLAG_CSYNC			(1<<6)
+#define DRM_MODE_FLAG_PCSYNC			(1<<7)
+#define DRM_MODE_FLAG_NCSYNC			(1<<8)
+#define DRM_MODE_FLAG_HSKEW			(1<<9) /* hskew provided */
+#define DRM_MODE_FLAG_BCAST			(1<<10) /* deprecated */
+#define DRM_MODE_FLAG_PIXMUX			(1<<11) /* deprecated */
+#define DRM_MODE_FLAG_DBLCLK			(1<<12)
+#define DRM_MODE_FLAG_CLKDIV2			(1<<13)
+ /*
+  * When adding a new stereo mode don't forget to adjust DRM_MODE_FLAGS_3D_MAX
+  * (define not exposed to user space).
+  */
+#define DRM_MODE_FLAG_3D_MASK			(0x1f<<14)
+#define  DRM_MODE_FLAG_3D_NONE		(0<<14)
+#define  DRM_MODE_FLAG_3D_FRAME_PACKING		(1<<14)
+#define  DRM_MODE_FLAG_3D_FIELD_ALTERNATIVE	(2<<14)
+#define  DRM_MODE_FLAG_3D_LINE_ALTERNATIVE	(3<<14)
+#define  DRM_MODE_FLAG_3D_SIDE_BY_SIDE_FULL	(4<<14)
+#define  DRM_MODE_FLAG_3D_L_DEPTH		(5<<14)
+#define  DRM_MODE_FLAG_3D_L_DEPTH_GFX_GFX_DEPTH	(6<<14)
+#define  DRM_MODE_FLAG_3D_TOP_AND_BOTTOM	(7<<14)
+#define  DRM_MODE_FLAG_3D_SIDE_BY_SIDE_HALF	(8<<14)
+
+/* Picture aspect ratio options */
+#define DRM_MODE_PICTURE_ASPECT_NONE		0
+#define DRM_MODE_PICTURE_ASPECT_4_3		1
+#define DRM_MODE_PICTURE_ASPECT_16_9		2
+#define DRM_MODE_PICTURE_ASPECT_64_27		3
+#define DRM_MODE_PICTURE_ASPECT_256_135		4
+
+/* Content type options */
+#define DRM_MODE_CONTENT_TYPE_NO_DATA		0
+#define DRM_MODE_CONTENT_TYPE_GRAPHICS		1
+#define DRM_MODE_CONTENT_TYPE_PHOTO		2
+#define DRM_MODE_CONTENT_TYPE_CINEMA		3
+#define DRM_MODE_CONTENT_TYPE_GAME		4
+
+/* Aspect ratio flag bitmask (4 bits 22:19) */
+#define DRM_MODE_FLAG_PIC_AR_MASK		(0x0F<<19)
+#define  DRM_MODE_FLAG_PIC_AR_NONE \
+			(DRM_MODE_PICTURE_ASPECT_NONE<<19)
+#define  DRM_MODE_FLAG_PIC_AR_4_3 \
+			(DRM_MODE_PICTURE_ASPECT_4_3<<19)
+#define  DRM_MODE_FLAG_PIC_AR_16_9 \
+			(DRM_MODE_PICTURE_ASPECT_16_9<<19)
+#define  DRM_MODE_FLAG_PIC_AR_64_27 \
+			(DRM_MODE_PICTURE_ASPECT_64_27<<19)
+#define  DRM_MODE_FLAG_PIC_AR_256_135 \
+			(DRM_MODE_PICTURE_ASPECT_256_135<<19)
+
+#define  DRM_MODE_FLAG_ALL	(DRM_MODE_FLAG_PHSYNC |		\
+				 DRM_MODE_FLAG_NHSYNC |		\
+				 DRM_MODE_FLAG_PVSYNC |		\
+				 DRM_MODE_FLAG_NVSYNC |		\
+				 DRM_MODE_FLAG_INTERLACE |	\
+				 DRM_MODE_FLAG_DBLSCAN |	\
+				 DRM_MODE_FLAG_CSYNC |		\
+				 DRM_MODE_FLAG_PCSYNC |		\
+				 DRM_MODE_FLAG_NCSYNC |		\
+				 DRM_MODE_FLAG_HSKEW |		\
+				 DRM_MODE_FLAG_DBLCLK |		\
+				 DRM_MODE_FLAG_CLKDIV2 |	\
+				 DRM_MODE_FLAG_3D_MASK)
+
+/* DPMS flags */
+/* bit compatible with the xorg definitions. */
+#define DRM_MODE_DPMS_ON	0
+#define DRM_MODE_DPMS_STANDBY	1
+#define DRM_MODE_DPMS_SUSPEND	2
+#define DRM_MODE_DPMS_OFF	3
+
+/* Scaling mode options */
+#define DRM_MODE_SCALE_NONE		0 /* Unmodified timing (display or
+					     software can still scale) */
+#define DRM_MODE_SCALE_FULLSCREEN	1 /* Full screen, ignore aspect */
+#define DRM_MODE_SCALE_CENTER		2 /* Centered, no scaling */
+#define DRM_MODE_SCALE_ASPECT		3 /* Full screen, preserve aspect */
+
+/* Dithering mode options */
+#define DRM_MODE_DITHERING_OFF	0
+#define DRM_MODE_DITHERING_ON	1
+#define DRM_MODE_DITHERING_AUTO 2
+
+/* Dirty info options */
+#define DRM_MODE_DIRTY_OFF      0
+#define DRM_MODE_DIRTY_ON       1
+#define DRM_MODE_DIRTY_ANNOTATE 2
+
+/* Link Status options */
+#define DRM_MODE_LINK_STATUS_GOOD	0
+#define DRM_MODE_LINK_STATUS_BAD	1
+
+/*
+ * DRM_MODE_ROTATE_<degrees>
+ *
+ * Signals that a drm plane is been rotated <degrees> degrees in counter
+ * clockwise direction.
+ *
+ * This define is provided as a convenience, looking up the property id
+ * using the name->prop id lookup is the preferred method.
+ */
+#define DRM_MODE_ROTATE_0       (1<<0)
+#define DRM_MODE_ROTATE_90      (1<<1)
+#define DRM_MODE_ROTATE_180     (1<<2)
+#define DRM_MODE_ROTATE_270     (1<<3)
+
+/*
+ * DRM_MODE_ROTATE_MASK
+ *
+ * Bitmask used to look for drm plane rotations.
+ */
+#define DRM_MODE_ROTATE_MASK (\
+		DRM_MODE_ROTATE_0  | \
+		DRM_MODE_ROTATE_90  | \
+		DRM_MODE_ROTATE_180 | \
+		DRM_MODE_ROTATE_270)
+
+/*
+ * DRM_MODE_REFLECT_<axis>
+ *
+ * Signals that the contents of a drm plane is reflected along the <axis> axis,
+ * in the same way as mirroring.
+ * See kerneldoc chapter "Plane Composition Properties" for more details.
+ *
+ * This define is provided as a convenience, looking up the property id
+ * using the name->prop id lookup is the preferred method.
+ */
+#define DRM_MODE_REFLECT_X      (1<<4)
+#define DRM_MODE_REFLECT_Y      (1<<5)
+
+/*
+ * DRM_MODE_REFLECT_MASK
+ *
+ * Bitmask used to look for drm plane reflections.
+ */
+#define DRM_MODE_REFLECT_MASK (\
+		DRM_MODE_REFLECT_X | \
+		DRM_MODE_REFLECT_Y)
+
+/* Content Protection Flags */
+#define DRM_MODE_CONTENT_PROTECTION_UNDESIRED	0
+#define DRM_MODE_CONTENT_PROTECTION_DESIRED     1
+#define DRM_MODE_CONTENT_PROTECTION_ENABLED     2
+
+/**
+ * struct drm_mode_modeinfo - Display mode information.
+ * @clock: pixel clock in kHz
+ * @hdisplay: horizontal display size
+ * @hsync_start: horizontal sync start
+ * @hsync_end: horizontal sync end
+ * @htotal: horizontal total size
+ * @hskew: horizontal skew
+ * @vdisplay: vertical display size
+ * @vsync_start: vertical sync start
+ * @vsync_end: vertical sync end
+ * @vtotal: vertical total size
+ * @vscan: vertical scan
+ * @vrefresh: approximate vertical refresh rate in Hz
+ * @flags: bitmask of misc. flags, see DRM_MODE_FLAG_* defines
+ * @type: bitmask of type flags, see DRM_MODE_TYPE_* defines
+ * @name: string describing the mode resolution
+ *
+ * This is the user-space API display mode information structure. For the
+ * kernel version see struct drm_display_mode.
+ */
+struct drm_mode_modeinfo {
+	__u32 clock;
+	__u16 hdisplay;
+	__u16 hsync_start;
+	__u16 hsync_end;
+	__u16 htotal;
+	__u16 hskew;
+	__u16 vdisplay;
+	__u16 vsync_start;
+	__u16 vsync_end;
+	__u16 vtotal;
+	__u16 vscan;
+
+	__u32 vrefresh;
+
+	__u32 flags;
+	__u32 type;
+	char name[DRM_DISPLAY_MODE_LEN];
+};
+
+struct drm_mode_card_res {
+	__u64 fb_id_ptr;
+	__u64 crtc_id_ptr;
+	__u64 connector_id_ptr;
+	__u64 encoder_id_ptr;
+	__u32 count_fbs;
+	__u32 count_crtcs;
+	__u32 count_connectors;
+	__u32 count_encoders;
+	__u32 min_width;
+	__u32 max_width;
+	__u32 min_height;
+	__u32 max_height;
+};
+
+struct drm_mode_crtc {
+	__u64 set_connectors_ptr;
+	__u32 count_connectors;
+
+	__u32 crtc_id; /**< Id */
+	__u32 fb_id; /**< Id of framebuffer */
+
+	__u32 x; /**< x Position on the framebuffer */
+	__u32 y; /**< y Position on the framebuffer */
+
+	__u32 gamma_size;
+	__u32 mode_valid;
+	struct drm_mode_modeinfo mode;
+};
+
+#define DRM_MODE_PRESENT_TOP_FIELD	(1<<0)
+#define DRM_MODE_PRESENT_BOTTOM_FIELD	(1<<1)
+
+/* Planes blend with or override other bits on the CRTC */
+struct drm_mode_set_plane {
+	__u32 plane_id;
+	__u32 crtc_id;
+	__u32 fb_id; /* fb object contains surface format type */
+	__u32 flags; /* see above flags */
+
+	/* Signed dest location allows it to be partially off screen */
+	__s32 crtc_x;
+	__s32 crtc_y;
+	__u32 crtc_w;
+	__u32 crtc_h;
+
+	/* Source values are 16.16 fixed point */
+	__u32 src_x;
+	__u32 src_y;
+	__u32 src_h;
+	__u32 src_w;
+};
+
+/**
+ * struct drm_mode_get_plane - Get plane metadata.
+ *
+ * Userspace can perform a GETPLANE ioctl to retrieve information about a
+ * plane.
+ *
+ * To retrieve the number of formats supported, set @count_format_types to zero
+ * and call the ioctl. @count_format_types will be updated with the value.
+ *
+ * To retrieve these formats, allocate an array with the memory needed to store
+ * @count_format_types formats. Point @format_type_ptr to this array and call
+ * the ioctl again (with @count_format_types still set to the value returned in
+ * the first ioctl call).
+ */
+struct drm_mode_get_plane {
+	/**
+	 * @plane_id: Object ID of the plane whose information should be
+	 * retrieved. Set by caller.
+	 */
+	__u32 plane_id;
+
+	/** @crtc_id: Object ID of the current CRTC. */
+	__u32 crtc_id;
+	/** @fb_id: Object ID of the current fb. */
+	__u32 fb_id;
+
+	/**
+	 * @possible_crtcs: Bitmask of CRTC's compatible with the plane. CRTC's
+	 * are created and they receive an index, which corresponds to their
+	 * position in the bitmask. Bit N corresponds to
+	 * :ref:`CRTC index<crtc_index>` N.
+	 */
+	__u32 possible_crtcs;
+	/** @gamma_size: Never used. */
+	__u32 gamma_size;
+
+	/** @count_format_types: Number of formats. */
+	__u32 count_format_types;
+	/**
+	 * @format_type_ptr: Pointer to ``__u32`` array of formats that are
+	 * supported by the plane. These formats do not require modifiers.
+	 */
+	__u64 format_type_ptr;
+};
+
+struct drm_mode_get_plane_res {
+	__u64 plane_id_ptr;
+	__u32 count_planes;
+};
+
+#define DRM_MODE_ENCODER_NONE	0
+#define DRM_MODE_ENCODER_DAC	1
+#define DRM_MODE_ENCODER_TMDS	2
+#define DRM_MODE_ENCODER_LVDS	3
+#define DRM_MODE_ENCODER_TVDAC	4
+#define DRM_MODE_ENCODER_VIRTUAL 5
+#define DRM_MODE_ENCODER_DSI	6
+#define DRM_MODE_ENCODER_DPMST	7
+#define DRM_MODE_ENCODER_DPI	8
+
+struct drm_mode_get_encoder {
+	__u32 encoder_id;
+	__u32 encoder_type;
+
+	__u32 crtc_id; /**< Id of crtc */
+
+	__u32 possible_crtcs;
+	__u32 possible_clones;
+};
+
+/* This is for connectors with multiple signal types. */
+/* Try to match DRM_MODE_CONNECTOR_X as closely as possible. */
+enum drm_mode_subconnector {
+	DRM_MODE_SUBCONNECTOR_Automatic   = 0,  /* DVI-I, TV     */
+	DRM_MODE_SUBCONNECTOR_Unknown     = 0,  /* DVI-I, TV, DP */
+	DRM_MODE_SUBCONNECTOR_VGA	  = 1,  /*            DP */
+	DRM_MODE_SUBCONNECTOR_DVID	  = 3,  /* DVI-I      DP */
+	DRM_MODE_SUBCONNECTOR_DVIA	  = 4,  /* DVI-I         */
+	DRM_MODE_SUBCONNECTOR_Composite   = 5,  /*        TV     */
+	DRM_MODE_SUBCONNECTOR_SVIDEO	  = 6,  /*        TV     */
+	DRM_MODE_SUBCONNECTOR_Component   = 8,  /*        TV     */
+	DRM_MODE_SUBCONNECTOR_SCART	  = 9,  /*        TV     */
+	DRM_MODE_SUBCONNECTOR_DisplayPort = 10, /*            DP */
+	DRM_MODE_SUBCONNECTOR_HDMIA       = 11, /*            DP */
+	DRM_MODE_SUBCONNECTOR_Native      = 15, /*            DP */
+	DRM_MODE_SUBCONNECTOR_Wireless    = 18, /*            DP */
+};
+
+#define DRM_MODE_CONNECTOR_Unknown	0
+#define DRM_MODE_CONNECTOR_VGA		1
+#define DRM_MODE_CONNECTOR_DVII		2
+#define DRM_MODE_CONNECTOR_DVID		3
+#define DRM_MODE_CONNECTOR_DVIA		4
+#define DRM_MODE_CONNECTOR_Composite	5
+#define DRM_MODE_CONNECTOR_SVIDEO	6
+#define DRM_MODE_CONNECTOR_LVDS		7
+#define DRM_MODE_CONNECTOR_Component	8
+#define DRM_MODE_CONNECTOR_9PinDIN	9
+#define DRM_MODE_CONNECTOR_DisplayPort	10
+#define DRM_MODE_CONNECTOR_HDMIA	11
+#define DRM_MODE_CONNECTOR_HDMIB	12
+#define DRM_MODE_CONNECTOR_TV		13
+#define DRM_MODE_CONNECTOR_eDP		14
+#define DRM_MODE_CONNECTOR_VIRTUAL      15
+#define DRM_MODE_CONNECTOR_DSI		16
+#define DRM_MODE_CONNECTOR_DPI		17
+#define DRM_MODE_CONNECTOR_WRITEBACK	18
+#define DRM_MODE_CONNECTOR_SPI		19
+#define DRM_MODE_CONNECTOR_USB		20
+
+/**
+ * struct drm_mode_get_connector - Get connector metadata.
+ *
+ * User-space can perform a GETCONNECTOR ioctl to retrieve information about a
+ * connector. User-space is expected to retrieve encoders, modes and properties
+ * by performing this ioctl at least twice: the first time to retrieve the
+ * number of elements, the second time to retrieve the elements themselves.
+ *
+ * To retrieve the number of elements, set @count_props and @count_encoders to
+ * zero, set @count_modes to 1, and set @modes_ptr to a temporary struct
+ * drm_mode_modeinfo element.
+ *
+ * To retrieve the elements, allocate arrays for @encoders_ptr, @modes_ptr,
+ * @props_ptr and @prop_values_ptr, then set @count_modes, @count_props and
+ * @count_encoders to their capacity.
+ *
+ * Performing the ioctl only twice may be racy: the number of elements may have
+ * changed with a hotplug event in-between the two ioctls. User-space is
+ * expected to retry the last ioctl until the number of elements stabilizes.
+ * The kernel won't fill any array which doesn't have the expected length.
+ *
+ * **Force-probing a connector**
+ *
+ * If the @count_modes field is set to zero and the DRM client is the current
+ * DRM master, the kernel will perform a forced probe on the connector to
+ * refresh the connector status, modes and EDID. A forced-probe can be slow,
+ * might cause flickering and the ioctl will block.
+ *
+ * User-space needs to force-probe connectors to ensure their metadata is
+ * up-to-date at startup and after receiving a hot-plug event. User-space
+ * may perform a forced-probe when the user explicitly requests it. User-space
+ * shouldn't perform a forced-probe in other situations.
+ */
+struct drm_mode_get_connector {
+	/** @encoders_ptr: Pointer to ``__u32`` array of object IDs. */
+	__u64 encoders_ptr;
+	/** @modes_ptr: Pointer to struct drm_mode_modeinfo array. */
+	__u64 modes_ptr;
+	/** @props_ptr: Pointer to ``__u32`` array of property IDs. */
+	__u64 props_ptr;
+	/** @prop_values_ptr: Pointer to ``__u64`` array of property values. */
+	__u64 prop_values_ptr;
+
+	/** @count_modes: Number of modes. */
+	__u32 count_modes;
+	/** @count_props: Number of properties. */
+	__u32 count_props;
+	/** @count_encoders: Number of encoders. */
+	__u32 count_encoders;
+
+	/** @encoder_id: Object ID of the current encoder. */
+	__u32 encoder_id;
+	/** @connector_id: Object ID of the connector. */
+	__u32 connector_id;
+	/**
+	 * @connector_type: Type of the connector.
+	 *
+	 * See DRM_MODE_CONNECTOR_* defines.
+	 */
+	__u32 connector_type;
+	/**
+	 * @connector_type_id: Type-specific connector number.
+	 *
+	 * This is not an object ID. This is a per-type connector number. Each
+	 * (type, type_id) combination is unique across all connectors of a DRM
+	 * device.
+	 *
+	 * The (type, type_id) combination is not a stable identifier: the
+	 * type_id can change depending on the driver probe order.
+	 */
+	__u32 connector_type_id;
+
+	/**
+	 * @connection: Status of the connector.
+	 *
+	 * See enum drm_connector_status.
+	 */
+	__u32 connection;
+	/** @mm_width: Width of the connected sink in millimeters. */
+	__u32 mm_width;
+	/** @mm_height: Height of the connected sink in millimeters. */
+	__u32 mm_height;
+	/**
+	 * @subpixel: Subpixel order of the connected sink.
+	 *
+	 * See enum subpixel_order.
+	 */
+	__u32 subpixel;
+
+	/** @pad: Padding, must be zero. */
+	__u32 pad;
+};
+
+#define DRM_MODE_PROP_PENDING	(1<<0) /* deprecated, do not use */
+#define DRM_MODE_PROP_RANGE	(1<<1)
+#define DRM_MODE_PROP_IMMUTABLE	(1<<2)
+#define DRM_MODE_PROP_ENUM	(1<<3) /* enumerated type with text strings */
+#define DRM_MODE_PROP_BLOB	(1<<4)
+#define DRM_MODE_PROP_BITMASK	(1<<5) /* bitmask of enumerated types */
+
+/* non-extended types: legacy bitmask, one bit per type: */
+#define DRM_MODE_PROP_LEGACY_TYPE  ( \
+		DRM_MODE_PROP_RANGE | \
+		DRM_MODE_PROP_ENUM | \
+		DRM_MODE_PROP_BLOB | \
+		DRM_MODE_PROP_BITMASK)
+
+/* extended-types: rather than continue to consume a bit per type,
+ * grab a chunk of the bits to use as integer type id.
+ */
+#define DRM_MODE_PROP_EXTENDED_TYPE	0x0000ffc0
+#define DRM_MODE_PROP_TYPE(n)		((n) << 6)
+#define DRM_MODE_PROP_OBJECT		DRM_MODE_PROP_TYPE(1)
+#define DRM_MODE_PROP_SIGNED_RANGE	DRM_MODE_PROP_TYPE(2)
+
+/* the PROP_ATOMIC flag is used to hide properties from userspace that
+ * is not aware of atomic properties.  This is mostly to work around
+ * older userspace (DDX drivers) that read/write each prop they find,
+ * witout being aware that this could be triggering a lengthy modeset.
+ */
+#define DRM_MODE_PROP_ATOMIC        0x80000000
+
+/**
+ * struct drm_mode_property_enum - Description for an enum/bitfield entry.
+ * @value: numeric value for this enum entry.
+ * @name: symbolic name for this enum entry.
+ *
+ * See struct drm_property_enum for details.
+ */
+struct drm_mode_property_enum {
+	__u64 value;
+	char name[DRM_PROP_NAME_LEN];
+};
+
+/**
+ * struct drm_mode_get_property - Get property metadata.
+ *
+ * User-space can perform a GETPROPERTY ioctl to retrieve information about a
+ * property. The same property may be attached to multiple objects, see
+ * "Modeset Base Object Abstraction".
+ *
+ * The meaning of the @values_ptr field changes depending on the property type.
+ * See &drm_property.flags for more details.
+ *
+ * The @enum_blob_ptr and @count_enum_blobs fields are only meaningful when the
+ * property has the type &DRM_MODE_PROP_ENUM or &DRM_MODE_PROP_BITMASK. For
+ * backwards compatibility, the kernel will always set @count_enum_blobs to
+ * zero when the property has the type &DRM_MODE_PROP_BLOB. User-space must
+ * ignore these two fields if the property has a different type.
+ *
+ * User-space is expected to retrieve values and enums by performing this ioctl
+ * at least twice: the first time to retrieve the number of elements, the
+ * second time to retrieve the elements themselves.
+ *
+ * To retrieve the number of elements, set @count_values and @count_enum_blobs
+ * to zero, then call the ioctl. @count_values will be updated with the number
+ * of elements. If the property has the type &DRM_MODE_PROP_ENUM or
+ * &DRM_MODE_PROP_BITMASK, @count_enum_blobs will be updated as well.
+ *
+ * To retrieve the elements themselves, allocate an array for @values_ptr and
+ * set @count_values to its capacity. If the property has the type
+ * &DRM_MODE_PROP_ENUM or &DRM_MODE_PROP_BITMASK, allocate an array for
+ * @enum_blob_ptr and set @count_enum_blobs to its capacity. Calling the ioctl
+ * again will fill the arrays.
+ */
+struct drm_mode_get_property {
+	/** @values_ptr: Pointer to a ``__u64`` array. */
+	__u64 values_ptr;
+	/** @enum_blob_ptr: Pointer to a struct drm_mode_property_enum array. */
+	__u64 enum_blob_ptr;
+
+	/**
+	 * @prop_id: Object ID of the property which should be retrieved. Set
+	 * by the caller.
+	 */
+	__u32 prop_id;
+	/**
+	 * @flags: ``DRM_MODE_PROP_*`` bitfield. See &drm_property.flags for
+	 * a definition of the flags.
+	 */
+	__u32 flags;
+	/**
+	 * @name: Symbolic property name. User-space should use this field to
+	 * recognize properties.
+	 */
+	char name[DRM_PROP_NAME_LEN];
+
+	/** @count_values: Number of elements in @values_ptr. */
+	__u32 count_values;
+	/** @count_enum_blobs: Number of elements in @enum_blob_ptr. */
+	__u32 count_enum_blobs;
+};
+
+struct drm_mode_connector_set_property {
+	__u64 value;
+	__u32 prop_id;
+	__u32 connector_id;
+};
+
+#define DRM_MODE_OBJECT_CRTC 0xcccccccc
+#define DRM_MODE_OBJECT_CONNECTOR 0xc0c0c0c0
+#define DRM_MODE_OBJECT_ENCODER 0xe0e0e0e0
+#define DRM_MODE_OBJECT_MODE 0xdededede
+#define DRM_MODE_OBJECT_PROPERTY 0xb0b0b0b0
+#define DRM_MODE_OBJECT_FB 0xfbfbfbfb
+#define DRM_MODE_OBJECT_BLOB 0xbbbbbbbb
+#define DRM_MODE_OBJECT_PLANE 0xeeeeeeee
+#define DRM_MODE_OBJECT_ANY 0
+
+struct drm_mode_obj_get_properties {
+	__u64 props_ptr;
+	__u64 prop_values_ptr;
+	__u32 count_props;
+	__u32 obj_id;
+	__u32 obj_type;
+};
+
+struct drm_mode_obj_set_property {
+	__u64 value;
+	__u32 prop_id;
+	__u32 obj_id;
+	__u32 obj_type;
+};
+
+struct drm_mode_get_blob {
+	__u32 blob_id;
+	__u32 length;
+	__u64 data;
+};
+
+struct drm_mode_fb_cmd {
+	__u32 fb_id;
+	__u32 width;
+	__u32 height;
+	__u32 pitch;
+	__u32 bpp;
+	__u32 depth;
+	/* driver specific handle */
+	__u32 handle;
+};
+
+#define DRM_MODE_FB_INTERLACED	(1<<0) /* for interlaced framebuffers */
+#define DRM_MODE_FB_MODIFIERS	(1<<1) /* enables ->modifer[] */
+
+/**
+ * struct drm_mode_fb_cmd2 - Frame-buffer metadata.
+ *
+ * This struct holds frame-buffer metadata. There are two ways to use it:
+ *
+ * - User-space can fill this struct and perform a &DRM_IOCTL_MODE_ADDFB2
+ *   ioctl to register a new frame-buffer. The new frame-buffer object ID will
+ *   be set by the kernel in @fb_id.
+ * - User-space can set @fb_id and perform a &DRM_IOCTL_MODE_GETFB2 ioctl to
+ *   fetch metadata about an existing frame-buffer.
+ *
+ * In case of planar formats, this struct allows up to 4 buffer objects with
+ * offsets and pitches per plane. The pitch and offset order are dictated by
+ * the format FourCC as defined by ``drm_fourcc.h``, e.g. NV12 is described as:
+ *
+ *     YUV 4:2:0 image with a plane of 8-bit Y samples followed by an
+ *     interleaved U/V plane containing 8-bit 2x2 subsampled colour difference
+ *     samples.
+ *
+ * So it would consist of a Y plane at ``offsets[0]`` and a UV plane at
+ * ``offsets[1]``.
+ *
+ * To accommodate tiled, compressed, etc formats, a modifier can be specified.
+ * For more information see the "Format Modifiers" section. Note that even
+ * though it looks like we have a modifier per-plane, we in fact do not. The
+ * modifier for each plane must be identical. Thus all combinations of
+ * different data layouts for multi-plane formats must be enumerated as
+ * separate modifiers.
+ *
+ * All of the entries in @handles, @pitches, @offsets and @modifier must be
+ * zero when unused. Warning, for @offsets and @modifier zero can't be used to
+ * figure out whether the entry is used or not since it's a valid value (a zero
+ * offset is common, and a zero modifier is &DRM_FORMAT_MOD_LINEAR).
+ */
+struct drm_mode_fb_cmd2 {
+	/** @fb_id: Object ID of the frame-buffer. */
+	__u32 fb_id;
+	/** @width: Width of the frame-buffer. */
+	__u32 width;
+	/** @height: Height of the frame-buffer. */
+	__u32 height;
+	/**
+	 * @pixel_format: FourCC format code, see ``DRM_FORMAT_*`` constants in
+	 * ``drm_fourcc.h``.
+	 */
+	__u32 pixel_format;
+	/**
+	 * @flags: Frame-buffer flags (see &DRM_MODE_FB_INTERLACED and
+	 * &DRM_MODE_FB_MODIFIERS).
+	 */
+	__u32 flags;
+
+	/**
+	 * @handles: GEM buffer handle, one per plane. Set to 0 if the plane is
+	 * unused. The same handle can be used for multiple planes.
+	 */
+	__u32 handles[4];
+	/** @pitches: Pitch (aka. stride) in bytes, one per plane. */
+	__u32 pitches[4];
+	/** @offsets: Offset into the buffer in bytes, one per plane. */
+	__u32 offsets[4];
+	/**
+	 * @modifier: Format modifier, one per plane. See ``DRM_FORMAT_MOD_*``
+	 * constants in ``drm_fourcc.h``. All planes must use the same
+	 * modifier. Ignored unless &DRM_MODE_FB_MODIFIERS is set in @flags.
+	 */
+	__u64 modifier[4];
+};
+
+#define DRM_MODE_FB_DIRTY_ANNOTATE_COPY 0x01
+#define DRM_MODE_FB_DIRTY_ANNOTATE_FILL 0x02
+#define DRM_MODE_FB_DIRTY_FLAGS         0x03
+
+#define DRM_MODE_FB_DIRTY_MAX_CLIPS     256
+
+/*
+ * Mark a region of a framebuffer as dirty.
+ *
+ * Some hardware does not automatically update display contents
+ * as a hardware or software draw to a framebuffer. This ioctl
+ * allows userspace to tell the kernel and the hardware what
+ * regions of the framebuffer have changed.
+ *
+ * The kernel or hardware is free to update more then just the
+ * region specified by the clip rects. The kernel or hardware
+ * may also delay and/or coalesce several calls to dirty into a
+ * single update.
+ *
+ * Userspace may annotate the updates, the annotates are a
+ * promise made by the caller that the change is either a copy
+ * of pixels or a fill of a single color in the region specified.
+ *
+ * If the DRM_MODE_FB_DIRTY_ANNOTATE_COPY flag is given then
+ * the number of updated regions are half of num_clips given,
+ * where the clip rects are paired in src and dst. The width and
+ * height of each one of the pairs must match.
+ *
+ * If the DRM_MODE_FB_DIRTY_ANNOTATE_FILL flag is given the caller
+ * promises that the region specified of the clip rects is filled
+ * completely with a single color as given in the color argument.
+ */
+
+struct drm_mode_fb_dirty_cmd {
+	__u32 fb_id;
+	__u32 flags;
+	__u32 color;
+	__u32 num_clips;
+	__u64 clips_ptr;
+};
+
+struct drm_mode_mode_cmd {
+	__u32 connector_id;
+	struct drm_mode_modeinfo mode;
+};
+
+#define DRM_MODE_CURSOR_BO	0x01
+#define DRM_MODE_CURSOR_MOVE	0x02
+#define DRM_MODE_CURSOR_FLAGS	0x03
+
+/*
+ * depending on the value in flags different members are used.
+ *
+ * CURSOR_BO uses
+ *    crtc_id
+ *    width
+ *    height
+ *    handle - if 0 turns the cursor off
+ *
+ * CURSOR_MOVE uses
+ *    crtc_id
+ *    x
+ *    y
+ */
+struct drm_mode_cursor {
+	__u32 flags;
+	__u32 crtc_id;
+	__s32 x;
+	__s32 y;
+	__u32 width;
+	__u32 height;
+	/* driver specific handle */
+	__u32 handle;
+};
+
+struct drm_mode_cursor2 {
+	__u32 flags;
+	__u32 crtc_id;
+	__s32 x;
+	__s32 y;
+	__u32 width;
+	__u32 height;
+	/* driver specific handle */
+	__u32 handle;
+	__s32 hot_x;
+	__s32 hot_y;
+};
+
+struct drm_mode_crtc_lut {
+	__u32 crtc_id;
+	__u32 gamma_size;
+
+	/* pointers to arrays */
+	__u64 red;
+	__u64 green;
+	__u64 blue;
+};
+
+struct drm_color_ctm {
+	/*
+	 * Conversion matrix in S31.32 sign-magnitude
+	 * (not two's complement!) format.
+	 *
+	 * out   matrix    in
+	 * |R|   |0 1 2|   |R|
+	 * |G| = |3 4 5| x |G|
+	 * |B|   |6 7 8|   |B|
+	 */
+	__u64 matrix[9];
+};
+
+struct drm_color_lut {
+	/*
+	 * Values are mapped linearly to 0.0 - 1.0 range, with 0x0 == 0.0 and
+	 * 0xffff == 1.0.
+	 */
+	__u16 red;
+	__u16 green;
+	__u16 blue;
+	__u16 reserved;
+};
+
+/**
+ * struct hdr_metadata_infoframe - HDR Metadata Infoframe Data.
+ *
+ * HDR Metadata Infoframe as per CTA 861.G spec. This is expected
+ * to match exactly with the spec.
+ *
+ * Userspace is expected to pass the metadata information as per
+ * the format described in this structure.
+ */
+struct hdr_metadata_infoframe {
+	/**
+	 * @eotf: Electro-Optical Transfer Function (EOTF)
+	 * used in the stream.
+	 */
+	__u8 eotf;
+	/**
+	 * @metadata_type: Static_Metadata_Descriptor_ID.
+	 */
+	__u8 metadata_type;
+	/**
+	 * @display_primaries: Color Primaries of the Data.
+	 * These are coded as unsigned 16-bit values in units of
+	 * 0.00002, where 0x0000 represents zero and 0xC350
+	 * represents 1.0000.
+	 * @display_primaries.x: X cordinate of color primary.
+	 * @display_primaries.y: Y cordinate of color primary.
+	 */
+	struct {
+		__u16 x, y;
+	} display_primaries[3];
+	/**
+	 * @white_point: White Point of Colorspace Data.
+	 * These are coded as unsigned 16-bit values in units of
+	 * 0.00002, where 0x0000 represents zero and 0xC350
+	 * represents 1.0000.
+	 * @white_point.x: X cordinate of whitepoint of color primary.
+	 * @white_point.y: Y cordinate of whitepoint of color primary.
+	 */
+	struct {
+		__u16 x, y;
+	} white_point;
+	/**
+	 * @max_display_mastering_luminance: Max Mastering Display Luminance.
+	 * This value is coded as an unsigned 16-bit value in units of 1 cd/m2,
+	 * where 0x0001 represents 1 cd/m2 and 0xFFFF represents 65535 cd/m2.
+	 */
+	__u16 max_display_mastering_luminance;
+	/**
+	 * @min_display_mastering_luminance: Min Mastering Display Luminance.
+	 * This value is coded as an unsigned 16-bit value in units of
+	 * 0.0001 cd/m2, where 0x0001 represents 0.0001 cd/m2 and 0xFFFF
+	 * represents 6.5535 cd/m2.
+	 */
+	__u16 min_display_mastering_luminance;
+	/**
+	 * @max_cll: Max Content Light Level.
+	 * This value is coded as an unsigned 16-bit value in units of 1 cd/m2,
+	 * where 0x0001 represents 1 cd/m2 and 0xFFFF represents 65535 cd/m2.
+	 */
+	__u16 max_cll;
+	/**
+	 * @max_fall: Max Frame Average Light Level.
+	 * This value is coded as an unsigned 16-bit value in units of 1 cd/m2,
+	 * where 0x0001 represents 1 cd/m2 and 0xFFFF represents 65535 cd/m2.
+	 */
+	__u16 max_fall;
+};
+
+/**
+ * struct hdr_output_metadata - HDR output metadata
+ *
+ * Metadata Information to be passed from userspace
+ */
+struct hdr_output_metadata {
+	/**
+	 * @metadata_type: Static_Metadata_Descriptor_ID.
+	 */
+	__u32 metadata_type;
+	/**
+	 * @hdmi_metadata_type1: HDR Metadata Infoframe.
+	 */
+	union {
+		struct hdr_metadata_infoframe hdmi_metadata_type1;
+	};
+};
+
+/**
+ * DRM_MODE_PAGE_FLIP_EVENT
+ *
+ * Request that the kernel sends back a vblank event (see
+ * struct drm_event_vblank) with the &DRM_EVENT_FLIP_COMPLETE type when the
+ * page-flip is done.
+ */
+#define DRM_MODE_PAGE_FLIP_EVENT 0x01
+/**
+ * DRM_MODE_PAGE_FLIP_ASYNC
+ *
+ * Request that the page-flip is performed as soon as possible, ie. with no
+ * delay due to waiting for vblank. This may cause tearing to be visible on
+ * the screen.
+ */
+#define DRM_MODE_PAGE_FLIP_ASYNC 0x02
+#define DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE 0x4
+#define DRM_MODE_PAGE_FLIP_TARGET_RELATIVE 0x8
+#define DRM_MODE_PAGE_FLIP_TARGET (DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE | \
+				   DRM_MODE_PAGE_FLIP_TARGET_RELATIVE)
+/**
+ * DRM_MODE_PAGE_FLIP_FLAGS
+ *
+ * Bitmask of flags suitable for &drm_mode_crtc_page_flip_target.flags.
+ */
+#define DRM_MODE_PAGE_FLIP_FLAGS (DRM_MODE_PAGE_FLIP_EVENT | \
+				  DRM_MODE_PAGE_FLIP_ASYNC | \
+				  DRM_MODE_PAGE_FLIP_TARGET)
+
+/*
+ * Request a page flip on the specified crtc.
+ *
+ * This ioctl will ask KMS to schedule a page flip for the specified
+ * crtc.  Once any pending rendering targeting the specified fb (as of
+ * ioctl time) has completed, the crtc will be reprogrammed to display
+ * that fb after the next vertical refresh.  The ioctl returns
+ * immediately, but subsequent rendering to the current fb will block
+ * in the execbuffer ioctl until the page flip happens.  If a page
+ * flip is already pending as the ioctl is called, EBUSY will be
+ * returned.
+ *
+ * Flag DRM_MODE_PAGE_FLIP_EVENT requests that drm sends back a vblank
+ * event (see drm.h: struct drm_event_vblank) when the page flip is
+ * done.  The user_data field passed in with this ioctl will be
+ * returned as the user_data field in the vblank event struct.
+ *
+ * Flag DRM_MODE_PAGE_FLIP_ASYNC requests that the flip happen
+ * 'as soon as possible', meaning that it not delay waiting for vblank.
+ * This may cause tearing on the screen.
+ *
+ * The reserved field must be zero.
+ */
+
+struct drm_mode_crtc_page_flip {
+	__u32 crtc_id;
+	__u32 fb_id;
+	__u32 flags;
+	__u32 reserved;
+	__u64 user_data;
+};
+
+/*
+ * Request a page flip on the specified crtc.
+ *
+ * Same as struct drm_mode_crtc_page_flip, but supports new flags and
+ * re-purposes the reserved field:
+ *
+ * The sequence field must be zero unless either of the
+ * DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE/RELATIVE flags is specified. When
+ * the ABSOLUTE flag is specified, the sequence field denotes the absolute
+ * vblank sequence when the flip should take effect. When the RELATIVE
+ * flag is specified, the sequence field denotes the relative (to the
+ * current one when the ioctl is called) vblank sequence when the flip
+ * should take effect. NOTE: DRM_IOCTL_WAIT_VBLANK must still be used to
+ * make sure the vblank sequence before the target one has passed before
+ * calling this ioctl. The purpose of the
+ * DRM_MODE_PAGE_FLIP_TARGET_ABSOLUTE/RELATIVE flags is merely to clarify
+ * the target for when code dealing with a page flip runs during a
+ * vertical blank period.
+ */
+
+struct drm_mode_crtc_page_flip_target {
+	__u32 crtc_id;
+	__u32 fb_id;
+	__u32 flags;
+	__u32 sequence;
+	__u64 user_data;
+};
+
+/* create a dumb scanout buffer */
+struct drm_mode_create_dumb {
+	__u32 height;
+	__u32 width;
+	__u32 bpp;
+	__u32 flags;
+	/* handle, pitch, size will be returned */
+	__u32 handle;
+	__u32 pitch;
+	__u64 size;
+};
+
+/* set up for mmap of a dumb scanout buffer */
+struct drm_mode_map_dumb {
+	/** Handle for the object being mapped. */
+	__u32 handle;
+	__u32 pad;
+	/**
+	 * Fake offset to use for subsequent mmap call
+	 *
+	 * This is a fixed-size type for 32/64 compatibility.
+	 */
+	__u64 offset;
+};
+
+struct drm_mode_destroy_dumb {
+	__u32 handle;
+};
+
+/**
+ * DRM_MODE_ATOMIC_TEST_ONLY
+ *
+ * Do not apply the atomic commit, instead check whether the hardware supports
+ * this configuration.
+ *
+ * See &drm_mode_config_funcs.atomic_check for more details on test-only
+ * commits.
+ */
+#define DRM_MODE_ATOMIC_TEST_ONLY 0x0100
+/**
+ * DRM_MODE_ATOMIC_NONBLOCK
+ *
+ * Do not block while applying the atomic commit. The &DRM_IOCTL_MODE_ATOMIC
+ * IOCTL returns immediately instead of waiting for the changes to be applied
+ * in hardware. Note, the driver will still check that the update can be
+ * applied before retuning.
+ */
+#define DRM_MODE_ATOMIC_NONBLOCK  0x0200
+/**
+ * DRM_MODE_ATOMIC_ALLOW_MODESET
+ *
+ * Allow the update to result in temporary or transient visible artifacts while
+ * the update is being applied. Applying the update may also take significantly
+ * more time than a page flip. All visual artifacts will disappear by the time
+ * the update is completed, as signalled through the vblank event's timestamp
+ * (see struct drm_event_vblank).
+ *
+ * This flag must be set when the KMS update might cause visible artifacts.
+ * Without this flag such KMS update will return a EINVAL error. What kind of
+ * update may cause visible artifacts depends on the driver and the hardware.
+ * User-space that needs to know beforehand if an update might cause visible
+ * artifacts can use &DRM_MODE_ATOMIC_TEST_ONLY without
+ * &DRM_MODE_ATOMIC_ALLOW_MODESET to see if it fails.
+ *
+ * To the best of the driver's knowledge, visual artifacts are guaranteed to
+ * not appear when this flag is not set. Some sinks might display visual
+ * artifacts outside of the driver's control.
+ */
+#define DRM_MODE_ATOMIC_ALLOW_MODESET 0x0400
+
+/**
+ * DRM_MODE_ATOMIC_FLAGS
+ *
+ * Bitfield of flags accepted by the &DRM_IOCTL_MODE_ATOMIC IOCTL in
+ * &drm_mode_atomic.flags.
+ */
+#define DRM_MODE_ATOMIC_FLAGS (\
+		DRM_MODE_PAGE_FLIP_EVENT |\
+		DRM_MODE_PAGE_FLIP_ASYNC |\
+		DRM_MODE_ATOMIC_TEST_ONLY |\
+		DRM_MODE_ATOMIC_NONBLOCK |\
+		DRM_MODE_ATOMIC_ALLOW_MODESET)
+
+struct drm_mode_atomic {
+	__u32 flags;
+	__u32 count_objs;
+	__u64 objs_ptr;
+	__u64 count_props_ptr;
+	__u64 props_ptr;
+	__u64 prop_values_ptr;
+	__u64 reserved;
+	__u64 user_data;
+};
+
+struct drm_format_modifier_blob {
+#define FORMAT_BLOB_CURRENT 1
+	/* Version of this blob format */
+	__u32 version;
+
+	/* Flags */
+	__u32 flags;
+
+	/* Number of fourcc formats supported */
+	__u32 count_formats;
+
+	/* Where in this blob the formats exist (in bytes) */
+	__u32 formats_offset;
+
+	/* Number of drm_format_modifiers */
+	__u32 count_modifiers;
+
+	/* Where in this blob the modifiers exist (in bytes) */
+	__u32 modifiers_offset;
+
+	/* __u32 formats[] */
+	/* struct drm_format_modifier modifiers[] */
+};
+
+struct drm_format_modifier {
+	/* Bitmask of formats in get_plane format list this info applies to. The
+	 * offset allows a sliding window of which 64 formats (bits).
+	 *
+	 * Some examples:
+	 * In today's world with < 65 formats, and formats 0, and 2 are
+	 * supported
+	 * 0x0000000000000005
+	 *		  ^-offset = 0, formats = 5
+	 *
+	 * If the number formats grew to 128, and formats 98-102 are
+	 * supported with the modifier:
+	 *
+	 * 0x0000007c00000000 0000000000000000
+	 *		  ^
+	 *		  |__offset = 64, formats = 0x7c00000000
+	 *
+	 */
+	__u64 formats;
+	__u32 offset;
+	__u32 pad;
+
+	/* The modifier that applies to the >get_plane format list bitmask. */
+	__u64 modifier;
+};
+
+/**
+ * struct drm_mode_create_blob - Create New blob property
+ *
+ * Create a new 'blob' data property, copying length bytes from data pointer,
+ * and returning new blob ID.
+ */
+struct drm_mode_create_blob {
+	/** @data: Pointer to data to copy. */
+	__u64 data;
+	/** @length: Length of data to copy. */
+	__u32 length;
+	/** @blob_id: Return: new property ID. */
+	__u32 blob_id;
+};
+
+/**
+ * struct drm_mode_destroy_blob - Destroy user blob
+ * @blob_id: blob_id to destroy
+ *
+ * Destroy a user-created blob property.
+ *
+ * User-space can release blobs as soon as they do not need to refer to them by
+ * their blob object ID.  For instance, if you are using a MODE_ID blob in an
+ * atomic commit and you will not make another commit re-using the same ID, you
+ * can destroy the blob as soon as the commit has been issued, without waiting
+ * for it to complete.
+ */
+struct drm_mode_destroy_blob {
+	__u32 blob_id;
+};
+
+/**
+ * struct drm_mode_create_lease - Create lease
+ *
+ * Lease mode resources, creating another drm_master.
+ *
+ * The @object_ids array must reference at least one CRTC, one connector and
+ * one plane if &DRM_CLIENT_CAP_UNIVERSAL_PLANES is enabled. Alternatively,
+ * the lease can be completely empty.
+ */
+struct drm_mode_create_lease {
+	/** @object_ids: Pointer to array of object ids (__u32) */
+	__u64 object_ids;
+	/** @object_count: Number of object ids */
+	__u32 object_count;
+	/** @flags: flags for new FD (O_CLOEXEC, etc) */
+	__u32 flags;
+
+	/** @lessee_id: Return: unique identifier for lessee. */
+	__u32 lessee_id;
+	/** @fd: Return: file descriptor to new drm_master file */
+	__u32 fd;
+};
+
+/**
+ * struct drm_mode_list_lessees - List lessees
+ *
+ * List lesses from a drm_master.
+ */
+struct drm_mode_list_lessees {
+	/**
+	 * @count_lessees: Number of lessees.
+	 *
+	 * On input, provides length of the array.
+	 * On output, provides total number. No
+	 * more than the input number will be written
+	 * back, so two calls can be used to get
+	 * the size and then the data.
+	 */
+	__u32 count_lessees;
+	/** @pad: Padding. */
+	__u32 pad;
+
+	/**
+	 * @lessees_ptr: Pointer to lessees.
+	 *
+	 * Pointer to __u64 array of lessee ids
+	 */
+	__u64 lessees_ptr;
+};
+
+/**
+ * struct drm_mode_get_lease - Get Lease
+ *
+ * Get leased objects.
+ */
+struct drm_mode_get_lease {
+	/**
+	 * @count_objects: Number of leased objects.
+	 *
+	 * On input, provides length of the array.
+	 * On output, provides total number. No
+	 * more than the input number will be written
+	 * back, so two calls can be used to get
+	 * the size and then the data.
+	 */
+	__u32 count_objects;
+	/** @pad: Padding. */
+	__u32 pad;
+
+	/**
+	 * @objects_ptr: Pointer to objects.
+	 *
+	 * Pointer to __u32 array of object ids.
+	 */
+	__u64 objects_ptr;
+};
+
+/**
+ * struct drm_mode_revoke_lease - Revoke lease
+ */
+struct drm_mode_revoke_lease {
+	/** @lessee_id: Unique ID of lessee */
+	__u32 lessee_id;
+};
+
+/**
+ * struct drm_mode_rect - Two dimensional rectangle.
+ * @x1: Horizontal starting coordinate (inclusive).
+ * @y1: Vertical starting coordinate (inclusive).
+ * @x2: Horizontal ending coordinate (exclusive).
+ * @y2: Vertical ending coordinate (exclusive).
+ *
+ * With drm subsystem using struct drm_rect to manage rectangular area this
+ * export it to user-space.
+ *
+ * Currently used by drm_mode_atomic blob property FB_DAMAGE_CLIPS.
+ */
+struct drm_mode_rect {
+	__s32 x1;
+	__s32 y1;
+	__s32 x2;
+	__s32 y2;
+};
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif

+ 3860 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/i915_drm.h

@@ -0,0 +1,3860 @@
+/*
+ * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sub license, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial portions
+ * of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ */
+
+#ifndef _I915_DRM_H_
+#define _I915_DRM_H_
+
+#include "drm.h"
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+/* Please note that modifications to all structs defined here are
+ * subject to backwards-compatibility constraints.
+ */
+
+/**
+ * DOC: uevents generated by i915 on its device node
+ *
+ * I915_L3_PARITY_UEVENT - Generated when the driver receives a parity mismatch
+ *	event from the GPU L3 cache. Additional information supplied is ROW,
+ *	BANK, SUBBANK, SLICE of the affected cacheline. Userspace should keep
+ *	track of these events, and if a specific cache-line seems to have a
+ *	persistent error, remap it with the L3 remapping tool supplied in
+ *	intel-gpu-tools.  The value supplied with the event is always 1.
+ *
+ * I915_ERROR_UEVENT - Generated upon error detection, currently only via
+ *	hangcheck. The error detection event is a good indicator of when things
+ *	began to go badly. The value supplied with the event is a 1 upon error
+ *	detection, and a 0 upon reset completion, signifying no more error
+ *	exists. NOTE: Disabling hangcheck or reset via module parameter will
+ *	cause the related events to not be seen.
+ *
+ * I915_RESET_UEVENT - Event is generated just before an attempt to reset the
+ *	GPU. The value supplied with the event is always 1. NOTE: Disable
+ *	reset via module parameter will cause this event to not be seen.
+ */
+#define I915_L3_PARITY_UEVENT		"L3_PARITY_ERROR"
+#define I915_ERROR_UEVENT		"ERROR"
+#define I915_RESET_UEVENT		"RESET"
+
+/**
+ * struct i915_user_extension - Base class for defining a chain of extensions
+ *
+ * Many interfaces need to grow over time. In most cases we can simply
+ * extend the struct and have userspace pass in more data. Another option,
+ * as demonstrated by Vulkan's approach to providing extensions for forward
+ * and backward compatibility, is to use a list of optional structs to
+ * provide those extra details.
+ *
+ * The key advantage to using an extension chain is that it allows us to
+ * redefine the interface more easily than an ever growing struct of
+ * increasing complexity, and for large parts of that interface to be
+ * entirely optional. The downside is more pointer chasing; chasing across
+ * the boundary with pointers encapsulated inside u64.
+ *
+ * Example chaining:
+ *
+ * .. code-block:: C
+ *
+ *	struct i915_user_extension ext3 {
+ *		.next_extension = 0, // end
+ *		.name = ...,
+ *	};
+ *	struct i915_user_extension ext2 {
+ *		.next_extension = (uintptr_t)&ext3,
+ *		.name = ...,
+ *	};
+ *	struct i915_user_extension ext1 {
+ *		.next_extension = (uintptr_t)&ext2,
+ *		.name = ...,
+ *	};
+ *
+ * Typically the struct i915_user_extension would be embedded in some uAPI
+ * struct, and in this case we would feed it the head of the chain(i.e ext1),
+ * which would then apply all of the above extensions.
+ *
+ */
+struct i915_user_extension {
+	/**
+	 * @next_extension:
+	 *
+	 * Pointer to the next struct i915_user_extension, or zero if the end.
+	 */
+	__u64 next_extension;
+	/**
+	 * @name: Name of the extension.
+	 *
+	 * Note that the name here is just some integer.
+	 *
+	 * Also note that the name space for this is not global for the whole
+	 * driver, but rather its scope/meaning is limited to the specific piece
+	 * of uAPI which has embedded the struct i915_user_extension.
+	 */
+	__u32 name;
+	/**
+	 * @flags: MBZ
+	 *
+	 * All undefined bits must be zero.
+	 */
+	__u32 flags;
+	/**
+	 * @rsvd: MBZ
+	 *
+	 * Reserved for future use; must be zero.
+	 */
+	__u32 rsvd[4];
+};
+
+/*
+ * MOCS indexes used for GPU surfaces, defining the cacheability of the
+ * surface data and the coherency for this data wrt. CPU vs. GPU accesses.
+ */
+enum i915_mocs_table_index {
+	/*
+	 * Not cached anywhere, coherency between CPU and GPU accesses is
+	 * guaranteed.
+	 */
+	I915_MOCS_UNCACHED,
+	/*
+	 * Cacheability and coherency controlled by the kernel automatically
+	 * based on the DRM_I915_GEM_SET_CACHING IOCTL setting and the current
+	 * usage of the surface (used for display scanout or not).
+	 */
+	I915_MOCS_PTE,
+	/*
+	 * Cached in all GPU caches available on the platform.
+	 * Coherency between CPU and GPU accesses to the surface is not
+	 * guaranteed without extra synchronization.
+	 */
+	I915_MOCS_CACHED,
+};
+
+/**
+ * enum drm_i915_gem_engine_class - uapi engine type enumeration
+ *
+ * Different engines serve different roles, and there may be more than one
+ * engine serving each role.  This enum provides a classification of the role
+ * of the engine, which may be used when requesting operations to be performed
+ * on a certain subset of engines, or for providing information about that
+ * group.
+ */
+enum drm_i915_gem_engine_class {
+	/**
+	 * @I915_ENGINE_CLASS_RENDER:
+	 *
+	 * Render engines support instructions used for 3D, Compute (GPGPU),
+	 * and programmable media workloads.  These instructions fetch data and
+	 * dispatch individual work items to threads that operate in parallel.
+	 * The threads run small programs (called "kernels" or "shaders") on
+	 * the GPU's execution units (EUs).
+	 */
+	I915_ENGINE_CLASS_RENDER	= 0,
+
+	/**
+	 * @I915_ENGINE_CLASS_COPY:
+	 *
+	 * Copy engines (also referred to as "blitters") support instructions
+	 * that move blocks of data from one location in memory to another,
+	 * or that fill a specified location of memory with fixed data.
+	 * Copy engines can perform pre-defined logical or bitwise operations
+	 * on the source, destination, or pattern data.
+	 */
+	I915_ENGINE_CLASS_COPY		= 1,
+
+	/**
+	 * @I915_ENGINE_CLASS_VIDEO:
+	 *
+	 * Video engines (also referred to as "bit stream decode" (BSD) or
+	 * "vdbox") support instructions that perform fixed-function media
+	 * decode and encode.
+	 */
+	I915_ENGINE_CLASS_VIDEO		= 2,
+
+	/**
+	 * @I915_ENGINE_CLASS_VIDEO_ENHANCE:
+	 *
+	 * Video enhancement engines (also referred to as "vebox") support
+	 * instructions related to image enhancement.
+	 */
+	I915_ENGINE_CLASS_VIDEO_ENHANCE	= 3,
+
+	/**
+	 * @I915_ENGINE_CLASS_COMPUTE:
+	 *
+	 * Compute engines support a subset of the instructions available
+	 * on render engines:  compute engines support Compute (GPGPU) and
+	 * programmable media workloads, but do not support the 3D pipeline.
+	 */
+	I915_ENGINE_CLASS_COMPUTE	= 4,
+
+	/* Values in this enum should be kept compact. */
+
+	/**
+	 * @I915_ENGINE_CLASS_INVALID:
+	 *
+	 * Placeholder value to represent an invalid engine class assignment.
+	 */
+	I915_ENGINE_CLASS_INVALID	= -1
+};
+
+/**
+ * struct i915_engine_class_instance - Engine class/instance identifier
+ *
+ * There may be more than one engine fulfilling any role within the system.
+ * Each engine of a class is given a unique instance number and therefore
+ * any engine can be specified by its class:instance tuplet. APIs that allow
+ * access to any engine in the system will use struct i915_engine_class_instance
+ * for this identification.
+ */
+struct i915_engine_class_instance {
+	/**
+	 * @engine_class:
+	 *
+	 * Engine class from enum drm_i915_gem_engine_class
+	 */
+	__u16 engine_class;
+#define I915_ENGINE_CLASS_INVALID_NONE -1
+#define I915_ENGINE_CLASS_INVALID_VIRTUAL -2
+
+	/**
+	 * @engine_instance:
+	 *
+	 * Engine instance.
+	 */
+	__u16 engine_instance;
+};
+
+/**
+ * DOC: perf_events exposed by i915 through /sys/bus/event_sources/drivers/i915
+ *
+ */
+
+enum drm_i915_pmu_engine_sample {
+	I915_SAMPLE_BUSY = 0,
+	I915_SAMPLE_WAIT = 1,
+	I915_SAMPLE_SEMA = 2
+};
+
+#define I915_PMU_SAMPLE_BITS (4)
+#define I915_PMU_SAMPLE_MASK (0xf)
+#define I915_PMU_SAMPLE_INSTANCE_BITS (8)
+#define I915_PMU_CLASS_SHIFT \
+	(I915_PMU_SAMPLE_BITS + I915_PMU_SAMPLE_INSTANCE_BITS)
+
+#define __I915_PMU_ENGINE(class, instance, sample) \
+	((class) << I915_PMU_CLASS_SHIFT | \
+	(instance) << I915_PMU_SAMPLE_BITS | \
+	(sample))
+
+#define I915_PMU_ENGINE_BUSY(class, instance) \
+	__I915_PMU_ENGINE(class, instance, I915_SAMPLE_BUSY)
+
+#define I915_PMU_ENGINE_WAIT(class, instance) \
+	__I915_PMU_ENGINE(class, instance, I915_SAMPLE_WAIT)
+
+#define I915_PMU_ENGINE_SEMA(class, instance) \
+	__I915_PMU_ENGINE(class, instance, I915_SAMPLE_SEMA)
+
+/*
+ * Top 4 bits of every non-engine counter are GT id.
+ */
+#define __I915_PMU_GT_SHIFT (60)
+
+#define ___I915_PMU_OTHER(gt, x) \
+	(((__u64)__I915_PMU_ENGINE(0xff, 0xff, 0xf) + 1 + (x)) | \
+	((__u64)(gt) << __I915_PMU_GT_SHIFT))
+
+#define __I915_PMU_OTHER(x) ___I915_PMU_OTHER(0, x)
+
+#define I915_PMU_ACTUAL_FREQUENCY	__I915_PMU_OTHER(0)
+#define I915_PMU_REQUESTED_FREQUENCY	__I915_PMU_OTHER(1)
+#define I915_PMU_INTERRUPTS		__I915_PMU_OTHER(2)
+#define I915_PMU_RC6_RESIDENCY		__I915_PMU_OTHER(3)
+#define I915_PMU_SOFTWARE_GT_AWAKE_TIME	__I915_PMU_OTHER(4)
+
+#define I915_PMU_LAST /* Deprecated - do not use */ I915_PMU_RC6_RESIDENCY
+
+#define __I915_PMU_ACTUAL_FREQUENCY(gt)		___I915_PMU_OTHER(gt, 0)
+#define __I915_PMU_REQUESTED_FREQUENCY(gt)	___I915_PMU_OTHER(gt, 1)
+#define __I915_PMU_INTERRUPTS(gt)		___I915_PMU_OTHER(gt, 2)
+#define __I915_PMU_RC6_RESIDENCY(gt)		___I915_PMU_OTHER(gt, 3)
+#define __I915_PMU_SOFTWARE_GT_AWAKE_TIME(gt)	___I915_PMU_OTHER(gt, 4)
+
+/* Each region is a minimum of 16k, and there are at most 255 of them.
+ */
+#define I915_NR_TEX_REGIONS 255	/* table size 2k - maximum due to use
+				 * of chars for next/prev indices */
+#define I915_LOG_MIN_TEX_REGION_SIZE 14
+
+typedef struct _drm_i915_init {
+	enum {
+		I915_INIT_DMA = 0x01,
+		I915_CLEANUP_DMA = 0x02,
+		I915_RESUME_DMA = 0x03
+	} func;
+	unsigned int mmio_offset;
+	int sarea_priv_offset;
+	unsigned int ring_start;
+	unsigned int ring_end;
+	unsigned int ring_size;
+	unsigned int front_offset;
+	unsigned int back_offset;
+	unsigned int depth_offset;
+	unsigned int w;
+	unsigned int h;
+	unsigned int pitch;
+	unsigned int pitch_bits;
+	unsigned int back_pitch;
+	unsigned int depth_pitch;
+	unsigned int cpp;
+	unsigned int chipset;
+} drm_i915_init_t;
+
+typedef struct _drm_i915_sarea {
+	struct drm_tex_region texList[I915_NR_TEX_REGIONS + 1];
+	int last_upload;	/* last time texture was uploaded */
+	int last_enqueue;	/* last time a buffer was enqueued */
+	int last_dispatch;	/* age of the most recently dispatched buffer */
+	int ctxOwner;		/* last context to upload state */
+	int texAge;
+	int pf_enabled;		/* is pageflipping allowed? */
+	int pf_active;
+	int pf_current_page;	/* which buffer is being displayed? */
+	int perf_boxes;		/* performance boxes to be displayed */
+	int width, height;      /* screen size in pixels */
+
+	drm_handle_t front_handle;
+	int front_offset;
+	int front_size;
+
+	drm_handle_t back_handle;
+	int back_offset;
+	int back_size;
+
+	drm_handle_t depth_handle;
+	int depth_offset;
+	int depth_size;
+
+	drm_handle_t tex_handle;
+	int tex_offset;
+	int tex_size;
+	int log_tex_granularity;
+	int pitch;
+	int rotation;           /* 0, 90, 180 or 270 */
+	int rotated_offset;
+	int rotated_size;
+	int rotated_pitch;
+	int virtualX, virtualY;
+
+	unsigned int front_tiled;
+	unsigned int back_tiled;
+	unsigned int depth_tiled;
+	unsigned int rotated_tiled;
+	unsigned int rotated2_tiled;
+
+	int pipeA_x;
+	int pipeA_y;
+	int pipeA_w;
+	int pipeA_h;
+	int pipeB_x;
+	int pipeB_y;
+	int pipeB_w;
+	int pipeB_h;
+
+	/* fill out some space for old userspace triple buffer */
+	drm_handle_t unused_handle;
+	__u32 unused1, unused2, unused3;
+
+	/* buffer object handles for static buffers. May change
+	 * over the lifetime of the client.
+	 */
+	__u32 front_bo_handle;
+	__u32 back_bo_handle;
+	__u32 unused_bo_handle;
+	__u32 depth_bo_handle;
+
+} drm_i915_sarea_t;
+
+/* due to userspace building against these headers we need some compat here */
+#define planeA_x pipeA_x
+#define planeA_y pipeA_y
+#define planeA_w pipeA_w
+#define planeA_h pipeA_h
+#define planeB_x pipeB_x
+#define planeB_y pipeB_y
+#define planeB_w pipeB_w
+#define planeB_h pipeB_h
+
+/* Flags for perf_boxes
+ */
+#define I915_BOX_RING_EMPTY    0x1
+#define I915_BOX_FLIP          0x2
+#define I915_BOX_WAIT          0x4
+#define I915_BOX_TEXTURE_LOAD  0x8
+#define I915_BOX_LOST_CONTEXT  0x10
+
+/*
+ * i915 specific ioctls.
+ *
+ * The device specific ioctl range is [DRM_COMMAND_BASE, DRM_COMMAND_END) ie
+ * [0x40, 0xa0) (a0 is excluded). The numbers below are defined as offset
+ * against DRM_COMMAND_BASE and should be between [0x0, 0x60).
+ */
+#define DRM_I915_INIT		0x00
+#define DRM_I915_FLUSH		0x01
+#define DRM_I915_FLIP		0x02
+#define DRM_I915_BATCHBUFFER	0x03
+#define DRM_I915_IRQ_EMIT	0x04
+#define DRM_I915_IRQ_WAIT	0x05
+#define DRM_I915_GETPARAM	0x06
+#define DRM_I915_SETPARAM	0x07
+#define DRM_I915_ALLOC		0x08
+#define DRM_I915_FREE		0x09
+#define DRM_I915_INIT_HEAP	0x0a
+#define DRM_I915_CMDBUFFER	0x0b
+#define DRM_I915_DESTROY_HEAP	0x0c
+#define DRM_I915_SET_VBLANK_PIPE	0x0d
+#define DRM_I915_GET_VBLANK_PIPE	0x0e
+#define DRM_I915_VBLANK_SWAP	0x0f
+#define DRM_I915_HWS_ADDR	0x11
+#define DRM_I915_GEM_INIT	0x13
+#define DRM_I915_GEM_EXECBUFFER	0x14
+#define DRM_I915_GEM_PIN	0x15
+#define DRM_I915_GEM_UNPIN	0x16
+#define DRM_I915_GEM_BUSY	0x17
+#define DRM_I915_GEM_THROTTLE	0x18
+#define DRM_I915_GEM_ENTERVT	0x19
+#define DRM_I915_GEM_LEAVEVT	0x1a
+#define DRM_I915_GEM_CREATE	0x1b
+#define DRM_I915_GEM_PREAD	0x1c
+#define DRM_I915_GEM_PWRITE	0x1d
+#define DRM_I915_GEM_MMAP	0x1e
+#define DRM_I915_GEM_SET_DOMAIN	0x1f
+#define DRM_I915_GEM_SW_FINISH	0x20
+#define DRM_I915_GEM_SET_TILING	0x21
+#define DRM_I915_GEM_GET_TILING	0x22
+#define DRM_I915_GEM_GET_APERTURE 0x23
+#define DRM_I915_GEM_MMAP_GTT	0x24
+#define DRM_I915_GET_PIPE_FROM_CRTC_ID	0x25
+#define DRM_I915_GEM_MADVISE	0x26
+#define DRM_I915_OVERLAY_PUT_IMAGE	0x27
+#define DRM_I915_OVERLAY_ATTRS	0x28
+#define DRM_I915_GEM_EXECBUFFER2	0x29
+#define DRM_I915_GEM_EXECBUFFER2_WR	DRM_I915_GEM_EXECBUFFER2
+#define DRM_I915_GET_SPRITE_COLORKEY	0x2a
+#define DRM_I915_SET_SPRITE_COLORKEY	0x2b
+#define DRM_I915_GEM_WAIT	0x2c
+#define DRM_I915_GEM_CONTEXT_CREATE	0x2d
+#define DRM_I915_GEM_CONTEXT_DESTROY	0x2e
+#define DRM_I915_GEM_SET_CACHING	0x2f
+#define DRM_I915_GEM_GET_CACHING	0x30
+#define DRM_I915_REG_READ		0x31
+#define DRM_I915_GET_RESET_STATS	0x32
+#define DRM_I915_GEM_USERPTR		0x33
+#define DRM_I915_GEM_CONTEXT_GETPARAM	0x34
+#define DRM_I915_GEM_CONTEXT_SETPARAM	0x35
+#define DRM_I915_PERF_OPEN		0x36
+#define DRM_I915_PERF_ADD_CONFIG	0x37
+#define DRM_I915_PERF_REMOVE_CONFIG	0x38
+#define DRM_I915_QUERY			0x39
+#define DRM_I915_GEM_VM_CREATE		0x3a
+#define DRM_I915_GEM_VM_DESTROY		0x3b
+#define DRM_I915_GEM_CREATE_EXT		0x3c
+/* Must be kept compact -- no holes */
+
+#define DRM_IOCTL_I915_INIT		DRM_IOW( DRM_COMMAND_BASE + DRM_I915_INIT, drm_i915_init_t)
+#define DRM_IOCTL_I915_FLUSH		DRM_IO ( DRM_COMMAND_BASE + DRM_I915_FLUSH)
+#define DRM_IOCTL_I915_FLIP		DRM_IO ( DRM_COMMAND_BASE + DRM_I915_FLIP)
+#define DRM_IOCTL_I915_BATCHBUFFER	DRM_IOW( DRM_COMMAND_BASE + DRM_I915_BATCHBUFFER, drm_i915_batchbuffer_t)
+#define DRM_IOCTL_I915_IRQ_EMIT         DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_IRQ_EMIT, drm_i915_irq_emit_t)
+#define DRM_IOCTL_I915_IRQ_WAIT         DRM_IOW( DRM_COMMAND_BASE + DRM_I915_IRQ_WAIT, drm_i915_irq_wait_t)
+#define DRM_IOCTL_I915_GETPARAM         DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GETPARAM, drm_i915_getparam_t)
+#define DRM_IOCTL_I915_SETPARAM         DRM_IOW( DRM_COMMAND_BASE + DRM_I915_SETPARAM, drm_i915_setparam_t)
+#define DRM_IOCTL_I915_ALLOC            DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_ALLOC, drm_i915_mem_alloc_t)
+#define DRM_IOCTL_I915_FREE             DRM_IOW( DRM_COMMAND_BASE + DRM_I915_FREE, drm_i915_mem_free_t)
+#define DRM_IOCTL_I915_INIT_HEAP        DRM_IOW( DRM_COMMAND_BASE + DRM_I915_INIT_HEAP, drm_i915_mem_init_heap_t)
+#define DRM_IOCTL_I915_CMDBUFFER	DRM_IOW( DRM_COMMAND_BASE + DRM_I915_CMDBUFFER, drm_i915_cmdbuffer_t)
+#define DRM_IOCTL_I915_DESTROY_HEAP	DRM_IOW( DRM_COMMAND_BASE + DRM_I915_DESTROY_HEAP, drm_i915_mem_destroy_heap_t)
+#define DRM_IOCTL_I915_SET_VBLANK_PIPE	DRM_IOW( DRM_COMMAND_BASE + DRM_I915_SET_VBLANK_PIPE, drm_i915_vblank_pipe_t)
+#define DRM_IOCTL_I915_GET_VBLANK_PIPE	DRM_IOR( DRM_COMMAND_BASE + DRM_I915_GET_VBLANK_PIPE, drm_i915_vblank_pipe_t)
+#define DRM_IOCTL_I915_VBLANK_SWAP	DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_VBLANK_SWAP, drm_i915_vblank_swap_t)
+#define DRM_IOCTL_I915_HWS_ADDR		DRM_IOW(DRM_COMMAND_BASE + DRM_I915_HWS_ADDR, struct drm_i915_gem_init)
+#define DRM_IOCTL_I915_GEM_INIT		DRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_INIT, struct drm_i915_gem_init)
+#define DRM_IOCTL_I915_GEM_EXECBUFFER	DRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_EXECBUFFER, struct drm_i915_gem_execbuffer)
+#define DRM_IOCTL_I915_GEM_EXECBUFFER2	DRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_EXECBUFFER2, struct drm_i915_gem_execbuffer2)
+#define DRM_IOCTL_I915_GEM_EXECBUFFER2_WR	DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_EXECBUFFER2_WR, struct drm_i915_gem_execbuffer2)
+#define DRM_IOCTL_I915_GEM_PIN		DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_PIN, struct drm_i915_gem_pin)
+#define DRM_IOCTL_I915_GEM_UNPIN	DRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_UNPIN, struct drm_i915_gem_unpin)
+#define DRM_IOCTL_I915_GEM_BUSY		DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_BUSY, struct drm_i915_gem_busy)
+#define DRM_IOCTL_I915_GEM_SET_CACHING		DRM_IOW(DRM_COMMAND_BASE + DRM_I915_GEM_SET_CACHING, struct drm_i915_gem_caching)
+#define DRM_IOCTL_I915_GEM_GET_CACHING		DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_GET_CACHING, struct drm_i915_gem_caching)
+#define DRM_IOCTL_I915_GEM_THROTTLE	DRM_IO ( DRM_COMMAND_BASE + DRM_I915_GEM_THROTTLE)
+#define DRM_IOCTL_I915_GEM_ENTERVT	DRM_IO(DRM_COMMAND_BASE + DRM_I915_GEM_ENTERVT)
+#define DRM_IOCTL_I915_GEM_LEAVEVT	DRM_IO(DRM_COMMAND_BASE + DRM_I915_GEM_LEAVEVT)
+#define DRM_IOCTL_I915_GEM_CREATE	DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_CREATE, struct drm_i915_gem_create)
+#define DRM_IOCTL_I915_GEM_CREATE_EXT	DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_CREATE_EXT, struct drm_i915_gem_create_ext)
+#define DRM_IOCTL_I915_GEM_PREAD	DRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_PREAD, struct drm_i915_gem_pread)
+#define DRM_IOCTL_I915_GEM_PWRITE	DRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_PWRITE, struct drm_i915_gem_pwrite)
+#define DRM_IOCTL_I915_GEM_MMAP		DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_MMAP, struct drm_i915_gem_mmap)
+#define DRM_IOCTL_I915_GEM_MMAP_GTT	DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_MMAP_GTT, struct drm_i915_gem_mmap_gtt)
+#define DRM_IOCTL_I915_GEM_MMAP_OFFSET	DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_MMAP_GTT, struct drm_i915_gem_mmap_offset)
+#define DRM_IOCTL_I915_GEM_SET_DOMAIN	DRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_SET_DOMAIN, struct drm_i915_gem_set_domain)
+#define DRM_IOCTL_I915_GEM_SW_FINISH	DRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_SW_FINISH, struct drm_i915_gem_sw_finish)
+#define DRM_IOCTL_I915_GEM_SET_TILING	DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_SET_TILING, struct drm_i915_gem_set_tiling)
+#define DRM_IOCTL_I915_GEM_GET_TILING	DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_GET_TILING, struct drm_i915_gem_get_tiling)
+#define DRM_IOCTL_I915_GEM_GET_APERTURE	DRM_IOR  (DRM_COMMAND_BASE + DRM_I915_GEM_GET_APERTURE, struct drm_i915_gem_get_aperture)
+#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)
+#define DRM_IOCTL_I915_GEM_MADVISE	DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_MADVISE, struct drm_i915_gem_madvise)
+#define DRM_IOCTL_I915_OVERLAY_PUT_IMAGE	DRM_IOW(DRM_COMMAND_BASE + DRM_I915_OVERLAY_PUT_IMAGE, struct drm_intel_overlay_put_image)
+#define DRM_IOCTL_I915_OVERLAY_ATTRS	DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_OVERLAY_ATTRS, struct drm_intel_overlay_attrs)
+#define DRM_IOCTL_I915_SET_SPRITE_COLORKEY DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_SET_SPRITE_COLORKEY, struct drm_intel_sprite_colorkey)
+#define DRM_IOCTL_I915_GET_SPRITE_COLORKEY DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GET_SPRITE_COLORKEY, struct drm_intel_sprite_colorkey)
+#define DRM_IOCTL_I915_GEM_WAIT		DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_WAIT, struct drm_i915_gem_wait)
+#define DRM_IOCTL_I915_GEM_CONTEXT_CREATE	DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_CREATE, struct drm_i915_gem_context_create)
+#define DRM_IOCTL_I915_GEM_CONTEXT_CREATE_EXT	DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_CREATE, struct drm_i915_gem_context_create_ext)
+#define DRM_IOCTL_I915_GEM_CONTEXT_DESTROY	DRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_DESTROY, struct drm_i915_gem_context_destroy)
+#define DRM_IOCTL_I915_REG_READ			DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_REG_READ, struct drm_i915_reg_read)
+#define DRM_IOCTL_I915_GET_RESET_STATS		DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GET_RESET_STATS, struct drm_i915_reset_stats)
+#define DRM_IOCTL_I915_GEM_USERPTR			DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_USERPTR, struct drm_i915_gem_userptr)
+#define DRM_IOCTL_I915_GEM_CONTEXT_GETPARAM	DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_GETPARAM, struct drm_i915_gem_context_param)
+#define DRM_IOCTL_I915_GEM_CONTEXT_SETPARAM	DRM_IOWR (DRM_COMMAND_BASE + DRM_I915_GEM_CONTEXT_SETPARAM, struct drm_i915_gem_context_param)
+#define DRM_IOCTL_I915_PERF_OPEN	DRM_IOW(DRM_COMMAND_BASE + DRM_I915_PERF_OPEN, struct drm_i915_perf_open_param)
+#define DRM_IOCTL_I915_PERF_ADD_CONFIG	DRM_IOW(DRM_COMMAND_BASE + DRM_I915_PERF_ADD_CONFIG, struct drm_i915_perf_oa_config)
+#define DRM_IOCTL_I915_PERF_REMOVE_CONFIG	DRM_IOW(DRM_COMMAND_BASE + DRM_I915_PERF_REMOVE_CONFIG, __u64)
+#define DRM_IOCTL_I915_QUERY			DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_QUERY, struct drm_i915_query)
+#define DRM_IOCTL_I915_GEM_VM_CREATE	DRM_IOWR(DRM_COMMAND_BASE + DRM_I915_GEM_VM_CREATE, struct drm_i915_gem_vm_control)
+#define DRM_IOCTL_I915_GEM_VM_DESTROY	DRM_IOW (DRM_COMMAND_BASE + DRM_I915_GEM_VM_DESTROY, struct drm_i915_gem_vm_control)
+
+/* Allow drivers to submit batchbuffers directly to hardware, relying
+ * on the security mechanisms provided by hardware.
+ */
+typedef struct drm_i915_batchbuffer {
+	int start;		/* agp offset */
+	int used;		/* nr bytes in use */
+	int DR1;		/* hw flags for GFX_OP_DRAWRECT_INFO */
+	int DR4;		/* window origin for GFX_OP_DRAWRECT_INFO */
+	int num_cliprects;	/* mulitpass with multiple cliprects? */
+	struct drm_clip_rect *cliprects;	/* pointer to userspace cliprects */
+} drm_i915_batchbuffer_t;
+
+/* As above, but pass a pointer to userspace buffer which can be
+ * validated by the kernel prior to sending to hardware.
+ */
+typedef struct _drm_i915_cmdbuffer {
+	char *buf;	/* pointer to userspace command buffer */
+	int sz;			/* nr bytes in buf */
+	int DR1;		/* hw flags for GFX_OP_DRAWRECT_INFO */
+	int DR4;		/* window origin for GFX_OP_DRAWRECT_INFO */
+	int num_cliprects;	/* mulitpass with multiple cliprects? */
+	struct drm_clip_rect *cliprects;	/* pointer to userspace cliprects */
+} drm_i915_cmdbuffer_t;
+
+/* Userspace can request & wait on irq's:
+ */
+typedef struct drm_i915_irq_emit {
+	int *irq_seq;
+} drm_i915_irq_emit_t;
+
+typedef struct drm_i915_irq_wait {
+	int irq_seq;
+} drm_i915_irq_wait_t;
+
+/*
+ * Different modes of per-process Graphics Translation Table,
+ * see I915_PARAM_HAS_ALIASING_PPGTT
+ */
+#define I915_GEM_PPGTT_NONE	0
+#define I915_GEM_PPGTT_ALIASING	1
+#define I915_GEM_PPGTT_FULL	2
+
+/* Ioctl to query kernel params:
+ */
+#define I915_PARAM_IRQ_ACTIVE            1
+#define I915_PARAM_ALLOW_BATCHBUFFER     2
+#define I915_PARAM_LAST_DISPATCH         3
+#define I915_PARAM_CHIPSET_ID            4
+#define I915_PARAM_HAS_GEM               5
+#define I915_PARAM_NUM_FENCES_AVAIL      6
+#define I915_PARAM_HAS_OVERLAY           7
+#define I915_PARAM_HAS_PAGEFLIPPING	 8
+#define I915_PARAM_HAS_EXECBUF2          9
+#define I915_PARAM_HAS_BSD		 10
+#define I915_PARAM_HAS_BLT		 11
+#define I915_PARAM_HAS_RELAXED_FENCING	 12
+#define I915_PARAM_HAS_COHERENT_RINGS	 13
+#define I915_PARAM_HAS_EXEC_CONSTANTS	 14
+#define I915_PARAM_HAS_RELAXED_DELTA	 15
+#define I915_PARAM_HAS_GEN7_SOL_RESET	 16
+#define I915_PARAM_HAS_LLC     	 	 17
+#define I915_PARAM_HAS_ALIASING_PPGTT	 18
+#define I915_PARAM_HAS_WAIT_TIMEOUT	 19
+#define I915_PARAM_HAS_SEMAPHORES	 20
+#define I915_PARAM_HAS_PRIME_VMAP_FLUSH	 21
+#define I915_PARAM_HAS_VEBOX		 22
+#define I915_PARAM_HAS_SECURE_BATCHES	 23
+#define I915_PARAM_HAS_PINNED_BATCHES	 24
+#define I915_PARAM_HAS_EXEC_NO_RELOC	 25
+#define I915_PARAM_HAS_EXEC_HANDLE_LUT   26
+#define I915_PARAM_HAS_WT     	 	 27
+#define I915_PARAM_CMD_PARSER_VERSION	 28
+#define I915_PARAM_HAS_COHERENT_PHYS_GTT 29
+#define I915_PARAM_MMAP_VERSION          30
+#define I915_PARAM_HAS_BSD2		 31
+#define I915_PARAM_REVISION              32
+#define I915_PARAM_SUBSLICE_TOTAL	 33
+#define I915_PARAM_EU_TOTAL		 34
+#define I915_PARAM_HAS_GPU_RESET	 35
+#define I915_PARAM_HAS_RESOURCE_STREAMER 36
+#define I915_PARAM_HAS_EXEC_SOFTPIN	 37
+#define I915_PARAM_HAS_POOLED_EU	 38
+#define I915_PARAM_MIN_EU_IN_POOL	 39
+#define I915_PARAM_MMAP_GTT_VERSION	 40
+
+/*
+ * Query whether DRM_I915_GEM_EXECBUFFER2 supports user defined execution
+ * priorities and the driver will attempt to execute batches in priority order.
+ * The param returns a capability bitmask, nonzero implies that the scheduler
+ * is enabled, with different features present according to the mask.
+ *
+ * The initial priority for each batch is supplied by the context and is
+ * controlled via I915_CONTEXT_PARAM_PRIORITY.
+ */
+#define I915_PARAM_HAS_SCHEDULER	 41
+#define   I915_SCHEDULER_CAP_ENABLED	(1ul << 0)
+#define   I915_SCHEDULER_CAP_PRIORITY	(1ul << 1)
+#define   I915_SCHEDULER_CAP_PREEMPTION	(1ul << 2)
+#define   I915_SCHEDULER_CAP_SEMAPHORES	(1ul << 3)
+#define   I915_SCHEDULER_CAP_ENGINE_BUSY_STATS	(1ul << 4)
+/*
+ * Indicates the 2k user priority levels are statically mapped into 3 buckets as
+ * follows:
+ *
+ * -1k to -1	Low priority
+ * 0		Normal priority
+ * 1 to 1k	Highest priority
+ */
+#define   I915_SCHEDULER_CAP_STATIC_PRIORITY_MAP	(1ul << 5)
+
+/*
+ * Query the status of HuC load.
+ *
+ * The query can fail in the following scenarios with the listed error codes:
+ *  -ENODEV if HuC is not present on this platform,
+ *  -EOPNOTSUPP if HuC firmware usage is disabled,
+ *  -ENOPKG if HuC firmware fetch failed,
+ *  -ENOEXEC if HuC firmware is invalid or mismatched,
+ *  -ENOMEM if i915 failed to prepare the FW objects for transfer to the uC,
+ *  -EIO if the FW transfer or the FW authentication failed.
+ *
+ * If the IOCTL is successful, the returned parameter will be set to one of the
+ * following values:
+ *  * 0 if HuC firmware load is not complete,
+ *  * 1 if HuC firmware is loaded and fully authenticated,
+ *  * 2 if HuC firmware is loaded and authenticated for clear media only
+ */
+#define I915_PARAM_HUC_STATUS		 42
+
+/* Query whether DRM_I915_GEM_EXECBUFFER2 supports the ability to opt-out of
+ * synchronisation with implicit fencing on individual objects.
+ * See EXEC_OBJECT_ASYNC.
+ */
+#define I915_PARAM_HAS_EXEC_ASYNC	 43
+
+/* Query whether DRM_I915_GEM_EXECBUFFER2 supports explicit fence support -
+ * both being able to pass in a sync_file fd to wait upon before executing,
+ * and being able to return a new sync_file fd that is signaled when the
+ * current request is complete. See I915_EXEC_FENCE_IN and I915_EXEC_FENCE_OUT.
+ */
+#define I915_PARAM_HAS_EXEC_FENCE	 44
+
+/* Query whether DRM_I915_GEM_EXECBUFFER2 supports the ability to capture
+ * user-specified buffers for post-mortem debugging of GPU hangs. See
+ * EXEC_OBJECT_CAPTURE.
+ */
+#define I915_PARAM_HAS_EXEC_CAPTURE	 45
+
+#define I915_PARAM_SLICE_MASK		 46
+
+/* Assuming it's uniform for each slice, this queries the mask of subslices
+ * per-slice for this system.
+ */
+#define I915_PARAM_SUBSLICE_MASK	 47
+
+/*
+ * Query whether DRM_I915_GEM_EXECBUFFER2 supports supplying the batch buffer
+ * as the first execobject as opposed to the last. See I915_EXEC_BATCH_FIRST.
+ */
+#define I915_PARAM_HAS_EXEC_BATCH_FIRST	 48
+
+/* Query whether DRM_I915_GEM_EXECBUFFER2 supports supplying an array of
+ * drm_i915_gem_exec_fence structures.  See I915_EXEC_FENCE_ARRAY.
+ */
+#define I915_PARAM_HAS_EXEC_FENCE_ARRAY  49
+
+/*
+ * Query whether every context (both per-file default and user created) is
+ * isolated (insofar as HW supports). If this parameter is not true, then
+ * freshly created contexts may inherit values from an existing context,
+ * rather than default HW values. If true, it also ensures (insofar as HW
+ * supports) that all state set by this context will not leak to any other
+ * context.
+ *
+ * As not every engine across every gen support contexts, the returned
+ * value reports the support of context isolation for individual engines by
+ * returning a bitmask of each engine class set to true if that class supports
+ * isolation.
+ */
+#define I915_PARAM_HAS_CONTEXT_ISOLATION 50
+
+/* Frequency of the command streamer timestamps given by the *_TIMESTAMP
+ * registers. This used to be fixed per platform but from CNL onwards, this
+ * might vary depending on the parts.
+ */
+#define I915_PARAM_CS_TIMESTAMP_FREQUENCY 51
+
+/*
+ * Once upon a time we supposed that writes through the GGTT would be
+ * immediately in physical memory (once flushed out of the CPU path). However,
+ * on a few different processors and chipsets, this is not necessarily the case
+ * as the writes appear to be buffered internally. Thus a read of the backing
+ * storage (physical memory) via a different path (with different physical tags
+ * to the indirect write via the GGTT) will see stale values from before
+ * the GGTT write. Inside the kernel, we can for the most part keep track of
+ * the different read/write domains in use (e.g. set-domain), but the assumption
+ * of coherency is baked into the ABI, hence reporting its true state in this
+ * parameter.
+ *
+ * Reports true when writes via mmap_gtt are immediately visible following an
+ * lfence to flush the WCB.
+ *
+ * Reports false when writes via mmap_gtt are indeterminately delayed in an in
+ * internal buffer and are _not_ immediately visible to third parties accessing
+ * directly via mmap_cpu/mmap_wc. Use of mmap_gtt as part of an IPC
+ * communications channel when reporting false is strongly disadvised.
+ */
+#define I915_PARAM_MMAP_GTT_COHERENT	52
+
+/*
+ * Query whether DRM_I915_GEM_EXECBUFFER2 supports coordination of parallel
+ * execution through use of explicit fence support.
+ * See I915_EXEC_FENCE_OUT and I915_EXEC_FENCE_SUBMIT.
+ */
+#define I915_PARAM_HAS_EXEC_SUBMIT_FENCE 53
+
+/*
+ * Revision of the i915-perf uAPI. The value returned helps determine what
+ * i915-perf features are available. See drm_i915_perf_property_id.
+ */
+#define I915_PARAM_PERF_REVISION	54
+
+/* Query whether DRM_I915_GEM_EXECBUFFER2 supports supplying an array of
+ * timeline syncobj through drm_i915_gem_execbuffer_ext_timeline_fences. See
+ * I915_EXEC_USE_EXTENSIONS.
+ */
+#define I915_PARAM_HAS_EXEC_TIMELINE_FENCES 55
+
+/* Query if the kernel supports the I915_USERPTR_PROBE flag. */
+#define I915_PARAM_HAS_USERPTR_PROBE 56
+
+/*
+ * Frequency of the timestamps in OA reports. This used to be the same as the CS
+ * timestamp frequency, but differs on some platforms.
+ */
+#define I915_PARAM_OA_TIMESTAMP_FREQUENCY 57
+
+/*
+ * Query the status of PXP support in i915.
+ *
+ * The query can fail in the following scenarios with the listed error codes:
+ *     -ENODEV = PXP support is not available on the GPU device or in the
+ *               kernel due to missing component drivers or kernel configs.
+ *
+ * If the IOCTL is successful, the returned parameter will be set to one of
+ * the following values:
+ *     1 = PXP feature is supported and is ready for use.
+ *     2 = PXP feature is supported but should be ready soon (pending
+ *         initialization of non-i915 system dependencies).
+ *
+ * NOTE: When param is supported (positive return values), user space should
+ *       still refer to the GEM PXP context-creation UAPI header specs to be
+ *       aware of possible failure due to system state machine at the time.
+ */
+#define I915_PARAM_PXP_STATUS		 58
+
+/* Must be kept compact -- no holes and well documented */
+
+/**
+ * struct drm_i915_getparam - Driver parameter query structure.
+ */
+struct drm_i915_getparam {
+	/** @param: Driver parameter to query. */
+	__s32 param;
+
+	/**
+	 * @value: Address of memory where queried value should be put.
+	 *
+	 * WARNING: Using pointers instead of fixed-size u64 means we need to write
+	 * compat32 code. Don't repeat this mistake.
+	 */
+	int *value;
+};
+
+/**
+ * typedef drm_i915_getparam_t - Driver parameter query structure.
+ * See struct drm_i915_getparam.
+ */
+typedef struct drm_i915_getparam drm_i915_getparam_t;
+
+/* Ioctl to set kernel params:
+ */
+#define I915_SETPARAM_USE_MI_BATCHBUFFER_START            1
+#define I915_SETPARAM_TEX_LRU_LOG_GRANULARITY             2
+#define I915_SETPARAM_ALLOW_BATCHBUFFER                   3
+#define I915_SETPARAM_NUM_USED_FENCES                     4
+/* Must be kept compact -- no holes */
+
+typedef struct drm_i915_setparam {
+	int param;
+	int value;
+} drm_i915_setparam_t;
+
+/* A memory manager for regions of shared memory:
+ */
+#define I915_MEM_REGION_AGP 1
+
+typedef struct drm_i915_mem_alloc {
+	int region;
+	int alignment;
+	int size;
+	int *region_offset;	/* offset from start of fb or agp */
+} drm_i915_mem_alloc_t;
+
+typedef struct drm_i915_mem_free {
+	int region;
+	int region_offset;
+} drm_i915_mem_free_t;
+
+typedef struct drm_i915_mem_init_heap {
+	int region;
+	int size;
+	int start;
+} drm_i915_mem_init_heap_t;
+
+/* Allow memory manager to be torn down and re-initialized (eg on
+ * rotate):
+ */
+typedef struct drm_i915_mem_destroy_heap {
+	int region;
+} drm_i915_mem_destroy_heap_t;
+
+/* Allow X server to configure which pipes to monitor for vblank signals
+ */
+#define	DRM_I915_VBLANK_PIPE_A	1
+#define	DRM_I915_VBLANK_PIPE_B	2
+
+typedef struct drm_i915_vblank_pipe {
+	int pipe;
+} drm_i915_vblank_pipe_t;
+
+/* Schedule buffer swap at given vertical blank:
+ */
+typedef struct drm_i915_vblank_swap {
+	drm_drawable_t drawable;
+	enum drm_vblank_seq_type seqtype;
+	unsigned int sequence;
+} drm_i915_vblank_swap_t;
+
+typedef struct drm_i915_hws_addr {
+	__u64 addr;
+} drm_i915_hws_addr_t;
+
+struct drm_i915_gem_init {
+	/**
+	 * Beginning offset in the GTT to be managed by the DRM memory
+	 * manager.
+	 */
+	__u64 gtt_start;
+	/**
+	 * Ending offset in the GTT to be managed by the DRM memory
+	 * manager.
+	 */
+	__u64 gtt_end;
+};
+
+struct drm_i915_gem_create {
+	/**
+	 * Requested size for the object.
+	 *
+	 * The (page-aligned) allocated size for the object will be returned.
+	 */
+	__u64 size;
+	/**
+	 * Returned handle for the object.
+	 *
+	 * Object handles are nonzero.
+	 */
+	__u32 handle;
+	__u32 pad;
+};
+
+struct drm_i915_gem_pread {
+	/** Handle for the object being read. */
+	__u32 handle;
+	__u32 pad;
+	/** Offset into the object to read from */
+	__u64 offset;
+	/** Length of data to read */
+	__u64 size;
+	/**
+	 * Pointer to write the data into.
+	 *
+	 * This is a fixed-size type for 32/64 compatibility.
+	 */
+	__u64 data_ptr;
+};
+
+struct drm_i915_gem_pwrite {
+	/** Handle for the object being written to. */
+	__u32 handle;
+	__u32 pad;
+	/** Offset into the object to write to */
+	__u64 offset;
+	/** Length of data to write */
+	__u64 size;
+	/**
+	 * Pointer to read the data from.
+	 *
+	 * This is a fixed-size type for 32/64 compatibility.
+	 */
+	__u64 data_ptr;
+};
+
+struct drm_i915_gem_mmap {
+	/** Handle for the object being mapped. */
+	__u32 handle;
+	__u32 pad;
+	/** Offset in the object to map. */
+	__u64 offset;
+	/**
+	 * Length of data to map.
+	 *
+	 * The value will be page-aligned.
+	 */
+	__u64 size;
+	/**
+	 * Returned pointer the data was mapped at.
+	 *
+	 * This is a fixed-size type for 32/64 compatibility.
+	 */
+	__u64 addr_ptr;
+
+	/**
+	 * Flags for extended behaviour.
+	 *
+	 * Added in version 2.
+	 */
+	__u64 flags;
+#define I915_MMAP_WC 0x1
+};
+
+struct drm_i915_gem_mmap_gtt {
+	/** Handle for the object being mapped. */
+	__u32 handle;
+	__u32 pad;
+	/**
+	 * Fake offset to use for subsequent mmap call
+	 *
+	 * This is a fixed-size type for 32/64 compatibility.
+	 */
+	__u64 offset;
+};
+
+/**
+ * struct drm_i915_gem_mmap_offset - Retrieve an offset so we can mmap this buffer object.
+ *
+ * This struct is passed as argument to the `DRM_IOCTL_I915_GEM_MMAP_OFFSET` ioctl,
+ * and is used to retrieve the fake offset to mmap an object specified by &handle.
+ *
+ * The legacy way of using `DRM_IOCTL_I915_GEM_MMAP` is removed on gen12+.
+ * `DRM_IOCTL_I915_GEM_MMAP_GTT` is an older supported alias to this struct, but will behave
+ * as setting the &extensions to 0, and &flags to `I915_MMAP_OFFSET_GTT`.
+ */
+struct drm_i915_gem_mmap_offset {
+	/** @handle: Handle for the object being mapped. */
+	__u32 handle;
+	/** @pad: Must be zero */
+	__u32 pad;
+	/**
+	 * @offset: The fake offset to use for subsequent mmap call
+	 *
+	 * This is a fixed-size type for 32/64 compatibility.
+	 */
+	__u64 offset;
+
+	/**
+	 * @flags: Flags for extended behaviour.
+	 *
+	 * It is mandatory that one of the `MMAP_OFFSET` types
+	 * should be included:
+	 *
+	 * - `I915_MMAP_OFFSET_GTT`: Use mmap with the object bound to GTT. (Write-Combined)
+	 * - `I915_MMAP_OFFSET_WC`: Use Write-Combined caching.
+	 * - `I915_MMAP_OFFSET_WB`: Use Write-Back caching.
+	 * - `I915_MMAP_OFFSET_FIXED`: Use object placement to determine caching.
+	 *
+	 * On devices with local memory `I915_MMAP_OFFSET_FIXED` is the only valid
+	 * type. On devices without local memory, this caching mode is invalid.
+	 *
+	 * As caching mode when specifying `I915_MMAP_OFFSET_FIXED`, WC or WB will
+	 * be used, depending on the object placement on creation. WB will be used
+	 * when the object can only exist in system memory, WC otherwise.
+	 */
+	__u64 flags;
+
+#define I915_MMAP_OFFSET_GTT	0
+#define I915_MMAP_OFFSET_WC	1
+#define I915_MMAP_OFFSET_WB	2
+#define I915_MMAP_OFFSET_UC	3
+#define I915_MMAP_OFFSET_FIXED	4
+
+	/**
+	 * @extensions: Zero-terminated chain of extensions.
+	 *
+	 * No current extensions defined; mbz.
+	 */
+	__u64 extensions;
+};
+
+/**
+ * struct drm_i915_gem_set_domain - Adjust the objects write or read domain, in
+ * preparation for accessing the pages via some CPU domain.
+ *
+ * Specifying a new write or read domain will flush the object out of the
+ * previous domain(if required), before then updating the objects domain
+ * tracking with the new domain.
+ *
+ * Note this might involve waiting for the object first if it is still active on
+ * the GPU.
+ *
+ * Supported values for @read_domains and @write_domain:
+ *
+ *	- I915_GEM_DOMAIN_WC: Uncached write-combined domain
+ *	- I915_GEM_DOMAIN_CPU: CPU cache domain
+ *	- I915_GEM_DOMAIN_GTT: Mappable aperture domain
+ *
+ * All other domains are rejected.
+ *
+ * Note that for discrete, starting from DG1, this is no longer supported, and
+ * is instead rejected. On such platforms the CPU domain is effectively static,
+ * where we also only support a single &drm_i915_gem_mmap_offset cache mode,
+ * which can't be set explicitly and instead depends on the object placements,
+ * as per the below.
+ *
+ * Implicit caching rules, starting from DG1:
+ *
+ *	- If any of the object placements (see &drm_i915_gem_create_ext_memory_regions)
+ *	  contain I915_MEMORY_CLASS_DEVICE then the object will be allocated and
+ *	  mapped as write-combined only.
+ *
+ *	- Everything else is always allocated and mapped as write-back, with the
+ *	  guarantee that everything is also coherent with the GPU.
+ *
+ * Note that this is likely to change in the future again, where we might need
+ * more flexibility on future devices, so making this all explicit as part of a
+ * new &drm_i915_gem_create_ext extension is probable.
+ */
+struct drm_i915_gem_set_domain {
+	/** @handle: Handle for the object. */
+	__u32 handle;
+
+	/** @read_domains: New read domains. */
+	__u32 read_domains;
+
+	/**
+	 * @write_domain: New write domain.
+	 *
+	 * Note that having something in the write domain implies it's in the
+	 * read domain, and only that read domain.
+	 */
+	__u32 write_domain;
+};
+
+struct drm_i915_gem_sw_finish {
+	/** Handle for the object */
+	__u32 handle;
+};
+
+struct drm_i915_gem_relocation_entry {
+	/**
+	 * Handle of the buffer being pointed to by this relocation entry.
+	 *
+	 * It's appealing to make this be an index into the mm_validate_entry
+	 * list to refer to the buffer, but this allows the driver to create
+	 * a relocation list for state buffers and not re-write it per
+	 * exec using the buffer.
+	 */
+	__u32 target_handle;
+
+	/**
+	 * Value to be added to the offset of the target buffer to make up
+	 * the relocation entry.
+	 */
+	__u32 delta;
+
+	/** Offset in the buffer the relocation entry will be written into */
+	__u64 offset;
+
+	/**
+	 * Offset value of the target buffer that the relocation entry was last
+	 * written as.
+	 *
+	 * If the buffer has the same offset as last time, we can skip syncing
+	 * and writing the relocation.  This value is written back out by
+	 * the execbuffer ioctl when the relocation is written.
+	 */
+	__u64 presumed_offset;
+
+	/**
+	 * Target memory domains read by this operation.
+	 */
+	__u32 read_domains;
+
+	/**
+	 * Target memory domains written by this operation.
+	 *
+	 * Note that only one domain may be written by the whole
+	 * execbuffer operation, so that where there are conflicts,
+	 * the application will get -EINVAL back.
+	 */
+	__u32 write_domain;
+};
+
+/** @{
+ * Intel memory domains
+ *
+ * Most of these just align with the various caches in
+ * the system and are used to flush and invalidate as
+ * objects end up cached in different domains.
+ */
+/** CPU cache */
+#define I915_GEM_DOMAIN_CPU		0x00000001
+/** Render cache, used by 2D and 3D drawing */
+#define I915_GEM_DOMAIN_RENDER		0x00000002
+/** Sampler cache, used by texture engine */
+#define I915_GEM_DOMAIN_SAMPLER		0x00000004
+/** Command queue, used to load batch buffers */
+#define I915_GEM_DOMAIN_COMMAND		0x00000008
+/** Instruction cache, used by shader programs */
+#define I915_GEM_DOMAIN_INSTRUCTION	0x00000010
+/** Vertex address cache */
+#define I915_GEM_DOMAIN_VERTEX		0x00000020
+/** GTT domain - aperture and scanout */
+#define I915_GEM_DOMAIN_GTT		0x00000040
+/** WC domain - uncached access */
+#define I915_GEM_DOMAIN_WC		0x00000080
+/** @} */
+
+struct drm_i915_gem_exec_object {
+	/**
+	 * User's handle for a buffer to be bound into the GTT for this
+	 * operation.
+	 */
+	__u32 handle;
+
+	/** Number of relocations to be performed on this buffer */
+	__u32 relocation_count;
+	/**
+	 * Pointer to array of struct drm_i915_gem_relocation_entry containing
+	 * the relocations to be performed in this buffer.
+	 */
+	__u64 relocs_ptr;
+
+	/** Required alignment in graphics aperture */
+	__u64 alignment;
+
+	/**
+	 * Returned value of the updated offset of the object, for future
+	 * presumed_offset writes.
+	 */
+	__u64 offset;
+};
+
+/* DRM_IOCTL_I915_GEM_EXECBUFFER was removed in Linux 5.13 */
+struct drm_i915_gem_execbuffer {
+	/**
+	 * List of buffers to be validated with their relocations to be
+	 * performend on them.
+	 *
+	 * This is a pointer to an array of struct drm_i915_gem_validate_entry.
+	 *
+	 * These buffers must be listed in an order such that all relocations
+	 * a buffer is performing refer to buffers that have already appeared
+	 * in the validate list.
+	 */
+	__u64 buffers_ptr;
+	__u32 buffer_count;
+
+	/** Offset in the batchbuffer to start execution from. */
+	__u32 batch_start_offset;
+	/** Bytes used in batchbuffer from batch_start_offset */
+	__u32 batch_len;
+	__u32 DR1;
+	__u32 DR4;
+	__u32 num_cliprects;
+	/** This is a struct drm_clip_rect *cliprects */
+	__u64 cliprects_ptr;
+};
+
+struct drm_i915_gem_exec_object2 {
+	/**
+	 * User's handle for a buffer to be bound into the GTT for this
+	 * operation.
+	 */
+	__u32 handle;
+
+	/** Number of relocations to be performed on this buffer */
+	__u32 relocation_count;
+	/**
+	 * Pointer to array of struct drm_i915_gem_relocation_entry containing
+	 * the relocations to be performed in this buffer.
+	 */
+	__u64 relocs_ptr;
+
+	/** Required alignment in graphics aperture */
+	__u64 alignment;
+
+	/**
+	 * When the EXEC_OBJECT_PINNED flag is specified this is populated by
+	 * the user with the GTT offset at which this object will be pinned.
+	 *
+	 * When the I915_EXEC_NO_RELOC flag is specified this must contain the
+	 * presumed_offset of the object.
+	 *
+	 * During execbuffer2 the kernel populates it with the value of the
+	 * current GTT offset of the object, for future presumed_offset writes.
+	 *
+	 * See struct drm_i915_gem_create_ext for the rules when dealing with
+	 * alignment restrictions with I915_MEMORY_CLASS_DEVICE, on devices with
+	 * minimum page sizes, like DG2.
+	 */
+	__u64 offset;
+
+#define EXEC_OBJECT_NEEDS_FENCE		 (1<<0)
+#define EXEC_OBJECT_NEEDS_GTT		 (1<<1)
+#define EXEC_OBJECT_WRITE		 (1<<2)
+#define EXEC_OBJECT_SUPPORTS_48B_ADDRESS (1<<3)
+#define EXEC_OBJECT_PINNED		 (1<<4)
+#define EXEC_OBJECT_PAD_TO_SIZE		 (1<<5)
+/* The kernel implicitly tracks GPU activity on all GEM objects, and
+ * synchronises operations with outstanding rendering. This includes
+ * rendering on other devices if exported via dma-buf. However, sometimes
+ * this tracking is too coarse and the user knows better. For example,
+ * if the object is split into non-overlapping ranges shared between different
+ * clients or engines (i.e. suballocating objects), the implicit tracking
+ * by kernel assumes that each operation affects the whole object rather
+ * than an individual range, causing needless synchronisation between clients.
+ * The kernel will also forgo any CPU cache flushes prior to rendering from
+ * the object as the client is expected to be also handling such domain
+ * tracking.
+ *
+ * The kernel maintains the implicit tracking in order to manage resources
+ * used by the GPU - this flag only disables the synchronisation prior to
+ * rendering with this object in this execbuf.
+ *
+ * Opting out of implicit synhronisation requires the user to do its own
+ * explicit tracking to avoid rendering corruption. See, for example,
+ * I915_PARAM_HAS_EXEC_FENCE to order execbufs and execute them asynchronously.
+ */
+#define EXEC_OBJECT_ASYNC		(1<<6)
+/* Request that the contents of this execobject be copied into the error
+ * state upon a GPU hang involving this batch for post-mortem debugging.
+ * These buffers are recorded in no particular order as "user" in
+ * /sys/class/drm/cardN/error. Query I915_PARAM_HAS_EXEC_CAPTURE to see
+ * if the kernel supports this flag.
+ */
+#define EXEC_OBJECT_CAPTURE		(1<<7)
+/* All remaining bits are MBZ and RESERVED FOR FUTURE USE */
+#define __EXEC_OBJECT_UNKNOWN_FLAGS -(EXEC_OBJECT_CAPTURE<<1)
+	__u64 flags;
+
+	union {
+		__u64 rsvd1;
+		__u64 pad_to_size;
+	};
+	__u64 rsvd2;
+};
+
+/**
+ * struct drm_i915_gem_exec_fence - An input or output fence for the execbuf
+ * ioctl.
+ *
+ * The request will wait for input fence to signal before submission.
+ *
+ * The returned output fence will be signaled after the completion of the
+ * request.
+ */
+struct drm_i915_gem_exec_fence {
+	/** @handle: User's handle for a drm_syncobj to wait on or signal. */
+	__u32 handle;
+
+	/**
+	 * @flags: Supported flags are:
+	 *
+	 * I915_EXEC_FENCE_WAIT:
+	 * Wait for the input fence before request submission.
+	 *
+	 * I915_EXEC_FENCE_SIGNAL:
+	 * Return request completion fence as output
+	 */
+	__u32 flags;
+#define I915_EXEC_FENCE_WAIT            (1<<0)
+#define I915_EXEC_FENCE_SIGNAL          (1<<1)
+#define __I915_EXEC_FENCE_UNKNOWN_FLAGS (-(I915_EXEC_FENCE_SIGNAL << 1))
+};
+
+/**
+ * struct drm_i915_gem_execbuffer_ext_timeline_fences - Timeline fences
+ * for execbuf ioctl.
+ *
+ * This structure describes an array of drm_syncobj and associated points for
+ * timeline variants of drm_syncobj. It is invalid to append this structure to
+ * the execbuf if I915_EXEC_FENCE_ARRAY is set.
+ */
+struct drm_i915_gem_execbuffer_ext_timeline_fences {
+#define DRM_I915_GEM_EXECBUFFER_EXT_TIMELINE_FENCES 0
+	/** @base: Extension link. See struct i915_user_extension. */
+	struct i915_user_extension base;
+
+	/**
+	 * @fence_count: Number of elements in the @handles_ptr & @value_ptr
+	 * arrays.
+	 */
+	__u64 fence_count;
+
+	/**
+	 * @handles_ptr: Pointer to an array of struct drm_i915_gem_exec_fence
+	 * of length @fence_count.
+	 */
+	__u64 handles_ptr;
+
+	/**
+	 * @values_ptr: Pointer to an array of u64 values of length
+	 * @fence_count.
+	 * Values must be 0 for a binary drm_syncobj. A Value of 0 for a
+	 * timeline drm_syncobj is invalid as it turns a drm_syncobj into a
+	 * binary one.
+	 */
+	__u64 values_ptr;
+};
+
+/**
+ * struct drm_i915_gem_execbuffer2 - Structure for DRM_I915_GEM_EXECBUFFER2
+ * ioctl.
+ */
+struct drm_i915_gem_execbuffer2 {
+	/** @buffers_ptr: Pointer to a list of gem_exec_object2 structs */
+	__u64 buffers_ptr;
+
+	/** @buffer_count: Number of elements in @buffers_ptr array */
+	__u32 buffer_count;
+
+	/**
+	 * @batch_start_offset: Offset in the batchbuffer to start execution
+	 * from.
+	 */
+	__u32 batch_start_offset;
+
+	/**
+	 * @batch_len: Length in bytes of the batch buffer, starting from the
+	 * @batch_start_offset. If 0, length is assumed to be the batch buffer
+	 * object size.
+	 */
+	__u32 batch_len;
+
+	/** @DR1: deprecated */
+	__u32 DR1;
+
+	/** @DR4: deprecated */
+	__u32 DR4;
+
+	/** @num_cliprects: See @cliprects_ptr */
+	__u32 num_cliprects;
+
+	/**
+	 * @cliprects_ptr: Kernel clipping was a DRI1 misfeature.
+	 *
+	 * It is invalid to use this field if I915_EXEC_FENCE_ARRAY or
+	 * I915_EXEC_USE_EXTENSIONS flags are not set.
+	 *
+	 * If I915_EXEC_FENCE_ARRAY is set, then this is a pointer to an array
+	 * of &drm_i915_gem_exec_fence and @num_cliprects is the length of the
+	 * array.
+	 *
+	 * If I915_EXEC_USE_EXTENSIONS is set, then this is a pointer to a
+	 * single &i915_user_extension and num_cliprects is 0.
+	 */
+	__u64 cliprects_ptr;
+
+	/** @flags: Execbuf flags */
+	__u64 flags;
+#define I915_EXEC_RING_MASK              (0x3f)
+#define I915_EXEC_DEFAULT                (0<<0)
+#define I915_EXEC_RENDER                 (1<<0)
+#define I915_EXEC_BSD                    (2<<0)
+#define I915_EXEC_BLT                    (3<<0)
+#define I915_EXEC_VEBOX                  (4<<0)
+
+/* Used for switching the constants addressing mode on gen4+ RENDER ring.
+ * Gen6+ only supports relative addressing to dynamic state (default) and
+ * absolute addressing.
+ *
+ * These flags are ignored for the BSD and BLT rings.
+ */
+#define I915_EXEC_CONSTANTS_MASK 	(3<<6)
+#define I915_EXEC_CONSTANTS_REL_GENERAL (0<<6) /* default */
+#define I915_EXEC_CONSTANTS_ABSOLUTE 	(1<<6)
+#define I915_EXEC_CONSTANTS_REL_SURFACE (2<<6) /* gen4/5 only */
+
+/** Resets the SO write offset registers for transform feedback on gen7. */
+#define I915_EXEC_GEN7_SOL_RESET	(1<<8)
+
+/** Request a privileged ("secure") batch buffer. Note only available for
+ * DRM_ROOT_ONLY | DRM_MASTER processes.
+ */
+#define I915_EXEC_SECURE		(1<<9)
+
+/** Inform the kernel that the batch is and will always be pinned. This
+ * negates the requirement for a workaround to be performed to avoid
+ * an incoherent CS (such as can be found on 830/845). If this flag is
+ * not passed, the kernel will endeavour to make sure the batch is
+ * coherent with the CS before execution. If this flag is passed,
+ * userspace assumes the responsibility for ensuring the same.
+ */
+#define I915_EXEC_IS_PINNED		(1<<10)
+
+/** Provide a hint to the kernel that the command stream and auxiliary
+ * state buffers already holds the correct presumed addresses and so the
+ * relocation process may be skipped if no buffers need to be moved in
+ * preparation for the execbuffer.
+ */
+#define I915_EXEC_NO_RELOC		(1<<11)
+
+/** Use the reloc.handle as an index into the exec object array rather
+ * than as the per-file handle.
+ */
+#define I915_EXEC_HANDLE_LUT		(1<<12)
+
+/** Used for switching BSD rings on the platforms with two BSD rings */
+#define I915_EXEC_BSD_SHIFT	 (13)
+#define I915_EXEC_BSD_MASK	 (3 << I915_EXEC_BSD_SHIFT)
+/* default ping-pong mode */
+#define I915_EXEC_BSD_DEFAULT	 (0 << I915_EXEC_BSD_SHIFT)
+#define I915_EXEC_BSD_RING1	 (1 << I915_EXEC_BSD_SHIFT)
+#define I915_EXEC_BSD_RING2	 (2 << I915_EXEC_BSD_SHIFT)
+
+/** Tell the kernel that the batchbuffer is processed by
+ *  the resource streamer.
+ */
+#define I915_EXEC_RESOURCE_STREAMER     (1<<15)
+
+/* Setting I915_EXEC_FENCE_IN implies that lower_32_bits(rsvd2) represent
+ * a sync_file fd to wait upon (in a nonblocking manner) prior to executing
+ * the batch.
+ *
+ * Returns -EINVAL if the sync_file fd cannot be found.
+ */
+#define I915_EXEC_FENCE_IN		(1<<16)
+
+/* Setting I915_EXEC_FENCE_OUT causes the ioctl to return a sync_file fd
+ * in the upper_32_bits(rsvd2) upon success. Ownership of the fd is given
+ * to the caller, and it should be close() after use. (The fd is a regular
+ * file descriptor and will be cleaned up on process termination. It holds
+ * a reference to the request, but nothing else.)
+ *
+ * The sync_file fd can be combined with other sync_file and passed either
+ * to execbuf using I915_EXEC_FENCE_IN, to atomic KMS ioctls (so that a flip
+ * will only occur after this request completes), or to other devices.
+ *
+ * Using I915_EXEC_FENCE_OUT requires use of
+ * DRM_IOCTL_I915_GEM_EXECBUFFER2_WR ioctl so that the result is written
+ * back to userspace. Failure to do so will cause the out-fence to always
+ * be reported as zero, and the real fence fd to be leaked.
+ */
+#define I915_EXEC_FENCE_OUT		(1<<17)
+
+/*
+ * Traditionally the execbuf ioctl has only considered the final element in
+ * the execobject[] to be the executable batch. Often though, the client
+ * will known the batch object prior to construction and being able to place
+ * it into the execobject[] array first can simplify the relocation tracking.
+ * Setting I915_EXEC_BATCH_FIRST tells execbuf to use element 0 of the
+ * execobject[] as the * batch instead (the default is to use the last
+ * element).
+ */
+#define I915_EXEC_BATCH_FIRST		(1<<18)
+
+/* Setting I915_FENCE_ARRAY implies that num_cliprects and cliprects_ptr
+ * define an array of i915_gem_exec_fence structures which specify a set of
+ * dma fences to wait upon or signal.
+ */
+#define I915_EXEC_FENCE_ARRAY   (1<<19)
+
+/*
+ * Setting I915_EXEC_FENCE_SUBMIT implies that lower_32_bits(rsvd2) represent
+ * a sync_file fd to wait upon (in a nonblocking manner) prior to executing
+ * the batch.
+ *
+ * Returns -EINVAL if the sync_file fd cannot be found.
+ */
+#define I915_EXEC_FENCE_SUBMIT		(1 << 20)
+
+/*
+ * Setting I915_EXEC_USE_EXTENSIONS implies that
+ * drm_i915_gem_execbuffer2.cliprects_ptr is treated as a pointer to an linked
+ * list of i915_user_extension. Each i915_user_extension node is the base of a
+ * larger structure. The list of supported structures are listed in the
+ * drm_i915_gem_execbuffer_ext enum.
+ */
+#define I915_EXEC_USE_EXTENSIONS	(1 << 21)
+#define __I915_EXEC_UNKNOWN_FLAGS (-(I915_EXEC_USE_EXTENSIONS << 1))
+
+	/** @rsvd1: Context id */
+	__u64 rsvd1;
+
+	/**
+	 * @rsvd2: in and out sync_file file descriptors.
+	 *
+	 * When I915_EXEC_FENCE_IN or I915_EXEC_FENCE_SUBMIT flag is set, the
+	 * lower 32 bits of this field will have the in sync_file fd (input).
+	 *
+	 * When I915_EXEC_FENCE_OUT flag is set, the upper 32 bits of this
+	 * field will have the out sync_file fd (output).
+	 */
+	__u64 rsvd2;
+};
+
+#define I915_EXEC_CONTEXT_ID_MASK	(0xffffffff)
+#define i915_execbuffer2_set_context_id(eb2, context) \
+	(eb2).rsvd1 = context & I915_EXEC_CONTEXT_ID_MASK
+#define i915_execbuffer2_get_context_id(eb2) \
+	((eb2).rsvd1 & I915_EXEC_CONTEXT_ID_MASK)
+
+struct drm_i915_gem_pin {
+	/** Handle of the buffer to be pinned. */
+	__u32 handle;
+	__u32 pad;
+
+	/** alignment required within the aperture */
+	__u64 alignment;
+
+	/** Returned GTT offset of the buffer. */
+	__u64 offset;
+};
+
+struct drm_i915_gem_unpin {
+	/** Handle of the buffer to be unpinned. */
+	__u32 handle;
+	__u32 pad;
+};
+
+struct drm_i915_gem_busy {
+	/** Handle of the buffer to check for busy */
+	__u32 handle;
+
+	/** Return busy status
+	 *
+	 * A return of 0 implies that the object is idle (after
+	 * having flushed any pending activity), and a non-zero return that
+	 * the object is still in-flight on the GPU. (The GPU has not yet
+	 * signaled completion for all pending requests that reference the
+	 * object.) An object is guaranteed to become idle eventually (so
+	 * long as no new GPU commands are executed upon it). Due to the
+	 * asynchronous nature of the hardware, an object reported
+	 * as busy may become idle before the ioctl is completed.
+	 *
+	 * Furthermore, if the object is busy, which engine is busy is only
+	 * provided as a guide and only indirectly by reporting its class
+	 * (there may be more than one engine in each class). There are race
+	 * conditions which prevent the report of which engines are busy from
+	 * being always accurate.  However, the converse is not true. If the
+	 * object is idle, the result of the ioctl, that all engines are idle,
+	 * is accurate.
+	 *
+	 * The returned dword is split into two fields to indicate both
+	 * the engine classes on which the object is being read, and the
+	 * engine class on which it is currently being written (if any).
+	 *
+	 * The low word (bits 0:15) indicate if the object is being written
+	 * to by any engine (there can only be one, as the GEM implicit
+	 * synchronisation rules force writes to be serialised). Only the
+	 * engine class (offset by 1, I915_ENGINE_CLASS_RENDER is reported as
+	 * 1 not 0 etc) for the last write is reported.
+	 *
+	 * The high word (bits 16:31) are a bitmask of which engines classes
+	 * are currently reading from the object. Multiple engines may be
+	 * reading from the object simultaneously.
+	 *
+	 * The value of each engine class is the same as specified in the
+	 * I915_CONTEXT_PARAM_ENGINES context parameter and via perf, i.e.
+	 * I915_ENGINE_CLASS_RENDER, I915_ENGINE_CLASS_COPY, etc.
+	 * Some hardware may have parallel execution engines, e.g. multiple
+	 * media engines, which are mapped to the same class identifier and so
+	 * are not separately reported for busyness.
+	 *
+	 * Caveat emptor:
+	 * Only the boolean result of this query is reliable; that is whether
+	 * the object is idle or busy. The report of which engines are busy
+	 * should be only used as a heuristic.
+	 */
+	__u32 busy;
+};
+
+/**
+ * struct drm_i915_gem_caching - Set or get the caching for given object
+ * handle.
+ *
+ * Allow userspace to control the GTT caching bits for a given object when the
+ * object is later mapped through the ppGTT(or GGTT on older platforms lacking
+ * ppGTT support, or if the object is used for scanout). Note that this might
+ * require unbinding the object from the GTT first, if its current caching value
+ * doesn't match.
+ *
+ * Note that this all changes on discrete platforms, starting from DG1, the
+ * set/get caching is no longer supported, and is now rejected.  Instead the CPU
+ * caching attributes(WB vs WC) will become an immutable creation time property
+ * for the object, along with the GTT caching level. For now we don't expose any
+ * new uAPI for this, instead on DG1 this is all implicit, although this largely
+ * shouldn't matter since DG1 is coherent by default(without any way of
+ * controlling it).
+ *
+ * Implicit caching rules, starting from DG1:
+ *
+ *     - If any of the object placements (see &drm_i915_gem_create_ext_memory_regions)
+ *       contain I915_MEMORY_CLASS_DEVICE then the object will be allocated and
+ *       mapped as write-combined only.
+ *
+ *     - Everything else is always allocated and mapped as write-back, with the
+ *       guarantee that everything is also coherent with the GPU.
+ *
+ * Note that this is likely to change in the future again, where we might need
+ * more flexibility on future devices, so making this all explicit as part of a
+ * new &drm_i915_gem_create_ext extension is probable.
+ *
+ * Side note: Part of the reason for this is that changing the at-allocation-time CPU
+ * caching attributes for the pages might be required(and is expensive) if we
+ * need to then CPU map the pages later with different caching attributes. This
+ * inconsistent caching behaviour, while supported on x86, is not universally
+ * supported on other architectures. So for simplicity we opt for setting
+ * everything at creation time, whilst also making it immutable, on discrete
+ * platforms.
+ */
+struct drm_i915_gem_caching {
+	/**
+	 * @handle: Handle of the buffer to set/get the caching level.
+	 */
+	__u32 handle;
+
+	/**
+	 * @caching: The GTT caching level to apply or possible return value.
+	 *
+	 * The supported @caching values:
+	 *
+	 * I915_CACHING_NONE:
+	 *
+	 * GPU access is not coherent with CPU caches.  Default for machines
+	 * without an LLC. This means manual flushing might be needed, if we
+	 * want GPU access to be coherent.
+	 *
+	 * I915_CACHING_CACHED:
+	 *
+	 * GPU access is coherent with CPU caches and furthermore the data is
+	 * cached in last-level caches shared between CPU cores and the GPU GT.
+	 *
+	 * I915_CACHING_DISPLAY:
+	 *
+	 * Special GPU caching mode which is coherent with the scanout engines.
+	 * Transparently falls back to I915_CACHING_NONE on platforms where no
+	 * special cache mode (like write-through or gfdt flushing) is
+	 * available. The kernel automatically sets this mode when using a
+	 * buffer as a scanout target.  Userspace can manually set this mode to
+	 * avoid a costly stall and clflush in the hotpath of drawing the first
+	 * frame.
+	 */
+#define I915_CACHING_NONE		0
+#define I915_CACHING_CACHED		1
+#define I915_CACHING_DISPLAY		2
+	__u32 caching;
+};
+
+#define I915_TILING_NONE	0
+#define I915_TILING_X		1
+#define I915_TILING_Y		2
+/*
+ * Do not add new tiling types here.  The I915_TILING_* values are for
+ * de-tiling fence registers that no longer exist on modern platforms.  Although
+ * the hardware may support new types of tiling in general (e.g., Tile4), we
+ * do not need to add them to the uapi that is specific to now-defunct ioctls.
+ */
+#define I915_TILING_LAST	I915_TILING_Y
+
+#define I915_BIT_6_SWIZZLE_NONE		0
+#define I915_BIT_6_SWIZZLE_9		1
+#define I915_BIT_6_SWIZZLE_9_10		2
+#define I915_BIT_6_SWIZZLE_9_11		3
+#define I915_BIT_6_SWIZZLE_9_10_11	4
+/* Not seen by userland */
+#define I915_BIT_6_SWIZZLE_UNKNOWN	5
+/* Seen by userland. */
+#define I915_BIT_6_SWIZZLE_9_17		6
+#define I915_BIT_6_SWIZZLE_9_10_17	7
+
+struct drm_i915_gem_set_tiling {
+	/** Handle of the buffer to have its tiling state updated */
+	__u32 handle;
+
+	/**
+	 * Tiling mode for the object (I915_TILING_NONE, I915_TILING_X,
+	 * I915_TILING_Y).
+	 *
+	 * This value is to be set on request, and will be updated by the
+	 * kernel on successful return with the actual chosen tiling layout.
+	 *
+	 * The tiling mode may be demoted to I915_TILING_NONE when the system
+	 * has bit 6 swizzling that can't be managed correctly by GEM.
+	 *
+	 * Buffer contents become undefined when changing tiling_mode.
+	 */
+	__u32 tiling_mode;
+
+	/**
+	 * Stride in bytes for the object when in I915_TILING_X or
+	 * I915_TILING_Y.
+	 */
+	__u32 stride;
+
+	/**
+	 * Returned address bit 6 swizzling required for CPU access through
+	 * mmap mapping.
+	 */
+	__u32 swizzle_mode;
+};
+
+struct drm_i915_gem_get_tiling {
+	/** Handle of the buffer to get tiling state for. */
+	__u32 handle;
+
+	/**
+	 * Current tiling mode for the object (I915_TILING_NONE, I915_TILING_X,
+	 * I915_TILING_Y).
+	 */
+	__u32 tiling_mode;
+
+	/**
+	 * Returned address bit 6 swizzling required for CPU access through
+	 * mmap mapping.
+	 */
+	__u32 swizzle_mode;
+
+	/**
+	 * Returned address bit 6 swizzling required for CPU access through
+	 * mmap mapping whilst bound.
+	 */
+	__u32 phys_swizzle_mode;
+};
+
+struct drm_i915_gem_get_aperture {
+	/** Total size of the aperture used by i915_gem_execbuffer, in bytes */
+	__u64 aper_size;
+
+	/**
+	 * Available space in the aperture used by i915_gem_execbuffer, in
+	 * bytes
+	 */
+	__u64 aper_available_size;
+};
+
+struct drm_i915_get_pipe_from_crtc_id {
+	/** ID of CRTC being requested **/
+	__u32 crtc_id;
+
+	/** pipe of requested CRTC **/
+	__u32 pipe;
+};
+
+#define I915_MADV_WILLNEED 0
+#define I915_MADV_DONTNEED 1
+#define __I915_MADV_PURGED 2 /* internal state */
+
+struct drm_i915_gem_madvise {
+	/** Handle of the buffer to change the backing store advice */
+	__u32 handle;
+
+	/* Advice: either the buffer will be needed again in the near future,
+	 *         or won't be and could be discarded under memory pressure.
+	 */
+	__u32 madv;
+
+	/** Whether the backing store still exists. */
+	__u32 retained;
+};
+
+/* flags */
+#define I915_OVERLAY_TYPE_MASK 		0xff
+#define I915_OVERLAY_YUV_PLANAR 	0x01
+#define I915_OVERLAY_YUV_PACKED 	0x02
+#define I915_OVERLAY_RGB		0x03
+
+#define I915_OVERLAY_DEPTH_MASK		0xff00
+#define I915_OVERLAY_RGB24		0x1000
+#define I915_OVERLAY_RGB16		0x2000
+#define I915_OVERLAY_RGB15		0x3000
+#define I915_OVERLAY_YUV422		0x0100
+#define I915_OVERLAY_YUV411		0x0200
+#define I915_OVERLAY_YUV420		0x0300
+#define I915_OVERLAY_YUV410		0x0400
+
+#define I915_OVERLAY_SWAP_MASK		0xff0000
+#define I915_OVERLAY_NO_SWAP		0x000000
+#define I915_OVERLAY_UV_SWAP		0x010000
+#define I915_OVERLAY_Y_SWAP		0x020000
+#define I915_OVERLAY_Y_AND_UV_SWAP	0x030000
+
+#define I915_OVERLAY_FLAGS_MASK		0xff000000
+#define I915_OVERLAY_ENABLE		0x01000000
+
+struct drm_intel_overlay_put_image {
+	/* various flags and src format description */
+	__u32 flags;
+	/* source picture description */
+	__u32 bo_handle;
+	/* stride values and offsets are in bytes, buffer relative */
+	__u16 stride_Y; /* stride for packed formats */
+	__u16 stride_UV;
+	__u32 offset_Y; /* offset for packet formats */
+	__u32 offset_U;
+	__u32 offset_V;
+	/* in pixels */
+	__u16 src_width;
+	__u16 src_height;
+	/* to compensate the scaling factors for partially covered surfaces */
+	__u16 src_scan_width;
+	__u16 src_scan_height;
+	/* output crtc description */
+	__u32 crtc_id;
+	__u16 dst_x;
+	__u16 dst_y;
+	__u16 dst_width;
+	__u16 dst_height;
+};
+
+/* flags */
+#define I915_OVERLAY_UPDATE_ATTRS	(1<<0)
+#define I915_OVERLAY_UPDATE_GAMMA	(1<<1)
+#define I915_OVERLAY_DISABLE_DEST_COLORKEY	(1<<2)
+struct drm_intel_overlay_attrs {
+	__u32 flags;
+	__u32 color_key;
+	__s32 brightness;
+	__u32 contrast;
+	__u32 saturation;
+	__u32 gamma0;
+	__u32 gamma1;
+	__u32 gamma2;
+	__u32 gamma3;
+	__u32 gamma4;
+	__u32 gamma5;
+};
+
+/*
+ * Intel sprite handling
+ *
+ * Color keying works with a min/mask/max tuple.  Both source and destination
+ * color keying is allowed.
+ *
+ * Source keying:
+ * Sprite pixels within the min & max values, masked against the color channels
+ * specified in the mask field, will be transparent.  All other pixels will
+ * be displayed on top of the primary plane.  For RGB surfaces, only the min
+ * and mask fields will be used; ranged compares are not allowed.
+ *
+ * Destination keying:
+ * Primary plane pixels that match the min value, masked against the color
+ * channels specified in the mask field, will be replaced by corresponding
+ * pixels from the sprite plane.
+ *
+ * Note that source & destination keying are exclusive; only one can be
+ * active on a given plane.
+ */
+
+#define I915_SET_COLORKEY_NONE		(1<<0) /* Deprecated. Instead set
+						* flags==0 to disable colorkeying.
+						*/
+#define I915_SET_COLORKEY_DESTINATION	(1<<1)
+#define I915_SET_COLORKEY_SOURCE	(1<<2)
+struct drm_intel_sprite_colorkey {
+	__u32 plane_id;
+	__u32 min_value;
+	__u32 channel_mask;
+	__u32 max_value;
+	__u32 flags;
+};
+
+struct drm_i915_gem_wait {
+	/** Handle of BO we shall wait on */
+	__u32 bo_handle;
+	__u32 flags;
+	/** Number of nanoseconds to wait, Returns time remaining. */
+	__s64 timeout_ns;
+};
+
+struct drm_i915_gem_context_create {
+	__u32 ctx_id; /* output: id of new context*/
+	__u32 pad;
+};
+
+/**
+ * struct drm_i915_gem_context_create_ext - Structure for creating contexts.
+ */
+struct drm_i915_gem_context_create_ext {
+	/** @ctx_id: Id of the created context (output) */
+	__u32 ctx_id;
+
+	/**
+	 * @flags: Supported flags are:
+	 *
+	 * I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS:
+	 *
+	 * Extensions may be appended to this structure and driver must check
+	 * for those. See @extensions.
+	 *
+	 * I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE
+	 *
+	 * Created context will have single timeline.
+	 */
+	__u32 flags;
+#define I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS	(1u << 0)
+#define I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE	(1u << 1)
+#define I915_CONTEXT_CREATE_FLAGS_UNKNOWN \
+	(-(I915_CONTEXT_CREATE_FLAGS_SINGLE_TIMELINE << 1))
+
+	/**
+	 * @extensions: Zero-terminated chain of extensions.
+	 *
+	 * I915_CONTEXT_CREATE_EXT_SETPARAM:
+	 * Context parameter to set or query during context creation.
+	 * See struct drm_i915_gem_context_create_ext_setparam.
+	 *
+	 * I915_CONTEXT_CREATE_EXT_CLONE:
+	 * This extension has been removed. On the off chance someone somewhere
+	 * has attempted to use it, never re-use this extension number.
+	 */
+	__u64 extensions;
+#define I915_CONTEXT_CREATE_EXT_SETPARAM 0
+#define I915_CONTEXT_CREATE_EXT_CLONE 1
+};
+
+/**
+ * struct drm_i915_gem_context_param - Context parameter to set or query.
+ */
+struct drm_i915_gem_context_param {
+	/** @ctx_id: Context id */
+	__u32 ctx_id;
+
+	/** @size: Size of the parameter @value */
+	__u32 size;
+
+	/** @param: Parameter to set or query */
+	__u64 param;
+#define I915_CONTEXT_PARAM_BAN_PERIOD	0x1
+/* I915_CONTEXT_PARAM_NO_ZEROMAP has been removed.  On the off chance
+ * someone somewhere has attempted to use it, never re-use this context
+ * param number.
+ */
+#define I915_CONTEXT_PARAM_NO_ZEROMAP	0x2
+#define I915_CONTEXT_PARAM_GTT_SIZE	0x3
+#define I915_CONTEXT_PARAM_NO_ERROR_CAPTURE	0x4
+#define I915_CONTEXT_PARAM_BANNABLE	0x5
+#define I915_CONTEXT_PARAM_PRIORITY	0x6
+#define   I915_CONTEXT_MAX_USER_PRIORITY	1023 /* inclusive */
+#define   I915_CONTEXT_DEFAULT_PRIORITY		0
+#define   I915_CONTEXT_MIN_USER_PRIORITY	-1023 /* inclusive */
+	/*
+	 * When using the following param, value should be a pointer to
+	 * drm_i915_gem_context_param_sseu.
+	 */
+#define I915_CONTEXT_PARAM_SSEU		0x7
+
+/*
+ * Not all clients may want to attempt automatic recover of a context after
+ * a hang (for example, some clients may only submit very small incremental
+ * batches relying on known logical state of previous batches which will never
+ * recover correctly and each attempt will hang), and so would prefer that
+ * the context is forever banned instead.
+ *
+ * If set to false (0), after a reset, subsequent (and in flight) rendering
+ * from this context is discarded, and the client will need to create a new
+ * context to use instead.
+ *
+ * If set to true (1), the kernel will automatically attempt to recover the
+ * context by skipping the hanging batch and executing the next batch starting
+ * from the default context state (discarding the incomplete logical context
+ * state lost due to the reset).
+ *
+ * On creation, all new contexts are marked as recoverable.
+ */
+#define I915_CONTEXT_PARAM_RECOVERABLE	0x8
+
+	/*
+	 * The id of the associated virtual memory address space (ppGTT) of
+	 * this context. Can be retrieved and passed to another context
+	 * (on the same fd) for both to use the same ppGTT and so share
+	 * address layouts, and avoid reloading the page tables on context
+	 * switches between themselves.
+	 *
+	 * See DRM_I915_GEM_VM_CREATE and DRM_I915_GEM_VM_DESTROY.
+	 */
+#define I915_CONTEXT_PARAM_VM		0x9
+
+/*
+ * I915_CONTEXT_PARAM_ENGINES:
+ *
+ * Bind this context to operate on this subset of available engines. Henceforth,
+ * the I915_EXEC_RING selector for DRM_IOCTL_I915_GEM_EXECBUFFER2 operates as
+ * an index into this array of engines; I915_EXEC_DEFAULT selecting engine[0]
+ * and upwards. Slots 0...N are filled in using the specified (class, instance).
+ * Use
+ *	engine_class: I915_ENGINE_CLASS_INVALID,
+ *	engine_instance: I915_ENGINE_CLASS_INVALID_NONE
+ * to specify a gap in the array that can be filled in later, e.g. by a
+ * virtual engine used for load balancing.
+ *
+ * Setting the number of engines bound to the context to 0, by passing a zero
+ * sized argument, will revert back to default settings.
+ *
+ * See struct i915_context_param_engines.
+ *
+ * Extensions:
+ *   i915_context_engines_load_balance (I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE)
+ *   i915_context_engines_bond (I915_CONTEXT_ENGINES_EXT_BOND)
+ *   i915_context_engines_parallel_submit (I915_CONTEXT_ENGINES_EXT_PARALLEL_SUBMIT)
+ */
+#define I915_CONTEXT_PARAM_ENGINES	0xa
+
+/*
+ * I915_CONTEXT_PARAM_PERSISTENCE:
+ *
+ * Allow the context and active rendering to survive the process until
+ * completion. Persistence allows fire-and-forget clients to queue up a
+ * bunch of work, hand the output over to a display server and then quit.
+ * If the context is marked as not persistent, upon closing (either via
+ * an explicit DRM_I915_GEM_CONTEXT_DESTROY or implicitly from file closure
+ * or process termination), the context and any outstanding requests will be
+ * cancelled (and exported fences for cancelled requests marked as -EIO).
+ *
+ * By default, new contexts allow persistence.
+ */
+#define I915_CONTEXT_PARAM_PERSISTENCE	0xb
+
+/* This API has been removed.  On the off chance someone somewhere has
+ * attempted to use it, never re-use this context param number.
+ */
+#define I915_CONTEXT_PARAM_RINGSIZE	0xc
+
+/*
+ * I915_CONTEXT_PARAM_PROTECTED_CONTENT:
+ *
+ * Mark that the context makes use of protected content, which will result
+ * in the context being invalidated when the protected content session is.
+ * Given that the protected content session is killed on suspend, the device
+ * is kept awake for the lifetime of a protected context, so the user should
+ * make sure to dispose of them once done.
+ * This flag can only be set at context creation time and, when set to true,
+ * must be preceded by an explicit setting of I915_CONTEXT_PARAM_RECOVERABLE
+ * to false. This flag can't be set to true in conjunction with setting the
+ * I915_CONTEXT_PARAM_BANNABLE flag to false. Creation example:
+ *
+ * .. code-block:: C
+ *
+ *	struct drm_i915_gem_context_create_ext_setparam p_protected = {
+ *		.base = {
+ *			.name = I915_CONTEXT_CREATE_EXT_SETPARAM,
+ *		},
+ *		.param = {
+ *			.param = I915_CONTEXT_PARAM_PROTECTED_CONTENT,
+ *			.value = 1,
+ *		}
+ *	};
+ *	struct drm_i915_gem_context_create_ext_setparam p_norecover = {
+ *		.base = {
+ *			.name = I915_CONTEXT_CREATE_EXT_SETPARAM,
+ *			.next_extension = to_user_pointer(&p_protected),
+ *		},
+ *		.param = {
+ *			.param = I915_CONTEXT_PARAM_RECOVERABLE,
+ *			.value = 0,
+ *		}
+ *	};
+ *	struct drm_i915_gem_context_create_ext create = {
+ *		.flags = I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS,
+ *		.extensions = to_user_pointer(&p_norecover);
+ *	};
+ *
+ *	ctx_id = gem_context_create_ext(drm_fd, &create);
+ *
+ * In addition to the normal failure cases, setting this flag during context
+ * creation can result in the following errors:
+ *
+ * -ENODEV: feature not available
+ * -EPERM: trying to mark a recoverable or not bannable context as protected
+ * -ENXIO: A dependency such as a component driver or firmware is not yet
+ *         loaded so user space may need to attempt again. Depending on the
+ *         device, this error may be reported if protected context creation is
+ *         attempted very early after kernel start because the internal timeout
+ *         waiting for such dependencies is not guaranteed to be larger than
+ *         required (numbers differ depending on system and kernel config):
+ *            - ADL/RPL: dependencies may take up to 3 seconds from kernel start
+ *                       while context creation internal timeout is 250 milisecs
+ *            - MTL: dependencies may take up to 8 seconds from kernel start
+ *                   while context creation internal timeout is 250 milisecs
+ *         NOTE: such dependencies happen once, so a subsequent call to create a
+ *         protected context after a prior successful call will not experience
+ *         such timeouts and will not return -ENXIO (unless the driver is reloaded,
+ *         or, depending on the device, resumes from a suspended state).
+ * -EIO: The firmware did not succeed in creating the protected context.
+ */
+#define I915_CONTEXT_PARAM_PROTECTED_CONTENT    0xd
+/* Must be kept compact -- no holes and well documented */
+
+	/** @value: Context parameter value to be set or queried */
+	__u64 value;
+};
+
+/*
+ * Context SSEU programming
+ *
+ * It may be necessary for either functional or performance reason to configure
+ * a context to run with a reduced number of SSEU (where SSEU stands for Slice/
+ * Sub-slice/EU).
+ *
+ * This is done by configuring SSEU configuration using the below
+ * @struct drm_i915_gem_context_param_sseu for every supported engine which
+ * userspace intends to use.
+ *
+ * Not all GPUs or engines support this functionality in which case an error
+ * code -ENODEV will be returned.
+ *
+ * Also, flexibility of possible SSEU configuration permutations varies between
+ * GPU generations and software imposed limitations. Requesting such a
+ * combination will return an error code of -EINVAL.
+ *
+ * NOTE: When perf/OA is active the context's SSEU configuration is ignored in
+ * favour of a single global setting.
+ */
+struct drm_i915_gem_context_param_sseu {
+	/*
+	 * Engine class & instance to be configured or queried.
+	 */
+	struct i915_engine_class_instance engine;
+
+	/*
+	 * Unknown flags must be cleared to zero.
+	 */
+	__u32 flags;
+#define I915_CONTEXT_SSEU_FLAG_ENGINE_INDEX (1u << 0)
+
+	/*
+	 * Mask of slices to enable for the context. Valid values are a subset
+	 * of the bitmask value returned for I915_PARAM_SLICE_MASK.
+	 */
+	__u64 slice_mask;
+
+	/*
+	 * Mask of subslices to enable for the context. Valid values are a
+	 * subset of the bitmask value return by I915_PARAM_SUBSLICE_MASK.
+	 */
+	__u64 subslice_mask;
+
+	/*
+	 * Minimum/Maximum number of EUs to enable per subslice for the
+	 * context. min_eus_per_subslice must be inferior or equal to
+	 * max_eus_per_subslice.
+	 */
+	__u16 min_eus_per_subslice;
+	__u16 max_eus_per_subslice;
+
+	/*
+	 * Unused for now. Must be cleared to zero.
+	 */
+	__u32 rsvd;
+};
+
+/**
+ * DOC: Virtual Engine uAPI
+ *
+ * Virtual engine is a concept where userspace is able to configure a set of
+ * physical engines, submit a batch buffer, and let the driver execute it on any
+ * engine from the set as it sees fit.
+ *
+ * This is primarily useful on parts which have multiple instances of a same
+ * class engine, like for example GT3+ Skylake parts with their two VCS engines.
+ *
+ * For instance userspace can enumerate all engines of a certain class using the
+ * previously described `Engine Discovery uAPI`_. After that userspace can
+ * create a GEM context with a placeholder slot for the virtual engine (using
+ * `I915_ENGINE_CLASS_INVALID` and `I915_ENGINE_CLASS_INVALID_NONE` for class
+ * and instance respectively) and finally using the
+ * `I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE` extension place a virtual engine in
+ * the same reserved slot.
+ *
+ * Example of creating a virtual engine and submitting a batch buffer to it:
+ *
+ * .. code-block:: C
+ *
+ * 	I915_DEFINE_CONTEXT_ENGINES_LOAD_BALANCE(virtual, 2) = {
+ * 		.base.name = I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE,
+ * 		.engine_index = 0, // Place this virtual engine into engine map slot 0
+ * 		.num_siblings = 2,
+ * 		.engines = { { I915_ENGINE_CLASS_VIDEO, 0 },
+ * 			     { I915_ENGINE_CLASS_VIDEO, 1 }, },
+ * 	};
+ * 	I915_DEFINE_CONTEXT_PARAM_ENGINES(engines, 1) = {
+ * 		.engines = { { I915_ENGINE_CLASS_INVALID,
+ * 			       I915_ENGINE_CLASS_INVALID_NONE } },
+ * 		.extensions = to_user_pointer(&virtual), // Chains after load_balance extension
+ * 	};
+ * 	struct drm_i915_gem_context_create_ext_setparam p_engines = {
+ * 		.base = {
+ * 			.name = I915_CONTEXT_CREATE_EXT_SETPARAM,
+ * 		},
+ * 		.param = {
+ * 			.param = I915_CONTEXT_PARAM_ENGINES,
+ * 			.value = to_user_pointer(&engines),
+ * 			.size = sizeof(engines),
+ * 		},
+ * 	};
+ * 	struct drm_i915_gem_context_create_ext create = {
+ * 		.flags = I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS,
+ * 		.extensions = to_user_pointer(&p_engines);
+ * 	};
+ *
+ * 	ctx_id = gem_context_create_ext(drm_fd, &create);
+ *
+ * 	// Now we have created a GEM context with its engine map containing a
+ * 	// single virtual engine. Submissions to this slot can go either to
+ * 	// vcs0 or vcs1, depending on the load balancing algorithm used inside
+ * 	// the driver. The load balancing is dynamic from one batch buffer to
+ * 	// another and transparent to userspace.
+ *
+ * 	...
+ * 	execbuf.rsvd1 = ctx_id;
+ * 	execbuf.flags = 0; // Submits to index 0 which is the virtual engine
+ * 	gem_execbuf(drm_fd, &execbuf);
+ */
+
+/*
+ * i915_context_engines_load_balance:
+ *
+ * Enable load balancing across this set of engines.
+ *
+ * Into the I915_EXEC_DEFAULT slot [0], a virtual engine is created that when
+ * used will proxy the execbuffer request onto one of the set of engines
+ * in such a way as to distribute the load evenly across the set.
+ *
+ * The set of engines must be compatible (e.g. the same HW class) as they
+ * will share the same logical GPU context and ring.
+ *
+ * To intermix rendering with the virtual engine and direct rendering onto
+ * the backing engines (bypassing the load balancing proxy), the context must
+ * be defined to use a single timeline for all engines.
+ */
+struct i915_context_engines_load_balance {
+	struct i915_user_extension base;
+
+	__u16 engine_index;
+	__u16 num_siblings;
+	__u32 flags; /* all undefined flags must be zero */
+
+	__u64 mbz64; /* reserved for future use; must be zero */
+
+	struct i915_engine_class_instance engines[];
+} __attribute__((packed));
+
+#define I915_DEFINE_CONTEXT_ENGINES_LOAD_BALANCE(name__, N__) struct { \
+	struct i915_user_extension base; \
+	__u16 engine_index; \
+	__u16 num_siblings; \
+	__u32 flags; \
+	__u64 mbz64; \
+	struct i915_engine_class_instance engines[N__]; \
+} __attribute__((packed)) name__
+
+/*
+ * i915_context_engines_bond:
+ *
+ * Constructed bonded pairs for execution within a virtual engine.
+ *
+ * All engines are equal, but some are more equal than others. Given
+ * the distribution of resources in the HW, it may be preferable to run
+ * a request on a given subset of engines in parallel to a request on a
+ * specific engine. We enable this selection of engines within a virtual
+ * engine by specifying bonding pairs, for any given master engine we will
+ * only execute on one of the corresponding siblings within the virtual engine.
+ *
+ * To execute a request in parallel on the master engine and a sibling requires
+ * coordination with a I915_EXEC_FENCE_SUBMIT.
+ */
+struct i915_context_engines_bond {
+	struct i915_user_extension base;
+
+	struct i915_engine_class_instance master;
+
+	__u16 virtual_index; /* index of virtual engine in ctx->engines[] */
+	__u16 num_bonds;
+
+	__u64 flags; /* all undefined flags must be zero */
+	__u64 mbz64[4]; /* reserved for future use; must be zero */
+
+	struct i915_engine_class_instance engines[];
+} __attribute__((packed));
+
+#define I915_DEFINE_CONTEXT_ENGINES_BOND(name__, N__) struct { \
+	struct i915_user_extension base; \
+	struct i915_engine_class_instance master; \
+	__u16 virtual_index; \
+	__u16 num_bonds; \
+	__u64 flags; \
+	__u64 mbz64[4]; \
+	struct i915_engine_class_instance engines[N__]; \
+} __attribute__((packed)) name__
+
+/**
+ * struct i915_context_engines_parallel_submit - Configure engine for
+ * parallel submission.
+ *
+ * Setup a slot in the context engine map to allow multiple BBs to be submitted
+ * in a single execbuf IOCTL. Those BBs will then be scheduled to run on the GPU
+ * in parallel. Multiple hardware contexts are created internally in the i915 to
+ * run these BBs. Once a slot is configured for N BBs only N BBs can be
+ * submitted in each execbuf IOCTL and this is implicit behavior e.g. The user
+ * doesn't tell the execbuf IOCTL there are N BBs, the execbuf IOCTL knows how
+ * many BBs there are based on the slot's configuration. The N BBs are the last
+ * N buffer objects or first N if I915_EXEC_BATCH_FIRST is set.
+ *
+ * The default placement behavior is to create implicit bonds between each
+ * context if each context maps to more than 1 physical engine (e.g. context is
+ * a virtual engine). Also we only allow contexts of same engine class and these
+ * contexts must be in logically contiguous order. Examples of the placement
+ * behavior are described below. Lastly, the default is to not allow BBs to be
+ * preempted mid-batch. Rather insert coordinated preemption points on all
+ * hardware contexts between each set of BBs. Flags could be added in the future
+ * to change both of these default behaviors.
+ *
+ * Returns -EINVAL if hardware context placement configuration is invalid or if
+ * the placement configuration isn't supported on the platform / submission
+ * interface.
+ * Returns -ENODEV if extension isn't supported on the platform / submission
+ * interface.
+ *
+ * .. code-block:: none
+ *
+ *	Examples syntax:
+ *	CS[X] = generic engine of same class, logical instance X
+ *	INVALID = I915_ENGINE_CLASS_INVALID, I915_ENGINE_CLASS_INVALID_NONE
+ *
+ *	Example 1 pseudo code:
+ *	set_engines(INVALID)
+ *	set_parallel(engine_index=0, width=2, num_siblings=1,
+ *		     engines=CS[0],CS[1])
+ *
+ *	Results in the following valid placement:
+ *	CS[0], CS[1]
+ *
+ *	Example 2 pseudo code:
+ *	set_engines(INVALID)
+ *	set_parallel(engine_index=0, width=2, num_siblings=2,
+ *		     engines=CS[0],CS[2],CS[1],CS[3])
+ *
+ *	Results in the following valid placements:
+ *	CS[0], CS[1]
+ *	CS[2], CS[3]
+ *
+ *	This can be thought of as two virtual engines, each containing two
+ *	engines thereby making a 2D array. However, there are bonds tying the
+ *	entries together and placing restrictions on how they can be scheduled.
+ *	Specifically, the scheduler can choose only vertical columns from the 2D
+ *	array. That is, CS[0] is bonded to CS[1] and CS[2] to CS[3]. So if the
+ *	scheduler wants to submit to CS[0], it must also choose CS[1] and vice
+ *	versa. Same for CS[2] requires also using CS[3].
+ *	VE[0] = CS[0], CS[2]
+ *	VE[1] = CS[1], CS[3]
+ *
+ *	Example 3 pseudo code:
+ *	set_engines(INVALID)
+ *	set_parallel(engine_index=0, width=2, num_siblings=2,
+ *		     engines=CS[0],CS[1],CS[1],CS[3])
+ *
+ *	Results in the following valid and invalid placements:
+ *	CS[0], CS[1]
+ *	CS[1], CS[3] - Not logically contiguous, return -EINVAL
+ */
+struct i915_context_engines_parallel_submit {
+	/**
+	 * @base: base user extension.
+	 */
+	struct i915_user_extension base;
+
+	/**
+	 * @engine_index: slot for parallel engine
+	 */
+	__u16 engine_index;
+
+	/**
+	 * @width: number of contexts per parallel engine or in other words the
+	 * number of batches in each submission
+	 */
+	__u16 width;
+
+	/**
+	 * @num_siblings: number of siblings per context or in other words the
+	 * number of possible placements for each submission
+	 */
+	__u16 num_siblings;
+
+	/**
+	 * @mbz16: reserved for future use; must be zero
+	 */
+	__u16 mbz16;
+
+	/**
+	 * @flags: all undefined flags must be zero, currently not defined flags
+	 */
+	__u64 flags;
+
+	/**
+	 * @mbz64: reserved for future use; must be zero
+	 */
+	__u64 mbz64[3];
+
+	/**
+	 * @engines: 2-d array of engine instances to configure parallel engine
+	 *
+	 * length = width (i) * num_siblings (j)
+	 * index = j + i * num_siblings
+	 */
+	struct i915_engine_class_instance engines[];
+
+} __attribute__((packed));
+
+#define I915_DEFINE_CONTEXT_ENGINES_PARALLEL_SUBMIT(name__, N__) struct { \
+	struct i915_user_extension base; \
+	__u16 engine_index; \
+	__u16 width; \
+	__u16 num_siblings; \
+	__u16 mbz16; \
+	__u64 flags; \
+	__u64 mbz64[3]; \
+	struct i915_engine_class_instance engines[N__]; \
+} __attribute__((packed)) name__
+
+/**
+ * DOC: Context Engine Map uAPI
+ *
+ * Context engine map is a new way of addressing engines when submitting batch-
+ * buffers, replacing the existing way of using identifiers like `I915_EXEC_BLT`
+ * inside the flags field of `struct drm_i915_gem_execbuffer2`.
+ *
+ * To use it created GEM contexts need to be configured with a list of engines
+ * the user is intending to submit to. This is accomplished using the
+ * `I915_CONTEXT_PARAM_ENGINES` parameter and `struct
+ * i915_context_param_engines`.
+ *
+ * For such contexts the `I915_EXEC_RING_MASK` field becomes an index into the
+ * configured map.
+ *
+ * Example of creating such context and submitting against it:
+ *
+ * .. code-block:: C
+ *
+ * 	I915_DEFINE_CONTEXT_PARAM_ENGINES(engines, 2) = {
+ * 		.engines = { { I915_ENGINE_CLASS_RENDER, 0 },
+ * 			     { I915_ENGINE_CLASS_COPY, 0 } }
+ * 	};
+ * 	struct drm_i915_gem_context_create_ext_setparam p_engines = {
+ * 		.base = {
+ * 			.name = I915_CONTEXT_CREATE_EXT_SETPARAM,
+ * 		},
+ * 		.param = {
+ * 			.param = I915_CONTEXT_PARAM_ENGINES,
+ * 			.value = to_user_pointer(&engines),
+ * 			.size = sizeof(engines),
+ * 		},
+ * 	};
+ * 	struct drm_i915_gem_context_create_ext create = {
+ * 		.flags = I915_CONTEXT_CREATE_FLAGS_USE_EXTENSIONS,
+ * 		.extensions = to_user_pointer(&p_engines);
+ * 	};
+ *
+ * 	ctx_id = gem_context_create_ext(drm_fd, &create);
+ *
+ * 	// We have now created a GEM context with two engines in the map:
+ * 	// Index 0 points to rcs0 while index 1 points to bcs0. Other engines
+ * 	// will not be accessible from this context.
+ *
+ * 	...
+ * 	execbuf.rsvd1 = ctx_id;
+ * 	execbuf.flags = 0; // Submits to index 0, which is rcs0 for this context
+ * 	gem_execbuf(drm_fd, &execbuf);
+ *
+ * 	...
+ * 	execbuf.rsvd1 = ctx_id;
+ * 	execbuf.flags = 1; // Submits to index 0, which is bcs0 for this context
+ * 	gem_execbuf(drm_fd, &execbuf);
+ */
+
+struct i915_context_param_engines {
+	__u64 extensions; /* linked chain of extension blocks, 0 terminates */
+#define I915_CONTEXT_ENGINES_EXT_LOAD_BALANCE 0 /* see i915_context_engines_load_balance */
+#define I915_CONTEXT_ENGINES_EXT_BOND 1 /* see i915_context_engines_bond */
+#define I915_CONTEXT_ENGINES_EXT_PARALLEL_SUBMIT 2 /* see i915_context_engines_parallel_submit */
+	struct i915_engine_class_instance engines[];
+} __attribute__((packed));
+
+#define I915_DEFINE_CONTEXT_PARAM_ENGINES(name__, N__) struct { \
+	__u64 extensions; \
+	struct i915_engine_class_instance engines[N__]; \
+} __attribute__((packed)) name__
+
+/**
+ * struct drm_i915_gem_context_create_ext_setparam - Context parameter
+ * to set or query during context creation.
+ */
+struct drm_i915_gem_context_create_ext_setparam {
+	/** @base: Extension link. See struct i915_user_extension. */
+	struct i915_user_extension base;
+
+	/**
+	 * @param: Context parameter to set or query.
+	 * See struct drm_i915_gem_context_param.
+	 */
+	struct drm_i915_gem_context_param param;
+};
+
+struct drm_i915_gem_context_destroy {
+	__u32 ctx_id;
+	__u32 pad;
+};
+
+/**
+ * struct drm_i915_gem_vm_control - Structure to create or destroy VM.
+ *
+ * DRM_I915_GEM_VM_CREATE -
+ *
+ * Create a new virtual memory address space (ppGTT) for use within a context
+ * on the same file. Extensions can be provided to configure exactly how the
+ * address space is setup upon creation.
+ *
+ * The id of new VM (bound to the fd) for use with I915_CONTEXT_PARAM_VM is
+ * returned in the outparam @id.
+ *
+ * An extension chain maybe provided, starting with @extensions, and terminated
+ * by the @next_extension being 0. Currently, no extensions are defined.
+ *
+ * DRM_I915_GEM_VM_DESTROY -
+ *
+ * Destroys a previously created VM id, specified in @vm_id.
+ *
+ * No extensions or flags are allowed currently, and so must be zero.
+ */
+struct drm_i915_gem_vm_control {
+	/** @extensions: Zero-terminated chain of extensions. */
+	__u64 extensions;
+
+	/** @flags: reserved for future usage, currently MBZ */
+	__u32 flags;
+
+	/** @vm_id: Id of the VM created or to be destroyed */
+	__u32 vm_id;
+};
+
+struct drm_i915_reg_read {
+	/*
+	 * Register offset.
+	 * For 64bit wide registers where the upper 32bits don't immediately
+	 * follow the lower 32bits, the offset of the lower 32bits must
+	 * be specified
+	 */
+	__u64 offset;
+#define I915_REG_READ_8B_WA (1ul << 0)
+
+	__u64 val; /* Return value */
+};
+
+/* Known registers:
+ *
+ * Render engine timestamp - 0x2358 + 64bit - gen7+
+ * - Note this register returns an invalid value if using the default
+ *   single instruction 8byte read, in order to workaround that pass
+ *   flag I915_REG_READ_8B_WA in offset field.
+ *
+ */
+
+struct drm_i915_reset_stats {
+	__u32 ctx_id;
+	__u32 flags;
+
+	/* All resets since boot/module reload, for all contexts */
+	__u32 reset_count;
+
+	/* Number of batches lost when active in GPU, for this context */
+	__u32 batch_active;
+
+	/* Number of batches lost pending for execution, for this context */
+	__u32 batch_pending;
+
+	__u32 pad;
+};
+
+/**
+ * struct drm_i915_gem_userptr - Create GEM object from user allocated memory.
+ *
+ * Userptr objects have several restrictions on what ioctls can be used with the
+ * object handle.
+ */
+struct drm_i915_gem_userptr {
+	/**
+	 * @user_ptr: The pointer to the allocated memory.
+	 *
+	 * Needs to be aligned to PAGE_SIZE.
+	 */
+	__u64 user_ptr;
+
+	/**
+	 * @user_size:
+	 *
+	 * The size in bytes for the allocated memory. This will also become the
+	 * object size.
+	 *
+	 * Needs to be aligned to PAGE_SIZE, and should be at least PAGE_SIZE,
+	 * or larger.
+	 */
+	__u64 user_size;
+
+	/**
+	 * @flags:
+	 *
+	 * Supported flags:
+	 *
+	 * I915_USERPTR_READ_ONLY:
+	 *
+	 * Mark the object as readonly, this also means GPU access can only be
+	 * readonly. This is only supported on HW which supports readonly access
+	 * through the GTT. If the HW can't support readonly access, an error is
+	 * returned.
+	 *
+	 * I915_USERPTR_PROBE:
+	 *
+	 * Probe the provided @user_ptr range and validate that the @user_ptr is
+	 * indeed pointing to normal memory and that the range is also valid.
+	 * For example if some garbage address is given to the kernel, then this
+	 * should complain.
+	 *
+	 * Returns -EFAULT if the probe failed.
+	 *
+	 * Note that this doesn't populate the backing pages, and also doesn't
+	 * guarantee that the object will remain valid when the object is
+	 * eventually used.
+	 *
+	 * The kernel supports this feature if I915_PARAM_HAS_USERPTR_PROBE
+	 * returns a non-zero value.
+	 *
+	 * I915_USERPTR_UNSYNCHRONIZED:
+	 *
+	 * NOT USED. Setting this flag will result in an error.
+	 */
+	__u32 flags;
+#define I915_USERPTR_READ_ONLY 0x1
+#define I915_USERPTR_PROBE 0x2
+#define I915_USERPTR_UNSYNCHRONIZED 0x80000000
+	/**
+	 * @handle: Returned handle for the object.
+	 *
+	 * Object handles are nonzero.
+	 */
+	__u32 handle;
+};
+
+enum drm_i915_oa_format {
+	I915_OA_FORMAT_A13 = 1,	    /* HSW only */
+	I915_OA_FORMAT_A29,	    /* HSW only */
+	I915_OA_FORMAT_A13_B8_C8,   /* HSW only */
+	I915_OA_FORMAT_B4_C8,	    /* HSW only */
+	I915_OA_FORMAT_A45_B8_C8,   /* HSW only */
+	I915_OA_FORMAT_B4_C8_A16,   /* HSW only */
+	I915_OA_FORMAT_C4_B8,	    /* HSW+ */
+
+	/* Gen8+ */
+	I915_OA_FORMAT_A12,
+	I915_OA_FORMAT_A12_B8_C8,
+	I915_OA_FORMAT_A32u40_A4u32_B8_C8,
+
+	/* DG2 */
+	I915_OAR_FORMAT_A32u40_A4u32_B8_C8,
+	I915_OA_FORMAT_A24u40_A14u32_B8_C8,
+
+	/* MTL OAM */
+	I915_OAM_FORMAT_MPEC8u64_B8_C8,
+	I915_OAM_FORMAT_MPEC8u32_B8_C8,
+
+	I915_OA_FORMAT_MAX	    /* non-ABI */
+};
+
+enum drm_i915_perf_property_id {
+	/**
+	 * Open the stream for a specific context handle (as used with
+	 * execbuffer2). A stream opened for a specific context this way
+	 * won't typically require root privileges.
+	 *
+	 * This property is available in perf revision 1.
+	 */
+	DRM_I915_PERF_PROP_CTX_HANDLE = 1,
+
+	/**
+	 * A value of 1 requests the inclusion of raw OA unit reports as
+	 * part of stream samples.
+	 *
+	 * This property is available in perf revision 1.
+	 */
+	DRM_I915_PERF_PROP_SAMPLE_OA,
+
+	/**
+	 * The value specifies which set of OA unit metrics should be
+	 * configured, defining the contents of any OA unit reports.
+	 *
+	 * This property is available in perf revision 1.
+	 */
+	DRM_I915_PERF_PROP_OA_METRICS_SET,
+
+	/**
+	 * The value specifies the size and layout of OA unit reports.
+	 *
+	 * This property is available in perf revision 1.
+	 */
+	DRM_I915_PERF_PROP_OA_FORMAT,
+
+	/**
+	 * Specifying this property implicitly requests periodic OA unit
+	 * sampling and (at least on Haswell) the sampling frequency is derived
+	 * from this exponent as follows:
+	 *
+	 *   80ns * 2^(period_exponent + 1)
+	 *
+	 * This property is available in perf revision 1.
+	 */
+	DRM_I915_PERF_PROP_OA_EXPONENT,
+
+	/**
+	 * Specifying this property is only valid when specify a context to
+	 * filter with DRM_I915_PERF_PROP_CTX_HANDLE. Specifying this property
+	 * will hold preemption of the particular context we want to gather
+	 * performance data about. The execbuf2 submissions must include a
+	 * drm_i915_gem_execbuffer_ext_perf parameter for this to apply.
+	 *
+	 * This property is available in perf revision 3.
+	 */
+	DRM_I915_PERF_PROP_HOLD_PREEMPTION,
+
+	/**
+	 * Specifying this pins all contexts to the specified SSEU power
+	 * configuration for the duration of the recording.
+	 *
+	 * This parameter's value is a pointer to a struct
+	 * drm_i915_gem_context_param_sseu.
+	 *
+	 * This property is available in perf revision 4.
+	 */
+	DRM_I915_PERF_PROP_GLOBAL_SSEU,
+
+	/**
+	 * This optional parameter specifies the timer interval in nanoseconds
+	 * at which the i915 driver will check the OA buffer for available data.
+	 * Minimum allowed value is 100 microseconds. A default value is used by
+	 * the driver if this parameter is not specified. Note that larger timer
+	 * values will reduce cpu consumption during OA perf captures. However,
+	 * excessively large values would potentially result in OA buffer
+	 * overwrites as captures reach end of the OA buffer.
+	 *
+	 * This property is available in perf revision 5.
+	 */
+	DRM_I915_PERF_PROP_POLL_OA_PERIOD,
+
+	/**
+	 * Multiple engines may be mapped to the same OA unit. The OA unit is
+	 * identified by class:instance of any engine mapped to it.
+	 *
+	 * This parameter specifies the engine class and must be passed along
+	 * with DRM_I915_PERF_PROP_OA_ENGINE_INSTANCE.
+	 *
+	 * This property is available in perf revision 6.
+	 */
+	DRM_I915_PERF_PROP_OA_ENGINE_CLASS,
+
+	/**
+	 * This parameter specifies the engine instance and must be passed along
+	 * with DRM_I915_PERF_PROP_OA_ENGINE_CLASS.
+	 *
+	 * This property is available in perf revision 6.
+	 */
+	DRM_I915_PERF_PROP_OA_ENGINE_INSTANCE,
+
+	DRM_I915_PERF_PROP_MAX /* non-ABI */
+};
+
+struct drm_i915_perf_open_param {
+	__u32 flags;
+#define I915_PERF_FLAG_FD_CLOEXEC	(1<<0)
+#define I915_PERF_FLAG_FD_NONBLOCK	(1<<1)
+#define I915_PERF_FLAG_DISABLED		(1<<2)
+
+	/** The number of u64 (id, value) pairs */
+	__u32 num_properties;
+
+	/**
+	 * Pointer to array of u64 (id, value) pairs configuring the stream
+	 * to open.
+	 */
+	__u64 properties_ptr;
+};
+
+/*
+ * Enable data capture for a stream that was either opened in a disabled state
+ * via I915_PERF_FLAG_DISABLED or was later disabled via
+ * I915_PERF_IOCTL_DISABLE.
+ *
+ * It is intended to be cheaper to disable and enable a stream than it may be
+ * to close and re-open a stream with the same configuration.
+ *
+ * It's undefined whether any pending data for the stream will be lost.
+ *
+ * This ioctl is available in perf revision 1.
+ */
+#define I915_PERF_IOCTL_ENABLE	_IO('i', 0x0)
+
+/*
+ * Disable data capture for a stream.
+ *
+ * It is an error to try and read a stream that is disabled.
+ *
+ * This ioctl is available in perf revision 1.
+ */
+#define I915_PERF_IOCTL_DISABLE	_IO('i', 0x1)
+
+/*
+ * Change metrics_set captured by a stream.
+ *
+ * If the stream is bound to a specific context, the configuration change
+ * will performed __inline__ with that context such that it takes effect before
+ * the next execbuf submission.
+ *
+ * Returns the previously bound metrics set id, or a negative error code.
+ *
+ * This ioctl is available in perf revision 2.
+ */
+#define I915_PERF_IOCTL_CONFIG	_IO('i', 0x2)
+
+/*
+ * Common to all i915 perf records
+ */
+struct drm_i915_perf_record_header {
+	__u32 type;
+	__u16 pad;
+	__u16 size;
+};
+
+enum drm_i915_perf_record_type {
+
+	/**
+	 * Samples are the work horse record type whose contents are extensible
+	 * and defined when opening an i915 perf stream based on the given
+	 * properties.
+	 *
+	 * Boolean properties following the naming convention
+	 * DRM_I915_PERF_SAMPLE_xyz_PROP request the inclusion of 'xyz' data in
+	 * every sample.
+	 *
+	 * The order of these sample properties given by userspace has no
+	 * affect on the ordering of data within a sample. The order is
+	 * documented here.
+	 *
+	 * struct {
+	 *     struct drm_i915_perf_record_header header;
+	 *
+	 *     { u32 oa_report[]; } && DRM_I915_PERF_PROP_SAMPLE_OA
+	 * };
+	 */
+	DRM_I915_PERF_RECORD_SAMPLE = 1,
+
+	/*
+	 * Indicates that one or more OA reports were not written by the
+	 * hardware. This can happen for example if an MI_REPORT_PERF_COUNT
+	 * command collides with periodic sampling - which would be more likely
+	 * at higher sampling frequencies.
+	 */
+	DRM_I915_PERF_RECORD_OA_REPORT_LOST = 2,
+
+	/**
+	 * An error occurred that resulted in all pending OA reports being lost.
+	 */
+	DRM_I915_PERF_RECORD_OA_BUFFER_LOST = 3,
+
+	DRM_I915_PERF_RECORD_MAX /* non-ABI */
+};
+
+/**
+ * struct drm_i915_perf_oa_config
+ *
+ * Structure to upload perf dynamic configuration into the kernel.
+ */
+struct drm_i915_perf_oa_config {
+	/**
+	 * @uuid:
+	 *
+	 * String formatted like "%\08x-%\04x-%\04x-%\04x-%\012x"
+	 */
+	char uuid[36];
+
+	/**
+	 * @n_mux_regs:
+	 *
+	 * Number of mux regs in &mux_regs_ptr.
+	 */
+	__u32 n_mux_regs;
+
+	/**
+	 * @n_boolean_regs:
+	 *
+	 * Number of boolean regs in &boolean_regs_ptr.
+	 */
+	__u32 n_boolean_regs;
+
+	/**
+	 * @n_flex_regs:
+	 *
+	 * Number of flex regs in &flex_regs_ptr.
+	 */
+	__u32 n_flex_regs;
+
+	/**
+	 * @mux_regs_ptr:
+	 *
+	 * Pointer to tuples of u32 values (register address, value) for mux
+	 * registers.  Expected length of buffer is (2 * sizeof(u32) *
+	 * &n_mux_regs).
+	 */
+	__u64 mux_regs_ptr;
+
+	/**
+	 * @boolean_regs_ptr:
+	 *
+	 * Pointer to tuples of u32 values (register address, value) for mux
+	 * registers.  Expected length of buffer is (2 * sizeof(u32) *
+	 * &n_boolean_regs).
+	 */
+	__u64 boolean_regs_ptr;
+
+	/**
+	 * @flex_regs_ptr:
+	 *
+	 * Pointer to tuples of u32 values (register address, value) for mux
+	 * registers.  Expected length of buffer is (2 * sizeof(u32) *
+	 * &n_flex_regs).
+	 */
+	__u64 flex_regs_ptr;
+};
+
+/**
+ * struct drm_i915_query_item - An individual query for the kernel to process.
+ *
+ * The behaviour is determined by the @query_id. Note that exactly what
+ * @data_ptr is also depends on the specific @query_id.
+ */
+struct drm_i915_query_item {
+	/**
+	 * @query_id:
+	 *
+	 * The id for this query.  Currently accepted query IDs are:
+	 *  - %DRM_I915_QUERY_TOPOLOGY_INFO (see struct drm_i915_query_topology_info)
+	 *  - %DRM_I915_QUERY_ENGINE_INFO (see struct drm_i915_engine_info)
+	 *  - %DRM_I915_QUERY_PERF_CONFIG (see struct drm_i915_query_perf_config)
+	 *  - %DRM_I915_QUERY_MEMORY_REGIONS (see struct drm_i915_query_memory_regions)
+	 *  - %DRM_I915_QUERY_HWCONFIG_BLOB (see `GuC HWCONFIG blob uAPI`)
+	 *  - %DRM_I915_QUERY_GEOMETRY_SUBSLICES (see struct drm_i915_query_topology_info)
+	 *  - %DRM_I915_QUERY_GUC_SUBMISSION_VERSION (see struct drm_i915_query_guc_submission_version)
+	 */
+	__u64 query_id;
+#define DRM_I915_QUERY_TOPOLOGY_INFO		1
+#define DRM_I915_QUERY_ENGINE_INFO		2
+#define DRM_I915_QUERY_PERF_CONFIG		3
+#define DRM_I915_QUERY_MEMORY_REGIONS		4
+#define DRM_I915_QUERY_HWCONFIG_BLOB		5
+#define DRM_I915_QUERY_GEOMETRY_SUBSLICES	6
+#define DRM_I915_QUERY_GUC_SUBMISSION_VERSION	7
+/* Must be kept compact -- no holes and well documented */
+
+	/**
+	 * @length:
+	 *
+	 * When set to zero by userspace, this is filled with the size of the
+	 * data to be written at the @data_ptr pointer. The kernel sets this
+	 * value to a negative value to signal an error on a particular query
+	 * item.
+	 */
+	__s32 length;
+
+	/**
+	 * @flags:
+	 *
+	 * When &query_id == %DRM_I915_QUERY_TOPOLOGY_INFO, must be 0.
+	 *
+	 * When &query_id == %DRM_I915_QUERY_PERF_CONFIG, must be one of the
+	 * following:
+	 *
+	 *	- %DRM_I915_QUERY_PERF_CONFIG_LIST
+	 *      - %DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID
+	 *      - %DRM_I915_QUERY_PERF_CONFIG_FOR_UUID
+	 *
+	 * When &query_id == %DRM_I915_QUERY_GEOMETRY_SUBSLICES must contain
+	 * a struct i915_engine_class_instance that references a render engine.
+	 */
+	__u32 flags;
+#define DRM_I915_QUERY_PERF_CONFIG_LIST          1
+#define DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID 2
+#define DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_ID   3
+
+	/**
+	 * @data_ptr:
+	 *
+	 * Data will be written at the location pointed by @data_ptr when the
+	 * value of @length matches the length of the data to be written by the
+	 * kernel.
+	 */
+	__u64 data_ptr;
+};
+
+/**
+ * struct drm_i915_query - Supply an array of struct drm_i915_query_item for the
+ * kernel to fill out.
+ *
+ * Note that this is generally a two step process for each struct
+ * drm_i915_query_item in the array:
+ *
+ * 1. Call the DRM_IOCTL_I915_QUERY, giving it our array of struct
+ *    drm_i915_query_item, with &drm_i915_query_item.length set to zero. The
+ *    kernel will then fill in the size, in bytes, which tells userspace how
+ *    memory it needs to allocate for the blob(say for an array of properties).
+ *
+ * 2. Next we call DRM_IOCTL_I915_QUERY again, this time with the
+ *    &drm_i915_query_item.data_ptr equal to our newly allocated blob. Note that
+ *    the &drm_i915_query_item.length should still be the same as what the
+ *    kernel previously set. At this point the kernel can fill in the blob.
+ *
+ * Note that for some query items it can make sense for userspace to just pass
+ * in a buffer/blob equal to or larger than the required size. In this case only
+ * a single ioctl call is needed. For some smaller query items this can work
+ * quite well.
+ *
+ */
+struct drm_i915_query {
+	/** @num_items: The number of elements in the @items_ptr array */
+	__u32 num_items;
+
+	/**
+	 * @flags: Unused for now. Must be cleared to zero.
+	 */
+	__u32 flags;
+
+	/**
+	 * @items_ptr:
+	 *
+	 * Pointer to an array of struct drm_i915_query_item. The number of
+	 * array elements is @num_items.
+	 */
+	__u64 items_ptr;
+};
+
+/**
+ * struct drm_i915_query_topology_info
+ *
+ * Describes slice/subslice/EU information queried by
+ * %DRM_I915_QUERY_TOPOLOGY_INFO
+ */
+struct drm_i915_query_topology_info {
+	/**
+	 * @flags:
+	 *
+	 * Unused for now. Must be cleared to zero.
+	 */
+	__u16 flags;
+
+	/**
+	 * @max_slices:
+	 *
+	 * The number of bits used to express the slice mask.
+	 */
+	__u16 max_slices;
+
+	/**
+	 * @max_subslices:
+	 *
+	 * The number of bits used to express the subslice mask.
+	 */
+	__u16 max_subslices;
+
+	/**
+	 * @max_eus_per_subslice:
+	 *
+	 * The number of bits in the EU mask that correspond to a single
+	 * subslice's EUs.
+	 */
+	__u16 max_eus_per_subslice;
+
+	/**
+	 * @subslice_offset:
+	 *
+	 * Offset in data[] at which the subslice masks are stored.
+	 */
+	__u16 subslice_offset;
+
+	/**
+	 * @subslice_stride:
+	 *
+	 * Stride at which each of the subslice masks for each slice are
+	 * stored.
+	 */
+	__u16 subslice_stride;
+
+	/**
+	 * @eu_offset:
+	 *
+	 * Offset in data[] at which the EU masks are stored.
+	 */
+	__u16 eu_offset;
+
+	/**
+	 * @eu_stride:
+	 *
+	 * Stride at which each of the EU masks for each subslice are stored.
+	 */
+	__u16 eu_stride;
+
+	/**
+	 * @data:
+	 *
+	 * Contains 3 pieces of information :
+	 *
+	 * - The slice mask with one bit per slice telling whether a slice is
+	 *   available. The availability of slice X can be queried with the
+	 *   following formula :
+	 *
+	 *   .. code:: c
+	 *
+	 *      (data[X / 8] >> (X % 8)) & 1
+	 *
+	 *   Starting with Xe_HP platforms, Intel hardware no longer has
+	 *   traditional slices so i915 will always report a single slice
+	 *   (hardcoded slicemask = 0x1) which contains all of the platform's
+	 *   subslices.  I.e., the mask here does not reflect any of the newer
+	 *   hardware concepts such as "gslices" or "cslices" since userspace
+	 *   is capable of inferring those from the subslice mask.
+	 *
+	 * - The subslice mask for each slice with one bit per subslice telling
+	 *   whether a subslice is available.  Starting with Gen12 we use the
+	 *   term "subslice" to refer to what the hardware documentation
+	 *   describes as a "dual-subslices."  The availability of subslice Y
+	 *   in slice X can be queried with the following formula :
+	 *
+	 *   .. code:: c
+	 *
+	 *      (data[subslice_offset + X * subslice_stride + Y / 8] >> (Y % 8)) & 1
+	 *
+	 * - The EU mask for each subslice in each slice, with one bit per EU
+	 *   telling whether an EU is available. The availability of EU Z in
+	 *   subslice Y in slice X can be queried with the following formula :
+	 *
+	 *   .. code:: c
+	 *
+	 *      (data[eu_offset +
+	 *            (X * max_subslices + Y) * eu_stride +
+	 *            Z / 8
+	 *       ] >> (Z % 8)) & 1
+	 */
+	__u8 data[];
+};
+
+/**
+ * DOC: Engine Discovery uAPI
+ *
+ * Engine discovery uAPI is a way of enumerating physical engines present in a
+ * GPU associated with an open i915 DRM file descriptor. This supersedes the old
+ * way of using `DRM_IOCTL_I915_GETPARAM` and engine identifiers like
+ * `I915_PARAM_HAS_BLT`.
+ *
+ * The need for this interface came starting with Icelake and newer GPUs, which
+ * started to establish a pattern of having multiple engines of a same class,
+ * where not all instances were always completely functionally equivalent.
+ *
+ * Entry point for this uapi is `DRM_IOCTL_I915_QUERY` with the
+ * `DRM_I915_QUERY_ENGINE_INFO` as the queried item id.
+ *
+ * Example for getting the list of engines:
+ *
+ * .. code-block:: C
+ *
+ * 	struct drm_i915_query_engine_info *info;
+ * 	struct drm_i915_query_item item = {
+ * 		.query_id = DRM_I915_QUERY_ENGINE_INFO;
+ * 	};
+ * 	struct drm_i915_query query = {
+ * 		.num_items = 1,
+ * 		.items_ptr = (uintptr_t)&item,
+ * 	};
+ * 	int err, i;
+ *
+ * 	// First query the size of the blob we need, this needs to be large
+ * 	// enough to hold our array of engines. The kernel will fill out the
+ * 	// item.length for us, which is the number of bytes we need.
+ * 	//
+ *	// Alternatively a large buffer can be allocated straightaway enabling
+ * 	// querying in one pass, in which case item.length should contain the
+ * 	// length of the provided buffer.
+ * 	err = ioctl(fd, DRM_IOCTL_I915_QUERY, &query);
+ * 	if (err) ...
+ *
+ * 	info = calloc(1, item.length);
+ * 	// Now that we allocated the required number of bytes, we call the ioctl
+ * 	// again, this time with the data_ptr pointing to our newly allocated
+ * 	// blob, which the kernel can then populate with info on all engines.
+ *	item.data_ptr = (uintptr_t)&info;
+ *
+ * 	err = ioctl(fd, DRM_IOCTL_I915_QUERY, &query);
+ * 	if (err) ...
+ *
+ * 	// We can now access each engine in the array
+ * 	for (i = 0; i < info->num_engines; i++) {
+ * 		struct drm_i915_engine_info einfo = info->engines[i];
+ * 		u16 class = einfo.engine.class;
+ * 		u16 instance = einfo.engine.instance;
+ * 		....
+ * 	}
+ *
+ * 	free(info);
+ *
+ * Each of the enumerated engines, apart from being defined by its class and
+ * instance (see `struct i915_engine_class_instance`), also can have flags and
+ * capabilities defined as documented in i915_drm.h.
+ *
+ * For instance video engines which support HEVC encoding will have the
+ * `I915_VIDEO_CLASS_CAPABILITY_HEVC` capability bit set.
+ *
+ * Engine discovery only fully comes to its own when combined with the new way
+ * of addressing engines when submitting batch buffers using contexts with
+ * engine maps configured.
+ */
+
+/**
+ * struct drm_i915_engine_info
+ *
+ * Describes one engine and its capabilities as known to the driver.
+ */
+struct drm_i915_engine_info {
+	/** @engine: Engine class and instance. */
+	struct i915_engine_class_instance engine;
+
+	/** @rsvd0: Reserved field. */
+	__u32 rsvd0;
+
+	/** @flags: Engine flags. */
+	__u64 flags;
+#define I915_ENGINE_INFO_HAS_LOGICAL_INSTANCE		(1 << 0)
+
+	/** @capabilities: Capabilities of this engine. */
+	__u64 capabilities;
+#define I915_VIDEO_CLASS_CAPABILITY_HEVC		(1 << 0)
+#define I915_VIDEO_AND_ENHANCE_CLASS_CAPABILITY_SFC	(1 << 1)
+
+	/** @logical_instance: Logical instance of engine */
+	__u16 logical_instance;
+
+	/** @rsvd1: Reserved fields. */
+	__u16 rsvd1[3];
+	/** @rsvd2: Reserved fields. */
+	__u64 rsvd2[3];
+};
+
+/**
+ * struct drm_i915_query_engine_info
+ *
+ * Engine info query enumerates all engines known to the driver by filling in
+ * an array of struct drm_i915_engine_info structures.
+ */
+struct drm_i915_query_engine_info {
+	/** @num_engines: Number of struct drm_i915_engine_info structs following. */
+	__u32 num_engines;
+
+	/** @rsvd: MBZ */
+	__u32 rsvd[3];
+
+	/** @engines: Marker for drm_i915_engine_info structures. */
+	struct drm_i915_engine_info engines[];
+};
+
+/**
+ * struct drm_i915_query_perf_config
+ *
+ * Data written by the kernel with query %DRM_I915_QUERY_PERF_CONFIG and
+ * %DRM_I915_QUERY_GEOMETRY_SUBSLICES.
+ */
+struct drm_i915_query_perf_config {
+	union {
+		/**
+		 * @n_configs:
+		 *
+		 * When &drm_i915_query_item.flags ==
+		 * %DRM_I915_QUERY_PERF_CONFIG_LIST, i915 sets this fields to
+		 * the number of configurations available.
+		 */
+		__u64 n_configs;
+
+		/**
+		 * @config:
+		 *
+		 * When &drm_i915_query_item.flags ==
+		 * %DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_ID, i915 will use the
+		 * value in this field as configuration identifier to decide
+		 * what data to write into config_ptr.
+		 */
+		__u64 config;
+
+		/**
+		 * @uuid:
+		 *
+		 * When &drm_i915_query_item.flags ==
+		 * %DRM_I915_QUERY_PERF_CONFIG_DATA_FOR_UUID, i915 will use the
+		 * value in this field as configuration identifier to decide
+		 * what data to write into config_ptr.
+		 *
+		 * String formatted like "%08x-%04x-%04x-%04x-%012x"
+		 */
+		char uuid[36];
+	};
+
+	/**
+	 * @flags:
+	 *
+	 * Unused for now. Must be cleared to zero.
+	 */
+	__u32 flags;
+
+	/**
+	 * @data:
+	 *
+	 * When &drm_i915_query_item.flags == %DRM_I915_QUERY_PERF_CONFIG_LIST,
+	 * i915 will write an array of __u64 of configuration identifiers.
+	 *
+	 * When &drm_i915_query_item.flags == %DRM_I915_QUERY_PERF_CONFIG_DATA,
+	 * i915 will write a struct drm_i915_perf_oa_config. If the following
+	 * fields of struct drm_i915_perf_oa_config are not set to 0, i915 will
+	 * write into the associated pointers the values of submitted when the
+	 * configuration was created :
+	 *
+	 *  - &drm_i915_perf_oa_config.n_mux_regs
+	 *  - &drm_i915_perf_oa_config.n_boolean_regs
+	 *  - &drm_i915_perf_oa_config.n_flex_regs
+	 */
+	__u8 data[];
+};
+
+/**
+ * enum drm_i915_gem_memory_class - Supported memory classes
+ */
+enum drm_i915_gem_memory_class {
+	/** @I915_MEMORY_CLASS_SYSTEM: System memory */
+	I915_MEMORY_CLASS_SYSTEM = 0,
+	/** @I915_MEMORY_CLASS_DEVICE: Device local-memory */
+	I915_MEMORY_CLASS_DEVICE,
+};
+
+/**
+ * struct drm_i915_gem_memory_class_instance - Identify particular memory region
+ */
+struct drm_i915_gem_memory_class_instance {
+	/** @memory_class: See enum drm_i915_gem_memory_class */
+	__u16 memory_class;
+
+	/** @memory_instance: Which instance */
+	__u16 memory_instance;
+};
+
+/**
+ * struct drm_i915_memory_region_info - Describes one region as known to the
+ * driver.
+ *
+ * Note this is using both struct drm_i915_query_item and struct drm_i915_query.
+ * For this new query we are adding the new query id DRM_I915_QUERY_MEMORY_REGIONS
+ * at &drm_i915_query_item.query_id.
+ */
+struct drm_i915_memory_region_info {
+	/** @region: The class:instance pair encoding */
+	struct drm_i915_gem_memory_class_instance region;
+
+	/** @rsvd0: MBZ */
+	__u32 rsvd0;
+
+	/**
+	 * @probed_size: Memory probed by the driver
+	 *
+	 * Note that it should not be possible to ever encounter a zero value
+	 * here, also note that no current region type will ever return -1 here.
+	 * Although for future region types, this might be a possibility. The
+	 * same applies to the other size fields.
+	 */
+	__u64 probed_size;
+
+	/**
+	 * @unallocated_size: Estimate of memory remaining
+	 *
+	 * Requires CAP_PERFMON or CAP_SYS_ADMIN to get reliable accounting.
+	 * Without this (or if this is an older kernel) the value here will
+	 * always equal the @probed_size. Note this is only currently tracked
+	 * for I915_MEMORY_CLASS_DEVICE regions (for other types the value here
+	 * will always equal the @probed_size).
+	 */
+	__u64 unallocated_size;
+
+	union {
+		/** @rsvd1: MBZ */
+		__u64 rsvd1[8];
+		struct {
+			/**
+			 * @probed_cpu_visible_size: Memory probed by the driver
+			 * that is CPU accessible.
+			 *
+			 * This will be always be <= @probed_size, and the
+			 * remainder (if there is any) will not be CPU
+			 * accessible.
+			 *
+			 * On systems without small BAR, the @probed_size will
+			 * always equal the @probed_cpu_visible_size, since all
+			 * of it will be CPU accessible.
+			 *
+			 * Note this is only tracked for
+			 * I915_MEMORY_CLASS_DEVICE regions (for other types the
+			 * value here will always equal the @probed_size).
+			 *
+			 * Note that if the value returned here is zero, then
+			 * this must be an old kernel which lacks the relevant
+			 * small-bar uAPI support (including
+			 * I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS), but on
+			 * such systems we should never actually end up with a
+			 * small BAR configuration, assuming we are able to load
+			 * the kernel module. Hence it should be safe to treat
+			 * this the same as when @probed_cpu_visible_size ==
+			 * @probed_size.
+			 */
+			__u64 probed_cpu_visible_size;
+
+			/**
+			 * @unallocated_cpu_visible_size: Estimate of CPU
+			 * visible memory remaining.
+			 *
+			 * Note this is only tracked for
+			 * I915_MEMORY_CLASS_DEVICE regions (for other types the
+			 * value here will always equal the
+			 * @probed_cpu_visible_size).
+			 *
+			 * Requires CAP_PERFMON or CAP_SYS_ADMIN to get reliable
+			 * accounting.  Without this the value here will always
+			 * equal the @probed_cpu_visible_size. Note this is only
+			 * currently tracked for I915_MEMORY_CLASS_DEVICE
+			 * regions (for other types the value here will also
+			 * always equal the @probed_cpu_visible_size).
+			 *
+			 * If this is an older kernel the value here will be
+			 * zero, see also @probed_cpu_visible_size.
+			 */
+			__u64 unallocated_cpu_visible_size;
+		};
+	};
+};
+
+/**
+ * struct drm_i915_query_memory_regions
+ *
+ * The region info query enumerates all regions known to the driver by filling
+ * in an array of struct drm_i915_memory_region_info structures.
+ *
+ * Example for getting the list of supported regions:
+ *
+ * .. code-block:: C
+ *
+ *	struct drm_i915_query_memory_regions *info;
+ *	struct drm_i915_query_item item = {
+ *		.query_id = DRM_I915_QUERY_MEMORY_REGIONS;
+ *	};
+ *	struct drm_i915_query query = {
+ *		.num_items = 1,
+ *		.items_ptr = (uintptr_t)&item,
+ *	};
+ *	int err, i;
+ *
+ *	// First query the size of the blob we need, this needs to be large
+ *	// enough to hold our array of regions. The kernel will fill out the
+ *	// item.length for us, which is the number of bytes we need.
+ *	err = ioctl(fd, DRM_IOCTL_I915_QUERY, &query);
+ *	if (err) ...
+ *
+ *	info = calloc(1, item.length);
+ *	// Now that we allocated the required number of bytes, we call the ioctl
+ *	// again, this time with the data_ptr pointing to our newly allocated
+ *	// blob, which the kernel can then populate with the all the region info.
+ *	item.data_ptr = (uintptr_t)&info,
+ *
+ *	err = ioctl(fd, DRM_IOCTL_I915_QUERY, &query);
+ *	if (err) ...
+ *
+ *	// We can now access each region in the array
+ *	for (i = 0; i < info->num_regions; i++) {
+ *		struct drm_i915_memory_region_info mr = info->regions[i];
+ *		u16 class = mr.region.class;
+ *		u16 instance = mr.region.instance;
+ *
+ *		....
+ *	}
+ *
+ *	free(info);
+ */
+struct drm_i915_query_memory_regions {
+	/** @num_regions: Number of supported regions */
+	__u32 num_regions;
+
+	/** @rsvd: MBZ */
+	__u32 rsvd[3];
+
+	/** @regions: Info about each supported region */
+	struct drm_i915_memory_region_info regions[];
+};
+
+/**
+ * struct drm_i915_query_guc_submission_version - query GuC submission interface version
+ */
+struct drm_i915_query_guc_submission_version {
+	__u32 branch;
+	__u32 major;
+	__u32 minor;
+	__u32 patch;
+};
+
+/**
+ * DOC: GuC HWCONFIG blob uAPI
+ *
+ * The GuC produces a blob with information about the current device.
+ * i915 reads this blob from GuC and makes it available via this uAPI.
+ *
+ * The format and meaning of the blob content are documented in the
+ * Programmer's Reference Manual.
+ */
+
+/**
+ * struct drm_i915_gem_create_ext - Existing gem_create behaviour, with added
+ * extension support using struct i915_user_extension.
+ *
+ * Note that new buffer flags should be added here, at least for the stuff that
+ * is immutable. Previously we would have two ioctls, one to create the object
+ * with gem_create, and another to apply various parameters, however this
+ * creates some ambiguity for the params which are considered immutable. Also in
+ * general we're phasing out the various SET/GET ioctls.
+ */
+struct drm_i915_gem_create_ext {
+	/**
+	 * @size: Requested size for the object.
+	 *
+	 * The (page-aligned) allocated size for the object will be returned.
+	 *
+	 * On platforms like DG2/ATS the kernel will always use 64K or larger
+	 * pages for I915_MEMORY_CLASS_DEVICE. The kernel also requires a
+	 * minimum of 64K GTT alignment for such objects.
+	 *
+	 * NOTE: Previously the ABI here required a minimum GTT alignment of 2M
+	 * on DG2/ATS, due to how the hardware implemented 64K GTT page support,
+	 * where we had the following complications:
+	 *
+	 *   1) The entire PDE (which covers a 2MB virtual address range), must
+	 *   contain only 64K PTEs, i.e mixing 4K and 64K PTEs in the same
+	 *   PDE is forbidden by the hardware.
+	 *
+	 *   2) We still need to support 4K PTEs for I915_MEMORY_CLASS_SYSTEM
+	 *   objects.
+	 *
+	 * However on actual production HW this was completely changed to now
+	 * allow setting a TLB hint at the PTE level (see PS64), which is a lot
+	 * more flexible than the above. With this the 2M restriction was
+	 * dropped where we now only require 64K.
+	 */
+	__u64 size;
+
+	/**
+	 * @handle: Returned handle for the object.
+	 *
+	 * Object handles are nonzero.
+	 */
+	__u32 handle;
+
+	/**
+	 * @flags: Optional flags.
+	 *
+	 * Supported values:
+	 *
+	 * I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS - Signal to the kernel that
+	 * the object will need to be accessed via the CPU.
+	 *
+	 * Only valid when placing objects in I915_MEMORY_CLASS_DEVICE, and only
+	 * strictly required on configurations where some subset of the device
+	 * memory is directly visible/mappable through the CPU (which we also
+	 * call small BAR), like on some DG2+ systems. Note that this is quite
+	 * undesirable, but due to various factors like the client CPU, BIOS etc
+	 * it's something we can expect to see in the wild. See
+	 * &drm_i915_memory_region_info.probed_cpu_visible_size for how to
+	 * determine if this system applies.
+	 *
+	 * Note that one of the placements MUST be I915_MEMORY_CLASS_SYSTEM, to
+	 * ensure the kernel can always spill the allocation to system memory,
+	 * if the object can't be allocated in the mappable part of
+	 * I915_MEMORY_CLASS_DEVICE.
+	 *
+	 * Also note that since the kernel only supports flat-CCS on objects
+	 * that can *only* be placed in I915_MEMORY_CLASS_DEVICE, we therefore
+	 * don't support I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS together with
+	 * flat-CCS.
+	 *
+	 * Without this hint, the kernel will assume that non-mappable
+	 * I915_MEMORY_CLASS_DEVICE is preferred for this object. Note that the
+	 * kernel can still migrate the object to the mappable part, as a last
+	 * resort, if userspace ever CPU faults this object, but this might be
+	 * expensive, and so ideally should be avoided.
+	 *
+	 * On older kernels which lack the relevant small-bar uAPI support (see
+	 * also &drm_i915_memory_region_info.probed_cpu_visible_size),
+	 * usage of the flag will result in an error, but it should NEVER be
+	 * possible to end up with a small BAR configuration, assuming we can
+	 * also successfully load the i915 kernel module. In such cases the
+	 * entire I915_MEMORY_CLASS_DEVICE region will be CPU accessible, and as
+	 * such there are zero restrictions on where the object can be placed.
+	 */
+#define I915_GEM_CREATE_EXT_FLAG_NEEDS_CPU_ACCESS (1 << 0)
+	__u32 flags;
+
+	/**
+	 * @extensions: The chain of extensions to apply to this object.
+	 *
+	 * This will be useful in the future when we need to support several
+	 * different extensions, and we need to apply more than one when
+	 * creating the object. See struct i915_user_extension.
+	 *
+	 * If we don't supply any extensions then we get the same old gem_create
+	 * behaviour.
+	 *
+	 * For I915_GEM_CREATE_EXT_MEMORY_REGIONS usage see
+	 * struct drm_i915_gem_create_ext_memory_regions.
+	 *
+	 * For I915_GEM_CREATE_EXT_PROTECTED_CONTENT usage see
+	 * struct drm_i915_gem_create_ext_protected_content.
+	 *
+	 * For I915_GEM_CREATE_EXT_SET_PAT usage see
+	 * struct drm_i915_gem_create_ext_set_pat.
+	 */
+#define I915_GEM_CREATE_EXT_MEMORY_REGIONS 0
+#define I915_GEM_CREATE_EXT_PROTECTED_CONTENT 1
+#define I915_GEM_CREATE_EXT_SET_PAT 2
+	__u64 extensions;
+};
+
+/**
+ * struct drm_i915_gem_create_ext_memory_regions - The
+ * I915_GEM_CREATE_EXT_MEMORY_REGIONS extension.
+ *
+ * Set the object with the desired set of placements/regions in priority
+ * order. Each entry must be unique and supported by the device.
+ *
+ * This is provided as an array of struct drm_i915_gem_memory_class_instance, or
+ * an equivalent layout of class:instance pair encodings. See struct
+ * drm_i915_query_memory_regions and DRM_I915_QUERY_MEMORY_REGIONS for how to
+ * query the supported regions for a device.
+ *
+ * As an example, on discrete devices, if we wish to set the placement as
+ * device local-memory we can do something like:
+ *
+ * .. code-block:: C
+ *
+ *	struct drm_i915_gem_memory_class_instance region_lmem = {
+ *              .memory_class = I915_MEMORY_CLASS_DEVICE,
+ *              .memory_instance = 0,
+ *      };
+ *      struct drm_i915_gem_create_ext_memory_regions regions = {
+ *              .base = { .name = I915_GEM_CREATE_EXT_MEMORY_REGIONS },
+ *              .regions = (uintptr_t)&region_lmem,
+ *              .num_regions = 1,
+ *      };
+ *      struct drm_i915_gem_create_ext create_ext = {
+ *              .size = 16 * PAGE_SIZE,
+ *              .extensions = (uintptr_t)&regions,
+ *      };
+ *
+ *      int err = ioctl(fd, DRM_IOCTL_I915_GEM_CREATE_EXT, &create_ext);
+ *      if (err) ...
+ *
+ * At which point we get the object handle in &drm_i915_gem_create_ext.handle,
+ * along with the final object size in &drm_i915_gem_create_ext.size, which
+ * should account for any rounding up, if required.
+ *
+ * Note that userspace has no means of knowing the current backing region
+ * for objects where @num_regions is larger than one. The kernel will only
+ * ensure that the priority order of the @regions array is honoured, either
+ * when initially placing the object, or when moving memory around due to
+ * memory pressure
+ *
+ * On Flat-CCS capable HW, compression is supported for the objects residing
+ * in I915_MEMORY_CLASS_DEVICE. When such objects (compressed) have other
+ * memory class in @regions and migrated (by i915, due to memory
+ * constraints) to the non I915_MEMORY_CLASS_DEVICE region, then i915 needs to
+ * decompress the content. But i915 doesn't have the required information to
+ * decompress the userspace compressed objects.
+ *
+ * So i915 supports Flat-CCS, on the objects which can reside only on
+ * I915_MEMORY_CLASS_DEVICE regions.
+ */
+struct drm_i915_gem_create_ext_memory_regions {
+	/** @base: Extension link. See struct i915_user_extension. */
+	struct i915_user_extension base;
+
+	/** @pad: MBZ */
+	__u32 pad;
+	/** @num_regions: Number of elements in the @regions array. */
+	__u32 num_regions;
+	/**
+	 * @regions: The regions/placements array.
+	 *
+	 * An array of struct drm_i915_gem_memory_class_instance.
+	 */
+	__u64 regions;
+};
+
+/**
+ * struct drm_i915_gem_create_ext_protected_content - The
+ * I915_OBJECT_PARAM_PROTECTED_CONTENT extension.
+ *
+ * If this extension is provided, buffer contents are expected to be protected
+ * by PXP encryption and require decryption for scan out and processing. This
+ * is only possible on platforms that have PXP enabled, on all other scenarios
+ * using this extension will cause the ioctl to fail and return -ENODEV. The
+ * flags parameter is reserved for future expansion and must currently be set
+ * to zero.
+ *
+ * The buffer contents are considered invalid after a PXP session teardown.
+ *
+ * The encryption is guaranteed to be processed correctly only if the object
+ * is submitted with a context created using the
+ * I915_CONTEXT_PARAM_PROTECTED_CONTENT flag. This will also enable extra checks
+ * at submission time on the validity of the objects involved.
+ *
+ * Below is an example on how to create a protected object:
+ *
+ * .. code-block:: C
+ *
+ *      struct drm_i915_gem_create_ext_protected_content protected_ext = {
+ *              .base = { .name = I915_GEM_CREATE_EXT_PROTECTED_CONTENT },
+ *              .flags = 0,
+ *      };
+ *      struct drm_i915_gem_create_ext create_ext = {
+ *              .size = PAGE_SIZE,
+ *              .extensions = (uintptr_t)&protected_ext,
+ *      };
+ *
+ *      int err = ioctl(fd, DRM_IOCTL_I915_GEM_CREATE_EXT, &create_ext);
+ *      if (err) ...
+ */
+struct drm_i915_gem_create_ext_protected_content {
+	/** @base: Extension link. See struct i915_user_extension. */
+	struct i915_user_extension base;
+	/** @flags: reserved for future usage, currently MBZ */
+	__u32 flags;
+};
+
+/**
+ * struct drm_i915_gem_create_ext_set_pat - The
+ * I915_GEM_CREATE_EXT_SET_PAT extension.
+ *
+ * If this extension is provided, the specified caching policy (PAT index) is
+ * applied to the buffer object.
+ *
+ * Below is an example on how to create an object with specific caching policy:
+ *
+ * .. code-block:: C
+ *
+ *      struct drm_i915_gem_create_ext_set_pat set_pat_ext = {
+ *              .base = { .name = I915_GEM_CREATE_EXT_SET_PAT },
+ *              .pat_index = 0,
+ *      };
+ *      struct drm_i915_gem_create_ext create_ext = {
+ *              .size = PAGE_SIZE,
+ *              .extensions = (uintptr_t)&set_pat_ext,
+ *      };
+ *
+ *      int err = ioctl(fd, DRM_IOCTL_I915_GEM_CREATE_EXT, &create_ext);
+ *      if (err) ...
+ */
+struct drm_i915_gem_create_ext_set_pat {
+	/** @base: Extension link. See struct i915_user_extension. */
+	struct i915_user_extension base;
+	/**
+	 * @pat_index: PAT index to be set
+	 * PAT index is a bit field in Page Table Entry to control caching
+	 * behaviors for GPU accesses. The definition of PAT index is
+	 * platform dependent and can be found in hardware specifications,
+	 */
+	__u32 pat_index;
+	/** @rsvd: reserved for future use */
+	__u32 rsvd;
+};
+
+/* ID of the protected content session managed by i915 when PXP is active */
+#define I915_PROTECTED_CONTENT_DEFAULT_SESSION 0xf
+
+#if defined(__cplusplus)
+}
+#endif
+
+#endif /* _I915_DRM_H_ */

+ 786 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/i915_pciids.h

@@ -0,0 +1,786 @@
+/*
+ * Copyright 2013 Intel Corporation
+ * All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sub license, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial portions
+ * of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+#ifndef _I915_PCIIDS_H
+#define _I915_PCIIDS_H
+
+/*
+ * A pci_device_id struct {
+ *	__u32 vendor, device;
+ *      __u32 subvendor, subdevice;
+ *	__u32 class, class_mask;
+ *	kernel_ulong_t driver_data;
+ * };
+ * Don't use C99 here because "class" is reserved and we want to
+ * give userspace flexibility.
+ */
+#define INTEL_VGA_DEVICE(id, info) { \
+	0x8086,	id, \
+	~0, ~0, \
+	0x030000, 0xff0000, \
+	(unsigned long) info }
+
+#define INTEL_QUANTA_VGA_DEVICE(info) { \
+	0x8086,	0x16a, \
+	0x152d,	0x8990, \
+	0x030000, 0xff0000, \
+	(unsigned long) info }
+
+#define INTEL_I810_IDS(MACRO__, ...) \
+	MACRO__(0x7121, ## __VA_ARGS__), /* I810 */ \
+	MACRO__(0x7123, ## __VA_ARGS__), /* I810_DC100 */ \
+	MACRO__(0x7125, ## __VA_ARGS__)  /* I810_E */
+
+#define INTEL_I815_IDS(MACRO__, ...) \
+	MACRO__(0x1132, ## __VA_ARGS__)  /* I815*/
+
+#define INTEL_I830_IDS(MACRO__, ...) \
+	MACRO__(0x3577, ## __VA_ARGS__)
+
+#define INTEL_I845G_IDS(MACRO__, ...) \
+	MACRO__(0x2562, ## __VA_ARGS__)
+
+#define INTEL_I85X_IDS(MACRO__, ...) \
+	MACRO__(0x3582, ## __VA_ARGS__), /* I855_GM */ \
+	MACRO__(0x358e, ## __VA_ARGS__)
+
+#define INTEL_I865G_IDS(MACRO__, ...) \
+	MACRO__(0x2572, ## __VA_ARGS__) /* I865_G */
+
+#define INTEL_I915G_IDS(MACRO__, ...) \
+	MACRO__(0x2582, ## __VA_ARGS__), /* I915_G */ \
+	MACRO__(0x258a, ## __VA_ARGS__)  /* E7221_G */
+
+#define INTEL_I915GM_IDS(MACRO__, ...) \
+	MACRO__(0x2592, ## __VA_ARGS__) /* I915_GM */
+
+#define INTEL_I945G_IDS(MACRO__, ...) \
+	MACRO__(0x2772, ## __VA_ARGS__) /* I945_G */
+
+#define INTEL_I945GM_IDS(MACRO__, ...) \
+	MACRO__(0x27a2, ## __VA_ARGS__), /* I945_GM */ \
+	MACRO__(0x27ae, ## __VA_ARGS__)  /* I945_GME */
+
+#define INTEL_I965G_IDS(MACRO__, ...) \
+	MACRO__(0x2972, ## __VA_ARGS__), /* I946_GZ */ \
+	MACRO__(0x2982, ## __VA_ARGS__),	/* G35_G */ \
+	MACRO__(0x2992, ## __VA_ARGS__),	/* I965_Q */ \
+	MACRO__(0x29a2, ## __VA_ARGS__)	/* I965_G */
+
+#define INTEL_G33_IDS(MACRO__, ...) \
+	MACRO__(0x29b2, ## __VA_ARGS__), /* Q35_G */ \
+	MACRO__(0x29c2, ## __VA_ARGS__),	/* G33_G */ \
+	MACRO__(0x29d2, ## __VA_ARGS__)	/* Q33_G */
+
+#define INTEL_I965GM_IDS(MACRO__, ...) \
+	MACRO__(0x2a02, ## __VA_ARGS__),	/* I965_GM */ \
+	MACRO__(0x2a12, ## __VA_ARGS__)  /* I965_GME */
+
+#define INTEL_GM45_IDS(MACRO__, ...) \
+	MACRO__(0x2a42, ## __VA_ARGS__) /* GM45_G */
+
+#define INTEL_G45_IDS(MACRO__, ...) \
+	MACRO__(0x2e02, ## __VA_ARGS__), /* IGD_E_G */ \
+	MACRO__(0x2e12, ## __VA_ARGS__), /* Q45_G */ \
+	MACRO__(0x2e22, ## __VA_ARGS__), /* G45_G */ \
+	MACRO__(0x2e32, ## __VA_ARGS__), /* G41_G */ \
+	MACRO__(0x2e42, ## __VA_ARGS__), /* B43_G */ \
+	MACRO__(0x2e92, ## __VA_ARGS__)	/* B43_G.1 */
+
+#define INTEL_PNV_G_IDS(MACRO__, ...) \
+	MACRO__(0xa001, ## __VA_ARGS__)
+
+#define INTEL_PNV_M_IDS(MACRO__, ...) \
+	MACRO__(0xa011, ## __VA_ARGS__)
+
+#define INTEL_PNV_IDS(MACRO__, ...) \
+	INTEL_PNV_G_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_PNV_M_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_ILK_D_IDS(MACRO__, ...) \
+	MACRO__(0x0042, ## __VA_ARGS__)
+
+#define INTEL_ILK_M_IDS(MACRO__, ...) \
+	MACRO__(0x0046, ## __VA_ARGS__)
+
+#define INTEL_ILK_IDS(MACRO__, ...) \
+	INTEL_ILK_D_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_ILK_M_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_SNB_D_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x0102, ## __VA_ARGS__), \
+	MACRO__(0x010A, ## __VA_ARGS__)
+
+#define INTEL_SNB_D_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x0112, ## __VA_ARGS__), \
+	MACRO__(0x0122, ## __VA_ARGS__)
+
+#define INTEL_SNB_D_IDS(MACRO__, ...) \
+	INTEL_SNB_D_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_SNB_D_GT2_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_SNB_M_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x0106, ## __VA_ARGS__)
+
+#define INTEL_SNB_M_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x0116, ## __VA_ARGS__), \
+	MACRO__(0x0126, ## __VA_ARGS__)
+
+#define INTEL_SNB_M_IDS(MACRO__, ...) \
+	INTEL_SNB_M_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_SNB_M_GT2_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_SNB_IDS(MACRO__, ...) \
+	INTEL_SNB_D_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_SNB_M_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_IVB_M_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x0156, ## __VA_ARGS__) /* GT1 mobile */
+
+#define INTEL_IVB_M_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x0166, ## __VA_ARGS__) /* GT2 mobile */
+
+#define INTEL_IVB_M_IDS(MACRO__, ...) \
+	INTEL_IVB_M_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_IVB_M_GT2_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_IVB_D_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x0152, ## __VA_ARGS__), /* GT1 desktop */ \
+	MACRO__(0x015a, ## __VA_ARGS__)  /* GT1 server */
+
+#define INTEL_IVB_D_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x0162, ## __VA_ARGS__), /* GT2 desktop */ \
+	MACRO__(0x016a, ## __VA_ARGS__)  /* GT2 server */
+
+#define INTEL_IVB_D_IDS(MACRO__, ...) \
+	INTEL_IVB_D_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_IVB_D_GT2_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_IVB_IDS(MACRO__, ...) \
+	INTEL_IVB_M_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_IVB_D_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_IVB_Q_IDS(MACRO__, ...) \
+	INTEL_QUANTA_VGA_DEVICE(__VA_ARGS__) /* Quanta transcode */
+
+#define INTEL_HSW_ULT_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x0A02, ## __VA_ARGS__), /* ULT GT1 desktop */ \
+	MACRO__(0x0A06, ## __VA_ARGS__), /* ULT GT1 mobile */ \
+	MACRO__(0x0A0A, ## __VA_ARGS__), /* ULT GT1 server */ \
+	MACRO__(0x0A0B, ## __VA_ARGS__)  /* ULT GT1 reserved */
+
+#define INTEL_HSW_ULX_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x0A0E, ## __VA_ARGS__) /* ULX GT1 mobile */
+
+#define INTEL_HSW_GT1_IDS(MACRO__, ...) \
+	INTEL_HSW_ULT_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_HSW_ULX_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x0402, ## __VA_ARGS__), /* GT1 desktop */ \
+	MACRO__(0x0406, ## __VA_ARGS__), /* GT1 mobile */ \
+	MACRO__(0x040A, ## __VA_ARGS__), /* GT1 server */ \
+	MACRO__(0x040B, ## __VA_ARGS__), /* GT1 reserved */ \
+	MACRO__(0x040E, ## __VA_ARGS__), /* GT1 reserved */ \
+	MACRO__(0x0C02, ## __VA_ARGS__), /* SDV GT1 desktop */ \
+	MACRO__(0x0C06, ## __VA_ARGS__), /* SDV GT1 mobile */ \
+	MACRO__(0x0C0A, ## __VA_ARGS__), /* SDV GT1 server */ \
+	MACRO__(0x0C0B, ## __VA_ARGS__), /* SDV GT1 reserved */ \
+	MACRO__(0x0C0E, ## __VA_ARGS__), /* SDV GT1 reserved */ \
+	MACRO__(0x0D02, ## __VA_ARGS__), /* CRW GT1 desktop */ \
+	MACRO__(0x0D06, ## __VA_ARGS__), /* CRW GT1 mobile */ \
+	MACRO__(0x0D0A, ## __VA_ARGS__), /* CRW GT1 server */ \
+	MACRO__(0x0D0B, ## __VA_ARGS__), /* CRW GT1 reserved */ \
+	MACRO__(0x0D0E, ## __VA_ARGS__)  /* CRW GT1 reserved */
+
+#define INTEL_HSW_ULT_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x0A12, ## __VA_ARGS__), /* ULT GT2 desktop */ \
+	MACRO__(0x0A16, ## __VA_ARGS__), /* ULT GT2 mobile */ \
+	MACRO__(0x0A1A, ## __VA_ARGS__), /* ULT GT2 server */ \
+	MACRO__(0x0A1B, ## __VA_ARGS__)  /* ULT GT2 reserved */ \
+
+#define INTEL_HSW_ULX_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x0A1E, ## __VA_ARGS__) /* ULX GT2 mobile */ \
+
+#define INTEL_HSW_GT2_IDS(MACRO__, ...) \
+	INTEL_HSW_ULT_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_HSW_ULX_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x0412, ## __VA_ARGS__), /* GT2 desktop */ \
+	MACRO__(0x0416, ## __VA_ARGS__), /* GT2 mobile */ \
+	MACRO__(0x041A, ## __VA_ARGS__), /* GT2 server */ \
+	MACRO__(0x041B, ## __VA_ARGS__), /* GT2 reserved */ \
+	MACRO__(0x041E, ## __VA_ARGS__), /* GT2 reserved */ \
+	MACRO__(0x0C12, ## __VA_ARGS__), /* SDV GT2 desktop */ \
+	MACRO__(0x0C16, ## __VA_ARGS__), /* SDV GT2 mobile */ \
+	MACRO__(0x0C1A, ## __VA_ARGS__), /* SDV GT2 server */ \
+	MACRO__(0x0C1B, ## __VA_ARGS__), /* SDV GT2 reserved */ \
+	MACRO__(0x0C1E, ## __VA_ARGS__), /* SDV GT2 reserved */ \
+	MACRO__(0x0D12, ## __VA_ARGS__), /* CRW GT2 desktop */ \
+	MACRO__(0x0D16, ## __VA_ARGS__), /* CRW GT2 mobile */ \
+	MACRO__(0x0D1A, ## __VA_ARGS__), /* CRW GT2 server */ \
+	MACRO__(0x0D1B, ## __VA_ARGS__), /* CRW GT2 reserved */ \
+	MACRO__(0x0D1E, ## __VA_ARGS__)  /* CRW GT2 reserved */
+
+#define INTEL_HSW_ULT_GT3_IDS(MACRO__, ...) \
+	MACRO__(0x0A22, ## __VA_ARGS__), /* ULT GT3 desktop */ \
+	MACRO__(0x0A26, ## __VA_ARGS__), /* ULT GT3 mobile */ \
+	MACRO__(0x0A2A, ## __VA_ARGS__), /* ULT GT3 server */ \
+	MACRO__(0x0A2B, ## __VA_ARGS__), /* ULT GT3 reserved */ \
+	MACRO__(0x0A2E, ## __VA_ARGS__)  /* ULT GT3 reserved */
+
+#define INTEL_HSW_GT3_IDS(MACRO__, ...) \
+	INTEL_HSW_ULT_GT3_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x0422, ## __VA_ARGS__), /* GT3 desktop */ \
+	MACRO__(0x0426, ## __VA_ARGS__), /* GT3 mobile */ \
+	MACRO__(0x042A, ## __VA_ARGS__), /* GT3 server */ \
+	MACRO__(0x042B, ## __VA_ARGS__), /* GT3 reserved */ \
+	MACRO__(0x042E, ## __VA_ARGS__), /* GT3 reserved */ \
+	MACRO__(0x0C22, ## __VA_ARGS__), /* SDV GT3 desktop */ \
+	MACRO__(0x0C26, ## __VA_ARGS__), /* SDV GT3 mobile */ \
+	MACRO__(0x0C2A, ## __VA_ARGS__), /* SDV GT3 server */ \
+	MACRO__(0x0C2B, ## __VA_ARGS__), /* SDV GT3 reserved */ \
+	MACRO__(0x0C2E, ## __VA_ARGS__), /* SDV GT3 reserved */ \
+	MACRO__(0x0D22, ## __VA_ARGS__), /* CRW GT3 desktop */ \
+	MACRO__(0x0D26, ## __VA_ARGS__), /* CRW GT3 mobile */ \
+	MACRO__(0x0D2A, ## __VA_ARGS__), /* CRW GT3 server */ \
+	MACRO__(0x0D2B, ## __VA_ARGS__), /* CRW GT3 reserved */ \
+	MACRO__(0x0D2E, ## __VA_ARGS__)  /* CRW GT3 reserved */
+
+#define INTEL_HSW_IDS(MACRO__, ...) \
+	INTEL_HSW_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_HSW_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_HSW_GT3_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_VLV_IDS(MACRO__, ...) \
+	MACRO__(0x0f30, ## __VA_ARGS__), \
+	MACRO__(0x0f31, ## __VA_ARGS__), \
+	MACRO__(0x0f32, ## __VA_ARGS__), \
+	MACRO__(0x0f33, ## __VA_ARGS__)
+
+#define INTEL_BDW_ULT_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x1606, ## __VA_ARGS__), /* GT1 ULT */ \
+	MACRO__(0x160B, ## __VA_ARGS__)  /* GT1 Iris */
+
+#define INTEL_BDW_ULX_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x160E, ## __VA_ARGS__) /* GT1 ULX */
+
+#define INTEL_BDW_GT1_IDS(MACRO__, ...) \
+	INTEL_BDW_ULT_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_BDW_ULX_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x1602, ## __VA_ARGS__), /* GT1 ULT */ \
+	MACRO__(0x160A, ## __VA_ARGS__), /* GT1 Server */ \
+	MACRO__(0x160D, ## __VA_ARGS__)  /* GT1 Workstation */
+
+#define INTEL_BDW_ULT_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x1616, ## __VA_ARGS__), /* GT2 ULT */ \
+	MACRO__(0x161B, ## __VA_ARGS__)  /* GT2 ULT */
+
+#define INTEL_BDW_ULX_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x161E, ## __VA_ARGS__) /* GT2 ULX */
+
+#define INTEL_BDW_GT2_IDS(MACRO__, ...) \
+	INTEL_BDW_ULT_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_BDW_ULX_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x1612, ## __VA_ARGS__), /* GT2 Halo */ \
+	MACRO__(0x161A, ## __VA_ARGS__), /* GT2 Server */ \
+	MACRO__(0x161D, ## __VA_ARGS__)  /* GT2 Workstation */
+
+#define INTEL_BDW_ULT_GT3_IDS(MACRO__, ...) \
+	MACRO__(0x1626, ## __VA_ARGS__), /* ULT */ \
+	MACRO__(0x162B, ## __VA_ARGS__)  /* Iris */ \
+
+#define INTEL_BDW_ULX_GT3_IDS(MACRO__, ...) \
+	MACRO__(0x162E, ## __VA_ARGS__)  /* ULX */
+
+#define INTEL_BDW_GT3_IDS(MACRO__, ...) \
+	INTEL_BDW_ULT_GT3_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_BDW_ULX_GT3_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x1622, ## __VA_ARGS__), /* ULT */ \
+	MACRO__(0x162A, ## __VA_ARGS__), /* Server */ \
+	MACRO__(0x162D, ## __VA_ARGS__)  /* Workstation */
+
+#define INTEL_BDW_ULT_RSVD_IDS(MACRO__, ...) \
+	MACRO__(0x1636, ## __VA_ARGS__), /* ULT */ \
+	MACRO__(0x163B, ## __VA_ARGS__)  /* Iris */
+
+#define INTEL_BDW_ULX_RSVD_IDS(MACRO__, ...) \
+	MACRO__(0x163E, ## __VA_ARGS__) /* ULX */
+
+#define INTEL_BDW_RSVD_IDS(MACRO__, ...) \
+	INTEL_BDW_ULT_RSVD_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_BDW_ULX_RSVD_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x1632, ## __VA_ARGS__), /* ULT */ \
+	MACRO__(0x163A, ## __VA_ARGS__), /* Server */ \
+	MACRO__(0x163D, ## __VA_ARGS__)  /* Workstation */
+
+#define INTEL_BDW_IDS(MACRO__, ...) \
+	INTEL_BDW_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_BDW_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_BDW_GT3_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_BDW_RSVD_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_CHV_IDS(MACRO__, ...) \
+	MACRO__(0x22b0, ## __VA_ARGS__), \
+	MACRO__(0x22b1, ## __VA_ARGS__), \
+	MACRO__(0x22b2, ## __VA_ARGS__), \
+	MACRO__(0x22b3, ## __VA_ARGS__)
+
+#define INTEL_SKL_ULT_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x1906, ## __VA_ARGS__), /* ULT GT1 */ \
+	MACRO__(0x1913, ## __VA_ARGS__)  /* ULT GT1.5 */
+
+#define INTEL_SKL_ULX_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x190E, ## __VA_ARGS__), /* ULX GT1 */ \
+	MACRO__(0x1915, ## __VA_ARGS__)  /* ULX GT1.5 */
+
+#define INTEL_SKL_GT1_IDS(MACRO__, ...) \
+	INTEL_SKL_ULT_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_SKL_ULX_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x1902, ## __VA_ARGS__), /* DT  GT1 */ \
+	MACRO__(0x190A, ## __VA_ARGS__), /* SRV GT1 */ \
+	MACRO__(0x190B, ## __VA_ARGS__), /* Halo GT1 */ \
+	MACRO__(0x1917, ## __VA_ARGS__)  /* DT  GT1.5 */
+
+#define INTEL_SKL_ULT_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x1916, ## __VA_ARGS__), /* ULT GT2 */ \
+	MACRO__(0x1921, ## __VA_ARGS__)  /* ULT GT2F */
+
+#define INTEL_SKL_ULX_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x191E, ## __VA_ARGS__) /* ULX GT2 */
+
+#define INTEL_SKL_GT2_IDS(MACRO__, ...) \
+	INTEL_SKL_ULT_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_SKL_ULX_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x1912, ## __VA_ARGS__), /* DT  GT2 */ \
+	MACRO__(0x191A, ## __VA_ARGS__), /* SRV GT2 */ \
+	MACRO__(0x191B, ## __VA_ARGS__), /* Halo GT2 */ \
+	MACRO__(0x191D, ## __VA_ARGS__)  /* WKS GT2 */
+
+#define INTEL_SKL_ULT_GT3_IDS(MACRO__, ...) \
+	MACRO__(0x1923, ## __VA_ARGS__), /* ULT GT3 */ \
+	MACRO__(0x1926, ## __VA_ARGS__), /* ULT GT3e */ \
+	MACRO__(0x1927, ## __VA_ARGS__)  /* ULT GT3e */
+
+#define INTEL_SKL_GT3_IDS(MACRO__, ...) \
+	INTEL_SKL_ULT_GT3_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x192A, ## __VA_ARGS__), /* SRV GT3 */ \
+	MACRO__(0x192B, ## __VA_ARGS__), /* Halo GT3e */ \
+	MACRO__(0x192D, ## __VA_ARGS__)  /* SRV GT3e */
+
+#define INTEL_SKL_GT4_IDS(MACRO__, ...) \
+	MACRO__(0x1932, ## __VA_ARGS__), /* DT GT4 */ \
+	MACRO__(0x193A, ## __VA_ARGS__), /* SRV GT4e */ \
+	MACRO__(0x193B, ## __VA_ARGS__), /* Halo GT4e */ \
+	MACRO__(0x193D, ## __VA_ARGS__) /* WKS GT4e */
+
+#define INTEL_SKL_IDS(MACRO__, ...) \
+	INTEL_SKL_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_SKL_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_SKL_GT3_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_SKL_GT4_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_BXT_IDS(MACRO__, ...) \
+	MACRO__(0x0A84, ## __VA_ARGS__), \
+	MACRO__(0x1A84, ## __VA_ARGS__), \
+	MACRO__(0x1A85, ## __VA_ARGS__), \
+	MACRO__(0x5A84, ## __VA_ARGS__), /* APL HD Graphics 505 */ \
+	MACRO__(0x5A85, ## __VA_ARGS__)  /* APL HD Graphics 500 */
+
+#define INTEL_GLK_IDS(MACRO__, ...) \
+	MACRO__(0x3184, ## __VA_ARGS__), \
+	MACRO__(0x3185, ## __VA_ARGS__)
+
+#define INTEL_KBL_ULT_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x5906, ## __VA_ARGS__), /* ULT GT1 */ \
+	MACRO__(0x5913, ## __VA_ARGS__)  /* ULT GT1.5 */
+
+#define INTEL_KBL_ULX_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x590E, ## __VA_ARGS__), /* ULX GT1 */ \
+	MACRO__(0x5915, ## __VA_ARGS__)  /* ULX GT1.5 */
+
+#define INTEL_KBL_GT1_IDS(MACRO__, ...) \
+	INTEL_KBL_ULT_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_KBL_ULX_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x5902, ## __VA_ARGS__), /* DT  GT1 */ \
+	MACRO__(0x5908, ## __VA_ARGS__), /* Halo GT1 */ \
+	MACRO__(0x590A, ## __VA_ARGS__), /* SRV GT1 */ \
+	MACRO__(0x590B, ## __VA_ARGS__) /* Halo GT1 */
+
+#define INTEL_KBL_ULT_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x5916, ## __VA_ARGS__), /* ULT GT2 */ \
+	MACRO__(0x5921, ## __VA_ARGS__)  /* ULT GT2F */
+
+#define INTEL_KBL_ULX_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x591E, ## __VA_ARGS__)  /* ULX GT2 */
+
+#define INTEL_KBL_GT2_IDS(MACRO__, ...) \
+	INTEL_KBL_ULT_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_KBL_ULX_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x5912, ## __VA_ARGS__), /* DT  GT2 */ \
+	MACRO__(0x5917, ## __VA_ARGS__), /* Mobile GT2 */ \
+	MACRO__(0x591A, ## __VA_ARGS__), /* SRV GT2 */ \
+	MACRO__(0x591B, ## __VA_ARGS__), /* Halo GT2 */ \
+	MACRO__(0x591D, ## __VA_ARGS__) /* WKS GT2 */
+
+#define INTEL_KBL_ULT_GT3_IDS(MACRO__, ...) \
+	MACRO__(0x5926, ## __VA_ARGS__) /* ULT GT3 */
+
+#define INTEL_KBL_GT3_IDS(MACRO__, ...) \
+	INTEL_KBL_ULT_GT3_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x5923, ## __VA_ARGS__), /* ULT GT3 */ \
+	MACRO__(0x5927, ## __VA_ARGS__) /* ULT GT3 */
+
+#define INTEL_KBL_GT4_IDS(MACRO__, ...) \
+	MACRO__(0x593B, ## __VA_ARGS__) /* Halo GT4 */
+
+/* AML/KBL Y GT2 */
+#define INTEL_AML_KBL_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x591C, ## __VA_ARGS__),  /* ULX GT2 */ \
+	MACRO__(0x87C0, ## __VA_ARGS__) /* ULX GT2 */
+
+/* AML/CFL Y GT2 */
+#define INTEL_AML_CFL_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x87CA, ## __VA_ARGS__)
+
+/* CML GT1 */
+#define INTEL_CML_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x9BA2, ## __VA_ARGS__), \
+	MACRO__(0x9BA4, ## __VA_ARGS__), \
+	MACRO__(0x9BA5, ## __VA_ARGS__), \
+	MACRO__(0x9BA8, ## __VA_ARGS__)
+
+#define INTEL_CML_U_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x9B21, ## __VA_ARGS__), \
+	MACRO__(0x9BAA, ## __VA_ARGS__), \
+	MACRO__(0x9BAC, ## __VA_ARGS__)
+
+/* CML GT2 */
+#define INTEL_CML_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x9BC2, ## __VA_ARGS__), \
+	MACRO__(0x9BC4, ## __VA_ARGS__), \
+	MACRO__(0x9BC5, ## __VA_ARGS__), \
+	MACRO__(0x9BC6, ## __VA_ARGS__), \
+	MACRO__(0x9BC8, ## __VA_ARGS__), \
+	MACRO__(0x9BE6, ## __VA_ARGS__), \
+	MACRO__(0x9BF6, ## __VA_ARGS__)
+
+#define INTEL_CML_U_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x9B41, ## __VA_ARGS__), \
+	MACRO__(0x9BCA, ## __VA_ARGS__), \
+	MACRO__(0x9BCC, ## __VA_ARGS__)
+
+#define INTEL_CML_IDS(MACRO__, ...) \
+	INTEL_CML_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_CML_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_CML_U_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_CML_U_GT2_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_KBL_IDS(MACRO__, ...) \
+	INTEL_KBL_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_KBL_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_KBL_GT3_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_KBL_GT4_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_AML_KBL_GT2_IDS(MACRO__, ## __VA_ARGS__)
+
+/* CFL S */
+#define INTEL_CFL_S_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x3E90, ## __VA_ARGS__), /* SRV GT1 */ \
+	MACRO__(0x3E93, ## __VA_ARGS__), /* SRV GT1 */ \
+	MACRO__(0x3E99, ## __VA_ARGS__)  /* SRV GT1 */
+
+#define INTEL_CFL_S_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x3E91, ## __VA_ARGS__), /* SRV GT2 */ \
+	MACRO__(0x3E92, ## __VA_ARGS__), /* SRV GT2 */ \
+	MACRO__(0x3E96, ## __VA_ARGS__), /* SRV GT2 */ \
+	MACRO__(0x3E98, ## __VA_ARGS__), /* SRV GT2 */ \
+	MACRO__(0x3E9A, ## __VA_ARGS__)  /* SRV GT2 */
+
+/* CFL H */
+#define INTEL_CFL_H_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x3E9C, ## __VA_ARGS__)
+
+#define INTEL_CFL_H_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x3E94, ## __VA_ARGS__),  /* Halo GT2 */ \
+	MACRO__(0x3E9B, ## __VA_ARGS__) /* Halo GT2 */
+
+/* CFL U GT2 */
+#define INTEL_CFL_U_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x3EA9, ## __VA_ARGS__)
+
+/* CFL U GT3 */
+#define INTEL_CFL_U_GT3_IDS(MACRO__, ...) \
+	MACRO__(0x3EA5, ## __VA_ARGS__), /* ULT GT3 */ \
+	MACRO__(0x3EA6, ## __VA_ARGS__), /* ULT GT3 */ \
+	MACRO__(0x3EA7, ## __VA_ARGS__), /* ULT GT3 */ \
+	MACRO__(0x3EA8, ## __VA_ARGS__)  /* ULT GT3 */
+
+#define INTEL_CFL_IDS(MACRO__, ...) \
+	INTEL_CFL_S_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_CFL_S_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_CFL_H_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_CFL_H_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_CFL_U_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_CFL_U_GT3_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_AML_CFL_GT2_IDS(MACRO__, ## __VA_ARGS__)
+
+/* WHL/CFL U GT1 */
+#define INTEL_WHL_U_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x3EA1, ## __VA_ARGS__), \
+	MACRO__(0x3EA4, ## __VA_ARGS__)
+
+/* WHL/CFL U GT2 */
+#define INTEL_WHL_U_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x3EA0, ## __VA_ARGS__), \
+	MACRO__(0x3EA3, ## __VA_ARGS__)
+
+/* WHL/CFL U GT3 */
+#define INTEL_WHL_U_GT3_IDS(MACRO__, ...) \
+	MACRO__(0x3EA2, ## __VA_ARGS__)
+
+#define INTEL_WHL_IDS(MACRO__, ...) \
+	INTEL_WHL_U_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_WHL_U_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_WHL_U_GT3_IDS(MACRO__, ## __VA_ARGS__)
+
+/* CNL */
+#define INTEL_CNL_PORT_F_IDS(MACRO__, ...) \
+	MACRO__(0x5A44, ## __VA_ARGS__), \
+	MACRO__(0x5A4C, ## __VA_ARGS__), \
+	MACRO__(0x5A54, ## __VA_ARGS__), \
+	MACRO__(0x5A5C, ## __VA_ARGS__)
+
+#define INTEL_CNL_IDS(MACRO__, ...) \
+	INTEL_CNL_PORT_F_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x5A40, ## __VA_ARGS__), \
+	MACRO__(0x5A41, ## __VA_ARGS__), \
+	MACRO__(0x5A42, ## __VA_ARGS__), \
+	MACRO__(0x5A49, ## __VA_ARGS__), \
+	MACRO__(0x5A4A, ## __VA_ARGS__), \
+	MACRO__(0x5A50, ## __VA_ARGS__), \
+	MACRO__(0x5A51, ## __VA_ARGS__), \
+	MACRO__(0x5A52, ## __VA_ARGS__), \
+	MACRO__(0x5A59, ## __VA_ARGS__), \
+	MACRO__(0x5A5A, ## __VA_ARGS__)
+
+/* ICL */
+#define INTEL_ICL_PORT_F_IDS(MACRO__, ...) \
+	MACRO__(0x8A50, ## __VA_ARGS__), \
+	MACRO__(0x8A52, ## __VA_ARGS__), \
+	MACRO__(0x8A53, ## __VA_ARGS__), \
+	MACRO__(0x8A54, ## __VA_ARGS__), \
+	MACRO__(0x8A56, ## __VA_ARGS__), \
+	MACRO__(0x8A57, ## __VA_ARGS__), \
+	MACRO__(0x8A58, ## __VA_ARGS__), \
+	MACRO__(0x8A59, ## __VA_ARGS__), \
+	MACRO__(0x8A5A, ## __VA_ARGS__), \
+	MACRO__(0x8A5B, ## __VA_ARGS__), \
+	MACRO__(0x8A5C, ## __VA_ARGS__), \
+	MACRO__(0x8A70, ## __VA_ARGS__), \
+	MACRO__(0x8A71, ## __VA_ARGS__)
+
+#define INTEL_ICL_IDS(MACRO__, ...) \
+	INTEL_ICL_PORT_F_IDS(MACRO__, ## __VA_ARGS__), \
+	MACRO__(0x8A51, ## __VA_ARGS__), \
+	MACRO__(0x8A5D, ## __VA_ARGS__)
+
+/* EHL */
+#define INTEL_EHL_IDS(MACRO__, ...) \
+	MACRO__(0x4541, ## __VA_ARGS__), \
+	MACRO__(0x4551, ## __VA_ARGS__), \
+	MACRO__(0x4555, ## __VA_ARGS__), \
+	MACRO__(0x4557, ## __VA_ARGS__), \
+	MACRO__(0x4570, ## __VA_ARGS__), \
+	MACRO__(0x4571, ## __VA_ARGS__)
+
+/* JSL */
+#define INTEL_JSL_IDS(MACRO__, ...) \
+	MACRO__(0x4E51, ## __VA_ARGS__), \
+	MACRO__(0x4E55, ## __VA_ARGS__), \
+	MACRO__(0x4E57, ## __VA_ARGS__), \
+	MACRO__(0x4E61, ## __VA_ARGS__), \
+	MACRO__(0x4E71, ## __VA_ARGS__)
+
+/* TGL */
+#define INTEL_TGL_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x9A60, ## __VA_ARGS__), \
+	MACRO__(0x9A68, ## __VA_ARGS__), \
+	MACRO__(0x9A70, ## __VA_ARGS__)
+
+#define INTEL_TGL_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x9A40, ## __VA_ARGS__), \
+	MACRO__(0x9A49, ## __VA_ARGS__), \
+	MACRO__(0x9A59, ## __VA_ARGS__), \
+	MACRO__(0x9A78, ## __VA_ARGS__), \
+	MACRO__(0x9AC0, ## __VA_ARGS__), \
+	MACRO__(0x9AC9, ## __VA_ARGS__), \
+	MACRO__(0x9AD9, ## __VA_ARGS__), \
+	MACRO__(0x9AF8, ## __VA_ARGS__)
+
+#define INTEL_TGL_IDS(MACRO__, ...) \
+	INTEL_TGL_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_TGL_GT2_IDS(MACRO__, ## __VA_ARGS__)
+
+/* RKL */
+#define INTEL_RKL_IDS(MACRO__, ...) \
+	MACRO__(0x4C80, ## __VA_ARGS__), \
+	MACRO__(0x4C8A, ## __VA_ARGS__), \
+	MACRO__(0x4C8B, ## __VA_ARGS__), \
+	MACRO__(0x4C8C, ## __VA_ARGS__), \
+	MACRO__(0x4C90, ## __VA_ARGS__), \
+	MACRO__(0x4C9A, ## __VA_ARGS__)
+
+/* DG1 */
+#define INTEL_DG1_IDS(MACRO__, ...) \
+	MACRO__(0x4905, ## __VA_ARGS__), \
+	MACRO__(0x4906, ## __VA_ARGS__), \
+	MACRO__(0x4907, ## __VA_ARGS__), \
+	MACRO__(0x4908, ## __VA_ARGS__), \
+	MACRO__(0x4909, ## __VA_ARGS__)
+
+/* ADL-S */
+#define INTEL_ADLS_IDS(MACRO__, ...) \
+	MACRO__(0x4680, ## __VA_ARGS__), \
+	MACRO__(0x4682, ## __VA_ARGS__), \
+	MACRO__(0x4688, ## __VA_ARGS__), \
+	MACRO__(0x468A, ## __VA_ARGS__), \
+	MACRO__(0x468B, ## __VA_ARGS__), \
+	MACRO__(0x4690, ## __VA_ARGS__), \
+	MACRO__(0x4692, ## __VA_ARGS__), \
+	MACRO__(0x4693, ## __VA_ARGS__)
+
+/* ADL-P */
+#define INTEL_ADLP_IDS(MACRO__, ...) \
+	MACRO__(0x46A0, ## __VA_ARGS__), \
+	MACRO__(0x46A1, ## __VA_ARGS__), \
+	MACRO__(0x46A2, ## __VA_ARGS__), \
+	MACRO__(0x46A3, ## __VA_ARGS__), \
+	MACRO__(0x46A6, ## __VA_ARGS__), \
+	MACRO__(0x46A8, ## __VA_ARGS__), \
+	MACRO__(0x46AA, ## __VA_ARGS__), \
+	MACRO__(0x462A, ## __VA_ARGS__), \
+	MACRO__(0x4626, ## __VA_ARGS__), \
+	MACRO__(0x4628, ## __VA_ARGS__), \
+	MACRO__(0x46B0, ## __VA_ARGS__), \
+	MACRO__(0x46B1, ## __VA_ARGS__), \
+	MACRO__(0x46B2, ## __VA_ARGS__), \
+	MACRO__(0x46B3, ## __VA_ARGS__), \
+	MACRO__(0x46C0, ## __VA_ARGS__), \
+	MACRO__(0x46C1, ## __VA_ARGS__), \
+	MACRO__(0x46C2, ## __VA_ARGS__), \
+	MACRO__(0x46C3, ## __VA_ARGS__)
+
+/* ADL-N */
+#define INTEL_ADLN_IDS(MACRO__, ...) \
+	MACRO__(0x46D0, ## __VA_ARGS__), \
+	MACRO__(0x46D1, ## __VA_ARGS__), \
+	MACRO__(0x46D2, ## __VA_ARGS__), \
+	MACRO__(0x46D3, ## __VA_ARGS__), \
+	MACRO__(0x46D4, ## __VA_ARGS__)
+
+/* RPL-S */
+#define INTEL_RPLS_IDS(MACRO__, ...) \
+	MACRO__(0xA780, ## __VA_ARGS__), \
+	MACRO__(0xA781, ## __VA_ARGS__), \
+	MACRO__(0xA782, ## __VA_ARGS__), \
+	MACRO__(0xA783, ## __VA_ARGS__), \
+	MACRO__(0xA788, ## __VA_ARGS__), \
+	MACRO__(0xA789, ## __VA_ARGS__), \
+	MACRO__(0xA78A, ## __VA_ARGS__), \
+	MACRO__(0xA78B, ## __VA_ARGS__)
+
+/* RPL-U */
+#define INTEL_RPLU_IDS(MACRO__, ...) \
+	MACRO__(0xA721, ## __VA_ARGS__), \
+	MACRO__(0xA7A1, ## __VA_ARGS__), \
+	MACRO__(0xA7A9, ## __VA_ARGS__), \
+	MACRO__(0xA7AC, ## __VA_ARGS__), \
+	MACRO__(0xA7AD, ## __VA_ARGS__)
+
+/* RPL-P */
+#define INTEL_RPLP_IDS(MACRO__, ...) \
+	MACRO__(0xA720, ## __VA_ARGS__), \
+	MACRO__(0xA7A0, ## __VA_ARGS__), \
+	MACRO__(0xA7A8, ## __VA_ARGS__), \
+	MACRO__(0xA7AA, ## __VA_ARGS__), \
+	MACRO__(0xA7AB, ## __VA_ARGS__)
+
+/* DG2 */
+#define INTEL_DG2_G10_IDS(MACRO__, ...) \
+	MACRO__(0x5690, ## __VA_ARGS__), \
+	MACRO__(0x5691, ## __VA_ARGS__), \
+	MACRO__(0x5692, ## __VA_ARGS__), \
+	MACRO__(0x56A0, ## __VA_ARGS__), \
+	MACRO__(0x56A1, ## __VA_ARGS__), \
+	MACRO__(0x56A2, ## __VA_ARGS__), \
+	MACRO__(0x56BE, ## __VA_ARGS__), \
+	MACRO__(0x56BF, ## __VA_ARGS__)
+
+#define INTEL_DG2_G11_IDS(MACRO__, ...) \
+	MACRO__(0x5693, ## __VA_ARGS__), \
+	MACRO__(0x5694, ## __VA_ARGS__), \
+	MACRO__(0x5695, ## __VA_ARGS__), \
+	MACRO__(0x56A5, ## __VA_ARGS__), \
+	MACRO__(0x56A6, ## __VA_ARGS__), \
+	MACRO__(0x56B0, ## __VA_ARGS__), \
+	MACRO__(0x56B1, ## __VA_ARGS__), \
+	MACRO__(0x56BA, ## __VA_ARGS__), \
+	MACRO__(0x56BB, ## __VA_ARGS__), \
+	MACRO__(0x56BC, ## __VA_ARGS__), \
+	MACRO__(0x56BD, ## __VA_ARGS__)
+
+#define INTEL_DG2_G12_IDS(MACRO__, ...) \
+	MACRO__(0x5696, ## __VA_ARGS__), \
+	MACRO__(0x5697, ## __VA_ARGS__), \
+	MACRO__(0x56A3, ## __VA_ARGS__), \
+	MACRO__(0x56A4, ## __VA_ARGS__), \
+	MACRO__(0x56B2, ## __VA_ARGS__), \
+	MACRO__(0x56B3, ## __VA_ARGS__)
+
+#define INTEL_DG2_IDS(MACRO__, ...) \
+	INTEL_DG2_G10_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_DG2_G11_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_DG2_G12_IDS(MACRO__, ## __VA_ARGS__)
+
+#define INTEL_ATS_M150_IDS(MACRO__, ...) \
+	MACRO__(0x56C0, ## __VA_ARGS__), \
+	MACRO__(0x56C2, ## __VA_ARGS__)
+
+#define INTEL_ATS_M75_IDS(MACRO__, ...) \
+	MACRO__(0x56C1, ## __VA_ARGS__)
+
+#define INTEL_ATS_M_IDS(MACRO__, ...) \
+	INTEL_ATS_M150_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_ATS_M75_IDS(MACRO__, ## __VA_ARGS__)
+
+/* MTL */
+#define INTEL_MTL_IDS(MACRO__, ...) \
+	MACRO__(0x7D40, ## __VA_ARGS__), \
+	MACRO__(0x7D41, ## __VA_ARGS__), \
+	MACRO__(0x7D45, ## __VA_ARGS__), \
+	MACRO__(0x7D51, ## __VA_ARGS__), \
+	MACRO__(0x7D55, ## __VA_ARGS__), \
+	MACRO__(0x7D60, ## __VA_ARGS__), \
+	MACRO__(0x7D67, ## __VA_ARGS__), \
+	MACRO__(0x7DD1, ## __VA_ARGS__), \
+	MACRO__(0x7DD5, ## __VA_ARGS__)
+
+#endif /* _I915_PCIIDS_H */

+ 67 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/i915_pciids_local.h

@@ -0,0 +1,67 @@
+/* SPDX-License-Identifier: MIT */
+/*
+ * Copyright © 2022 Intel Corporation
+ */
+#ifndef _I915_PCIIDS_LOCAL_H_
+#define _I915_PCIIDS_LOCAL_H_
+
+#include "i915_pciids.h"
+
+/* MTL perf */
+#ifndef INTEL_MTL_M_IDS
+#define INTEL_MTL_M_IDS(MACRO__, ...) \
+	MACRO__(0x7D60, ## __VA_ARGS__), \
+	MACRO__(0x7D67, ## __VA_ARGS__)
+#endif
+
+#ifndef INTEL_MTL_P_GT2_IDS
+#define INTEL_MTL_P_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x7D45, ## __VA_ARGS__)
+#endif
+
+#ifndef INTEL_MTL_P_GT3_IDS
+#define INTEL_MTL_P_GT3_IDS(MACRO__, ...) \
+	MACRO__(0x7D55, ## __VA_ARGS__), \
+	MACRO__(0x7DD5, ## __VA_ARGS__)
+#endif
+
+#ifndef INTEL_MTL_P_IDS
+#define INTEL_MTL_P_IDS(MACRO__, ...) \
+	INTEL_MTL_P_GT2_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_MTL_P_GT3_IDS(MACRO__, ## __VA_ARGS__)
+#endif
+
+#ifndef INTEL_ARL_GT1_IDS
+#define INTEL_ARL_GT1_IDS(MACRO__, ...) \
+	MACRO__(0x7D41, ## __VA_ARGS__), \
+	MACRO__(0x7D67, ## __VA_ARGS__)
+#endif
+
+#ifndef INTEL_ARL_GT2_IDS
+#define INTEL_ARL_GT2_IDS(MACRO__, ...) \
+	MACRO__(0x7D51, ## __VA_ARGS__), \
+	MACRO__(0x7DD1, ## __VA_ARGS__)
+#endif
+
+#ifndef INTEL_ARL_IDS
+#define INTEL_ARL_IDS(MACRO__, ...) \
+	INTEL_ARL_GT1_IDS(MACRO__, ## __VA_ARGS__), \
+	INTEL_ARL_GT2_IDS(MACRO__, ## __VA_ARGS__)
+#endif
+
+/* PVC */
+#ifndef INTEL_PVC_IDS
+#define INTEL_PVC_IDS(MACRO__, ...) \
+	MACRO__(0x0BD0, ## __VA_ARGS__), \
+	MACRO__(0x0BD1, ## __VA_ARGS__), \
+	MACRO__(0x0BD2, ## __VA_ARGS__), \
+	MACRO__(0x0BD5, ## __VA_ARGS__), \
+	MACRO__(0x0BD6, ## __VA_ARGS__), \
+	MACRO__(0x0BD7, ## __VA_ARGS__), \
+	MACRO__(0x0BD8, ## __VA_ARGS__), \
+	MACRO__(0x0BD9, ## __VA_ARGS__), \
+	MACRO__(0x0BDA, ## __VA_ARGS__), \
+	MACRO__(0x0BDB, ## __VA_ARGS__)
+#endif
+
+#endif /* _I915_PCIIDS_LOCAL_H */

+ 210 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/igt_perf.c

@@ -0,0 +1,210 @@
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#ifdef __linux__
+#include <sys/sysinfo.h>
+#include <sys/sysmacros.h>
+#include <linux/limits.h>
+#endif
+#include <time.h>
+#include <unistd.h>
+#include <stdio.h>
+
+#include "igt_perf.h"
+
+static char *bus_address(int i915, char *path, int pathlen)
+{
+	struct stat st;
+	int len = -1;
+	int dir;
+	char *s;
+
+	if (fstat(i915, &st) || !S_ISCHR(st.st_mode))
+		return NULL;
+
+	snprintf(path, pathlen, "/sys/dev/char/%d:%d",
+		 major(st.st_rdev), minor(st.st_rdev));
+
+	dir = open(path, O_RDONLY);
+	if (dir != -1) {
+		len = readlinkat(dir, "device", path, pathlen - 1);
+		close(dir);
+	}
+	if (len < 0)
+		return NULL;
+
+	path[len] = '\0';
+
+	/* strip off the relative path */
+	s = strrchr(path, '/');
+	if (s)
+		memmove(path, s + 1, len - (s - path) + 1);
+
+	return path;
+}
+
+const char *i915_perf_device(int i915, char *buf, int buflen)
+{
+	char *s;
+
+#define prefix "i915_"
+#define plen strlen(prefix)
+
+	if (!buf || buflen < plen)
+		return "i915";
+
+	memcpy(buf, prefix, plen);
+
+	if (!bus_address(i915, buf + plen, buflen - plen) ||
+	    strcmp(buf + plen, "0000:00:02.0") == 0) /* legacy name for igfx */
+		buf[plen - 1] = '\0';
+
+	/* Convert all colons in the address to '_', thanks perf! */
+	for (s = buf; *s; s++)
+		if (*s == ':')
+			*s = '_';
+
+	return buf;
+}
+
+const char *xe_perf_device(int xe, char *buf, int buflen)
+{
+	char *s;
+	char pref[] = "xe_";
+	int len = strlen(pref);
+
+
+	if (!buf || buflen < len)
+		return "xe";
+
+	memcpy(buf, pref, len);
+
+	if (!bus_address(xe, buf + len, buflen - len))
+		buf[len - 1] = '\0';
+
+	/* Convert all colons in the address to '_', thanks perf! */
+	for (s = buf; *s; s++)
+		if (*s == ':')
+			*s = '_';
+
+	return buf;
+}
+
+uint64_t xe_perf_type_id(int xe)
+{
+	char buf[80];
+
+	return igt_perf_type_id(xe_perf_device(xe, buf, sizeof(buf)));
+}
+
+uint64_t i915_perf_type_id(int i915)
+{
+	char buf[80];
+
+	return igt_perf_type_id(i915_perf_device(i915, buf, sizeof(buf)));
+}
+
+uint64_t igt_perf_type_id(const char *device)
+{
+	char buf[64];
+	ssize_t ret;
+	int fd;
+
+	snprintf(buf, sizeof(buf),
+		 "/sys/bus/event_source/devices/%s/type", device);
+
+	fd = open(buf, O_RDONLY);
+	if (fd < 0)
+		return 0;
+
+	ret = read(fd, buf, sizeof(buf) - 1);
+	close(fd);
+	if (ret < 1)
+		return 0;
+
+	buf[ret] = '\0';
+
+	return strtoull(buf, NULL, 0);
+}
+
+int igt_perf_events_dir(int i915)
+{
+	char buf[80];
+	char path[PATH_MAX];
+
+	i915_perf_device(i915, buf, sizeof(buf));
+	snprintf(path, sizeof(path), "/sys/bus/event_source/devices/%s/events", buf);
+	return open(path, O_RDONLY);
+}
+
+static int
+_perf_open(uint64_t type, uint64_t config, int group, uint64_t format)
+{
+	struct perf_event_attr attr = { };
+	int nr_cpus = get_nprocs_conf();
+	int cpu = 0, ret;
+
+	attr.type = type;
+	if (attr.type == 0)
+		return -ENOENT;
+
+	if (group >= 0)
+		format &= ~PERF_FORMAT_GROUP;
+
+	attr.read_format = format;
+	attr.config = config;
+	attr.use_clockid = 1;
+	attr.clockid = CLOCK_MONOTONIC;
+
+	do {
+		ret = perf_event_open(&attr, -1, cpu++, group, 0);
+	} while ((ret < 0 && errno == EINVAL) && (cpu < nr_cpus));
+
+	return ret;
+}
+
+int perf_igfx_open(uint64_t config)
+{
+	return _perf_open(igt_perf_type_id("i915"), config, -1,
+			  PERF_FORMAT_TOTAL_TIME_ENABLED);
+}
+
+int perf_igfx_open_group(uint64_t config, int group)
+{
+	return _perf_open(igt_perf_type_id("i915"), config, group,
+			  PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_GROUP);
+}
+
+int perf_xe_open(int xe, uint64_t config)
+{
+	return _perf_open(xe_perf_type_id(xe), config, -1,
+			PERF_FORMAT_TOTAL_TIME_ENABLED);
+}
+
+int perf_i915_open(int i915, uint64_t config)
+{
+	return _perf_open(i915_perf_type_id(i915), config, -1,
+			  PERF_FORMAT_TOTAL_TIME_ENABLED);
+}
+
+int perf_i915_open_group(int i915, uint64_t config, int group)
+{
+	return _perf_open(i915_perf_type_id(i915), config, group,
+			  PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_GROUP);
+}
+
+int igt_perf_open(uint64_t type, uint64_t config)
+{
+	return _perf_open(type, config, -1,
+			  PERF_FORMAT_TOTAL_TIME_ENABLED);
+}
+
+int igt_perf_open_group(uint64_t type, uint64_t config, int group)
+{
+	return _perf_open(type, config, group,
+			  PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_GROUP);
+}

+ 75 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/igt_perf.h

@@ -0,0 +1,75 @@
+/*
+ * Copyright © 2017 Intel Corporation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ *
+ */
+
+#ifndef I915_PERF_H
+#define I915_PERF_H
+
+#include <stdint.h>
+
+#ifdef __linux__
+#include <linux/perf_event.h>
+#endif
+
+//#include "igt_gt.h"
+
+static inline int
+perf_event_open(struct perf_event_attr *attr,
+		pid_t pid,
+		int cpu,
+		int group_fd,
+		unsigned long flags)
+{
+#ifndef __NR_perf_event_open
+#if defined(__i386__)
+#define __NR_perf_event_open 336
+#elif defined(__x86_64__)
+#define __NR_perf_event_open 298
+#else
+#define __NR_perf_event_open 0
+#endif
+#endif
+    attr->size = sizeof(*attr);
+    return syscall(__NR_perf_event_open, attr, pid, cpu, group_fd, flags);
+}
+
+uint64_t igt_perf_type_id(const char *device);
+int igt_perf_events_dir(int i915);
+int igt_perf_open(uint64_t type, uint64_t config);
+int igt_perf_open_group(uint64_t type, uint64_t config, int group);
+
+const char *i915_perf_device(int i915, char *buf, int buflen);
+uint64_t i915_perf_type_id(int i915);
+
+const char *xe_perf_device(int xe, char *buf, int buflen);
+uint64_t xe_perf_type_id(int);
+
+int perf_igfx_open(uint64_t config);
+int perf_igfx_open_group(uint64_t config, int group);
+
+int perf_i915_open(int i915, uint64_t config);
+int perf_i915_open_group(int i915, uint64_t config, int group);
+
+int perf_xe_open(int xe, uint64_t config);
+
+#endif /* I915_PERF_H */

+ 233 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/intel_chipset.h

@@ -0,0 +1,233 @@
+/*
+ * Copyright © 2007 Intel Corporation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ *
+ * Authors:
+ *    Eric Anholt <eric@anholt.net>
+ *
+ */
+
+#ifndef _INTEL_CHIPSET_H
+#define _INTEL_CHIPSET_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#define BIT(x) (1ul <<(x))
+
+struct intel_device_info {
+	unsigned graphics_ver;
+	unsigned graphics_rel;
+	unsigned display_ver;
+	unsigned gt; /* 0 if unknown */
+	bool has_4tile : 1;
+	bool has_flatccs : 1;
+	bool has_oam : 1;
+	bool is_mobile : 1;
+	bool is_whitney : 1;
+	bool is_almador : 1;
+	bool is_brookdale : 1;
+	bool is_montara : 1;
+	bool is_springdale : 1;
+	bool is_grantsdale : 1;
+	bool is_alviso : 1;
+	bool is_lakeport : 1;
+	bool is_calistoga : 1;
+	bool is_bearlake : 1;
+	bool is_pineview : 1;
+	bool is_broadwater : 1;
+	bool is_crestline : 1;
+	bool is_eaglelake : 1;
+	bool is_cantiga : 1;
+	bool is_ironlake : 1;
+	bool is_arrandale : 1;
+	bool is_sandybridge : 1;
+	bool is_ivybridge : 1;
+	bool is_valleyview : 1;
+	bool is_haswell : 1;
+	bool is_broadwell : 1;
+	bool is_cherryview : 1;
+	bool is_skylake : 1;
+	bool is_broxton : 1;
+	bool is_kabylake : 1;
+	bool is_geminilake : 1;
+	bool is_coffeelake : 1;
+	bool is_cometlake : 1;
+	bool is_cannonlake : 1;
+	bool is_icelake : 1;
+	bool is_elkhartlake : 1;
+	bool is_jasperlake : 1;
+	bool is_tigerlake : 1;
+	bool is_rocketlake : 1;
+	bool is_dg1 : 1;
+	bool is_dg2 : 1;
+	bool is_alderlake_s : 1;
+	bool is_raptorlake_s : 1;
+	bool is_alderlake_p : 1;
+	bool is_alderlake_n : 1;
+	bool is_meteorlake : 1;
+	bool is_pontevecchio : 1;
+	bool is_lunarlake : 1;
+	bool is_battlemage : 1;
+	const char *codename;
+};
+
+const struct intel_device_info *intel_get_device_info(uint16_t devid) __attribute__((pure));
+
+extern enum pch_type intel_pch;
+
+enum pch_type {
+	PCH_NONE,
+	PCH_IBX,
+	PCH_CPT,
+	PCH_LPT,
+};
+
+void intel_check_pch(void);
+
+#define HAS_IBX (intel_pch == PCH_IBX)
+#define HAS_CPT (intel_pch == PCH_CPT)
+#define HAS_LPT (intel_pch == PCH_LPT)
+
+#define IP_VER(ver, rel)		((ver) << 8 | (rel))
+
+/* Exclude chipset #defines, they just add noise */
+#ifndef __GTK_DOC_IGNORE__
+
+#define PCI_CHIP_I810			0x7121
+#define PCI_CHIP_I810_DC100		0x7123
+#define PCI_CHIP_I810_E			0x7125
+#define PCI_CHIP_I815			0x1132
+
+#define PCI_CHIP_I830_M			0x3577
+#define PCI_CHIP_845_G			0x2562
+#define PCI_CHIP_I854_G			0x358e
+#define PCI_CHIP_I855_GM		0x3582
+#define PCI_CHIP_I865_G			0x2572
+
+#define PCI_CHIP_I915_G			0x2582
+#define PCI_CHIP_E7221_G		0x258A
+#define PCI_CHIP_I915_GM		0x2592
+#define PCI_CHIP_I945_G			0x2772
+#define PCI_CHIP_I945_GM		0x27A2
+#define PCI_CHIP_I945_GME		0x27AE
+
+#define PCI_CHIP_I965_G			0x29A2
+#define PCI_CHIP_I965_Q			0x2992
+#define PCI_CHIP_I965_G_1		0x2982
+#define PCI_CHIP_I946_GZ		0x2972
+#define PCI_CHIP_I965_GM		0x2A02
+#define PCI_CHIP_I965_GME		0x2A12
+
+#define PCI_CHIP_GM45_GM		0x2A42
+
+#define PCI_CHIP_Q45_G			0x2E12
+#define PCI_CHIP_G45_G			0x2E22
+#define PCI_CHIP_G41_G			0x2E32
+
+#endif /* __GTK_DOC_IGNORE__ */
+
+#define IS_915G(devid)		(intel_get_device_info(devid)->is_grantsdale)
+#define IS_915GM(devid)		(intel_get_device_info(devid)->is_alviso)
+
+#define IS_915(devid)		(IS_915G(devid) || IS_915GM(devid))
+
+#define IS_945G(devid)		(intel_get_device_info(devid)->is_lakeport)
+#define IS_945GM(devid)		(intel_get_device_info(devid)->is_calistoga)
+
+#define IS_945(devid)		(IS_945G(devid) || \
+				 IS_945GM(devid) || \
+				 IS_G33(devid))
+
+#define IS_PINEVIEW(devid)	(intel_get_device_info(devid)->is_pineview)
+#define IS_G33(devid)		(intel_get_device_info(devid)->is_bearlake || \
+				 intel_get_device_info(devid)->is_pineview)
+
+#define IS_BROADWATER(devid)	(intel_get_device_info(devid)->is_broadwater)
+#define IS_CRESTLINE(devid)	(intel_get_device_info(devid)->is_crestline)
+
+#define IS_GM45(devid)		(intel_get_device_info(devid)->is_cantiga)
+#define IS_G45(devid)		(intel_get_device_info(devid)->is_eaglelake)
+#define IS_G4X(devid)		(IS_G45(devid) || IS_GM45(devid))
+
+#define IS_IRONLAKE(devid)	(intel_get_device_info(devid)->is_ironlake)
+#define IS_ARRANDALE(devid)	(intel_get_device_info(devid)->is_arrandale)
+#define IS_SANDYBRIDGE(devid)	(intel_get_device_info(devid)->is_sandybridge)
+#define IS_IVYBRIDGE(devid)	(intel_get_device_info(devid)->is_ivybridge)
+#define IS_VALLEYVIEW(devid)	(intel_get_device_info(devid)->is_valleyview)
+#define IS_HASWELL(devid)	(intel_get_device_info(devid)->is_haswell)
+#define IS_BROADWELL(devid)	(intel_get_device_info(devid)->is_broadwell)
+#define IS_CHERRYVIEW(devid)	(intel_get_device_info(devid)->is_cherryview)
+#define IS_SKYLAKE(devid)	(intel_get_device_info(devid)->is_skylake)
+#define IS_BROXTON(devid)	(intel_get_device_info(devid)->is_broxton)
+#define IS_KABYLAKE(devid)	(intel_get_device_info(devid)->is_kabylake)
+#define IS_GEMINILAKE(devid)	(intel_get_device_info(devid)->is_geminilake)
+#define IS_COFFEELAKE(devid)	(intel_get_device_info(devid)->is_coffeelake)
+#define IS_COMETLAKE(devid)	(intel_get_device_info(devid)->is_cometlake)
+#define IS_CANNONLAKE(devid)	(intel_get_device_info(devid)->is_cannonlake)
+#define IS_ICELAKE(devid)	(intel_get_device_info(devid)->is_icelake)
+#define IS_TIGERLAKE(devid)	(intel_get_device_info(devid)->is_tigerlake)
+#define IS_ROCKETLAKE(devid)	(intel_get_device_info(devid)->is_rocketlake)
+#define IS_DG1(devid)		(intel_get_device_info(devid)->is_dg1)
+#define IS_DG2(devid)		(intel_get_device_info(devid)->is_dg2)
+#define IS_ALDERLAKE_S(devid)	(intel_get_device_info(devid)->is_alderlake_s)
+#define IS_RAPTORLAKE_S(devid)	(intel_get_device_info(devid)->is_raptorlake_s)
+#define IS_ALDERLAKE_P(devid)	(intel_get_device_info(devid)->is_alderlake_p)
+#define IS_ALDERLAKE_N(devid)	(intel_get_device_info(devid)->is_alderlake_n)
+#define IS_METEORLAKE(devid)	(intel_get_device_info(devid)->is_meteorlake)
+#define IS_PONTEVECCHIO(devid)	(intel_get_device_info(devid)->is_pontevecchio)
+#define IS_LUNARLAKE(devid)	(intel_get_device_info(devid)->is_lunarlake)
+#define IS_BATTLEMAGE(devid)	(intel_get_device_info(devid)->is_battlemage)
+
+#define IS_GEN(devid, x)	(intel_get_device_info(devid)->graphics_ver == x)
+#define AT_LEAST_GEN(devid, x)	(intel_get_device_info(devid)->graphics_ver >= x)
+#define AT_LEAST_DISPLAY(devid, x) (intel_get_device_info(devid)->display_ver >= x)
+
+#define IS_GEN2(devid)		IS_GEN(devid, 2)
+#define IS_GEN3(devid)		IS_GEN(devid, 3)
+#define IS_GEN4(devid)		IS_GEN(devid, 4)
+#define IS_GEN5(devid)		IS_GEN(devid, 5)
+#define IS_GEN6(devid)		IS_GEN(devid, 6)
+#define IS_GEN7(devid)		IS_GEN(devid, 7)
+#define IS_GEN8(devid)		IS_GEN(devid, 8)
+#define IS_GEN9(devid)		IS_GEN(devid, 9)
+#define IS_GEN10(devid)		IS_GEN(devid, 10)
+#define IS_GEN11(devid)		IS_GEN(devid, 11)
+#define IS_GEN12(devid)		IS_GEN(devid, 12)
+
+#define IS_MOBILE(devid)	(intel_get_device_info(devid)->is_mobile)
+#define IS_965(devid)		AT_LEAST_GEN(devid, 4)
+
+#define HAS_BSD_RING(devid)	AT_LEAST_GEN(devid, 5)
+#define HAS_BLT_RING(devid)	AT_LEAST_GEN(devid, 6)
+
+#define HAS_PCH_SPLIT(devid)	(AT_LEAST_GEN(devid, 5) && \
+				 !(IS_VALLEYVIEW(devid) || \
+				   IS_CHERRYVIEW(devid) || \
+				   IS_BROXTON(devid)))
+
+#define HAS_4TILE(devid)	(intel_get_device_info(devid)->has_4tile)
+
+#define HAS_FLATCCS(devid)	(intel_get_device_info(devid)->has_flatccs)
+
+#define HAS_OAM(devid)		(intel_get_device_info(devid)->has_oam)
+
+#endif /* _INTEL_CHIPSET_H */

+ 653 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/intel_device_info.c

@@ -0,0 +1,653 @@
+#include "intel_chipset.h"
+#include "i915_pciids.h"
+#include "i915_pciids_local.h"
+#include "xe_pciids.h"
+
+#include <strings.h> /* ffs() */
+
+// from pciaccess.h
+#define PCI_MATCH_ANY  (~0U)
+
+// from pciaccess.h
+struct pci_id_match {
+    /**
+     * \name Device / vendor matching controls
+     *
+     * Control the search based on the device, vendor, subdevice, or subvendor
+     * IDs.  Setting any of these fields to \c PCI_MATCH_ANY will cause the
+     * field to not be used in the comparison.
+     */
+    /*@{*/
+    uint32_t    vendor_id;
+    uint32_t    device_id;
+    uint32_t    subvendor_id;
+    uint32_t    subdevice_id;
+    /*@}*/
+
+
+    /**
+     * \name Device class matching controls
+     *
+     */
+    /*@{*/
+    uint32_t    device_class;
+    uint32_t    device_class_mask;
+    /*@}*/
+
+    intptr_t    match_data;
+};
+
+static const struct intel_device_info intel_generic_info = {
+	.graphics_ver = 0,
+	.display_ver = 0,
+};
+
+static const struct intel_device_info intel_i810_info = {
+	.graphics_ver = 1,
+	.display_ver = 1,
+	.is_whitney = true,
+	.codename = "solano" /* 815 == "whitney" ? or vice versa? */
+};
+
+static const struct intel_device_info intel_i815_info = {
+	.graphics_ver = 1,
+	.display_ver = 1,
+	.is_whitney = true,
+	.codename = "whitney"
+};
+
+static const struct intel_device_info intel_i830_info = {
+	.graphics_ver = 2,
+	.display_ver = 2,
+	.is_almador = true,
+	.codename = "almador"
+};
+static const struct intel_device_info intel_i845_info = {
+	.graphics_ver = 2,
+	.display_ver = 2,
+	.is_brookdale = true,
+	.codename = "brookdale"
+};
+static const struct intel_device_info intel_i855_info = {
+	.graphics_ver = 2,
+	.display_ver = 2,
+	.is_mobile = true,
+	.is_montara = true,
+	.codename = "montara"
+};
+static const struct intel_device_info intel_i865_info = {
+	.graphics_ver = 2,
+	.display_ver = 2,
+	.is_springdale = true,
+	.codename = "spingdale"
+};
+
+static const struct intel_device_info intel_i915_info = {
+	.graphics_ver = 3,
+	.display_ver = 3,
+	.is_grantsdale = true,
+	.codename = "grantsdale"
+};
+static const struct intel_device_info intel_i915m_info = {
+	.graphics_ver = 3,
+	.display_ver = 3,
+	.is_mobile = true,
+	.is_alviso = true,
+	.codename = "alviso"
+};
+static const struct intel_device_info intel_i945_info = {
+	.graphics_ver = 3,
+	.display_ver = 3,
+	.is_lakeport = true,
+	.codename = "lakeport"
+};
+static const struct intel_device_info intel_i945m_info = {
+	.graphics_ver = 3,
+	.display_ver = 3,
+	.is_mobile = true,
+	.is_calistoga = true,
+	.codename = "calistoga"
+};
+
+static const struct intel_device_info intel_g33_info = {
+	.graphics_ver = 3,
+	.display_ver = 3,
+	.is_bearlake = true,
+	.codename = "bearlake"
+};
+
+static const struct intel_device_info intel_pineview_g_info = {
+	.graphics_ver = 3,
+	.display_ver = 3,
+	.is_pineview = true,
+	.codename = "pineview"
+};
+
+static const struct intel_device_info intel_pineview_m_info = {
+	.graphics_ver = 3,
+	.display_ver = 3,
+	.is_mobile = true,
+	.is_pineview = true,
+	.codename = "pineview"
+};
+
+static const struct intel_device_info intel_i965_info = {
+	.graphics_ver = 4,
+	.display_ver = 4,
+	.is_broadwater = true,
+	.codename = "broadwater"
+};
+
+static const struct intel_device_info intel_i965m_info = {
+	.graphics_ver = 4,
+	.display_ver = 4,
+	.is_mobile = true,
+	.is_crestline = true,
+	.codename = "crestline"
+};
+
+static const struct intel_device_info intel_g45_info = {
+	.graphics_ver = 4,
+	.display_ver = 4,
+	.is_eaglelake = true,
+	.codename = "eaglelake"
+};
+static const struct intel_device_info intel_gm45_info = {
+	.graphics_ver = 4,
+	.display_ver = 4,
+	.is_mobile = true,
+	.is_cantiga = true,
+	.codename = "cantiga"
+};
+
+static const struct intel_device_info intel_ironlake_info = {
+	.graphics_ver = 5,
+	.display_ver = 5,
+	.is_ironlake = true,
+	.codename = "ironlake" /* clarkdale? */
+};
+static const struct intel_device_info intel_ironlake_m_info = {
+	.graphics_ver = 5,
+	.display_ver = 5,
+	.is_mobile = true,
+	.is_arrandale = true,
+	.codename = "arrandale"
+};
+
+static const struct intel_device_info intel_sandybridge_info = {
+	.graphics_ver = 6,
+	.display_ver = 6,
+	.is_sandybridge = true,
+	.codename = "sandybridge"
+};
+static const struct intel_device_info intel_sandybridge_m_info = {
+	.graphics_ver = 6,
+	.display_ver = 6,
+	.is_mobile = true,
+	.is_sandybridge = true,
+	.codename = "sandybridge"
+};
+
+static const struct intel_device_info intel_ivybridge_info = {
+	.graphics_ver = 7,
+	.display_ver = 7,
+	.is_ivybridge = true,
+	.codename = "ivybridge"
+};
+static const struct intel_device_info intel_ivybridge_m_info = {
+	.graphics_ver = 7,
+	.display_ver = 7,
+	.is_mobile = true,
+	.is_ivybridge = true,
+	.codename = "ivybridge"
+};
+
+static const struct intel_device_info intel_valleyview_info = {
+	.graphics_ver = 7,
+	.display_ver = 7,
+	.is_valleyview = true,
+	.codename = "valleyview"
+};
+
+#define HASWELL_FIELDS \
+	.graphics_ver = 7, \
+	.display_ver = 7, \
+	.is_haswell = true, \
+	.codename = "haswell"
+
+static const struct intel_device_info intel_haswell_gt1_info = {
+	HASWELL_FIELDS,
+	.gt = 1,
+};
+
+static const struct intel_device_info intel_haswell_gt2_info = {
+	HASWELL_FIELDS,
+	.gt = 2,
+};
+
+static const struct intel_device_info intel_haswell_gt3_info = {
+	HASWELL_FIELDS,
+	.gt = 3,
+};
+
+#define BROADWELL_FIELDS \
+	.graphics_ver = 8, \
+	.display_ver = 8, \
+	.is_broadwell = true, \
+	.codename = "broadwell"
+
+static const struct intel_device_info intel_broadwell_gt1_info = {
+	BROADWELL_FIELDS,
+	.gt = 1,
+};
+
+static const struct intel_device_info intel_broadwell_gt2_info = {
+	BROADWELL_FIELDS,
+	.gt = 2,
+};
+
+static const struct intel_device_info intel_broadwell_gt3_info = {
+	BROADWELL_FIELDS,
+	.gt = 3,
+};
+
+static const struct intel_device_info intel_broadwell_unknown_info = {
+	BROADWELL_FIELDS,
+};
+
+static const struct intel_device_info intel_cherryview_info = {
+	.graphics_ver = 8,
+	.display_ver = 8,
+	.is_cherryview = true,
+	.codename = "cherryview"
+};
+
+#define SKYLAKE_FIELDS \
+	.graphics_ver = 9, \
+	.display_ver = 9, \
+	.codename = "skylake", \
+	.is_skylake = true
+
+static const struct intel_device_info intel_skylake_gt1_info = {
+	SKYLAKE_FIELDS,
+	.gt = 1,
+};
+
+static const struct intel_device_info intel_skylake_gt2_info = {
+	SKYLAKE_FIELDS,
+	.gt = 2,
+};
+
+static const struct intel_device_info intel_skylake_gt3_info = {
+	SKYLAKE_FIELDS,
+	.gt = 3,
+};
+
+static const struct intel_device_info intel_skylake_gt4_info = {
+	SKYLAKE_FIELDS,
+	.gt = 4,
+};
+
+static const struct intel_device_info intel_broxton_info = {
+	.graphics_ver = 9,
+	.display_ver = 9,
+	.is_broxton = true,
+	.codename = "broxton"
+};
+
+#define KABYLAKE_FIELDS \
+	.graphics_ver = 9, \
+	.display_ver = 9, \
+	.is_kabylake = true, \
+	.codename = "kabylake"
+
+static const struct intel_device_info intel_kabylake_gt1_info = {
+	KABYLAKE_FIELDS,
+	.gt = 1,
+};
+
+static const struct intel_device_info intel_kabylake_gt2_info = {
+	KABYLAKE_FIELDS,
+	.gt = 2,
+};
+
+static const struct intel_device_info intel_kabylake_gt3_info = {
+	KABYLAKE_FIELDS,
+	.gt = 3,
+};
+
+static const struct intel_device_info intel_kabylake_gt4_info = {
+	KABYLAKE_FIELDS,
+	.gt = 4,
+};
+
+static const struct intel_device_info intel_geminilake_info = {
+	.graphics_ver = 9,
+	.display_ver = 9,
+	.is_geminilake = true,
+	.codename = "geminilake"
+};
+
+#define COFFEELAKE_FIELDS \
+	.graphics_ver = 9, \
+	.display_ver = 9, \
+	.is_coffeelake = true, \
+	.codename = "coffeelake"
+
+static const struct intel_device_info intel_coffeelake_gt1_info = {
+	COFFEELAKE_FIELDS,
+	.gt = 1,
+};
+
+static const struct intel_device_info intel_coffeelake_gt2_info = {
+	COFFEELAKE_FIELDS,
+	.gt = 2,
+};
+
+static const struct intel_device_info intel_coffeelake_gt3_info = {
+	COFFEELAKE_FIELDS,
+	.gt = 3,
+};
+
+#define COMETLAKE_FIELDS \
+	.graphics_ver = 9, \
+	.display_ver = 9, \
+	.is_cometlake = true, \
+	.codename = "cometlake"
+
+static const struct intel_device_info intel_cometlake_gt1_info = {
+	COMETLAKE_FIELDS,
+	.gt = 1,
+};
+
+static const struct intel_device_info intel_cometlake_gt2_info = {
+	COMETLAKE_FIELDS,
+	.gt = 2,
+};
+
+static const struct intel_device_info intel_cannonlake_info = {
+	.graphics_ver = 10,
+	.display_ver = 10,
+	.is_cannonlake = true,
+	.codename = "cannonlake"
+};
+
+static const struct intel_device_info intel_icelake_info = {
+	.graphics_ver = 11,
+	.display_ver = 11,
+	.is_icelake = true,
+	.codename = "icelake"
+};
+
+static const struct intel_device_info intel_elkhartlake_info = {
+	.graphics_ver = 11,
+	.display_ver = 11,
+	.is_elkhartlake = true,
+	.codename = "elkhartlake"
+};
+
+static const struct intel_device_info intel_jasperlake_info = {
+	.graphics_ver = 11,
+	.display_ver = 11,
+	.is_jasperlake = true,
+	.codename = "jasperlake"
+};
+
+static const struct intel_device_info intel_tigerlake_gt1_info = {
+	.graphics_ver = 12,
+	.display_ver = 12,
+	.is_tigerlake = true,
+	.codename = "tigerlake",
+	.gt = 1,
+};
+
+static const struct intel_device_info intel_tigerlake_gt2_info = {
+	.graphics_ver = 12,
+	.display_ver = 12,
+	.is_tigerlake = true,
+	.codename = "tigerlake",
+	.gt = 2,
+};
+
+static const struct intel_device_info intel_rocketlake_info = {
+	.graphics_ver = 12,
+	.display_ver = 12,
+	.is_rocketlake = true,
+	.codename = "rocketlake"
+};
+
+static const struct intel_device_info intel_dg1_info = {
+	.graphics_ver = 12,
+	.graphics_rel = 10,
+	.display_ver = 12,
+	.is_dg1 = true,
+	.codename = "dg1"
+};
+
+static const struct intel_device_info intel_dg2_info = {
+	.graphics_ver = 12,
+	.graphics_rel = 55,
+	.display_ver = 13,
+	.has_4tile = true,
+	.is_dg2 = true,
+	.codename = "dg2",
+	.has_flatccs = true,
+};
+
+static const struct intel_device_info intel_alderlake_s_info = {
+	.graphics_ver = 12,
+	.display_ver = 12,
+	.is_alderlake_s = true,
+	.codename = "alderlake_s"
+};
+
+static const struct intel_device_info intel_raptorlake_s_info = {
+	.graphics_ver = 12,
+	.display_ver = 12,
+	.is_raptorlake_s = true,
+	.codename = "raptorlake_s"
+};
+
+static const struct intel_device_info intel_alderlake_p_info = {
+	.graphics_ver = 12,
+	.display_ver = 13,
+	.is_alderlake_p = true,
+	.codename = "alderlake_p"
+};
+
+static const struct intel_device_info intel_alderlake_n_info = {
+	.graphics_ver = 12,
+	.display_ver = 13,
+	.is_alderlake_n = true,
+	.codename = "alderlake_n"
+};
+
+static const struct intel_device_info intel_ats_m_info = {
+	.graphics_ver = 12,
+	.graphics_rel = 55,
+	.display_ver = 0, /* no display support */
+	.is_dg2 = true,
+	.has_4tile = true,
+	.codename = "ats_m",
+	.has_flatccs = true,
+};
+
+static const struct intel_device_info intel_meteorlake_info = {
+	.graphics_ver = 12,
+	.graphics_rel = 70,
+	.display_ver = 14,
+	.has_4tile = true,
+	.has_oam = true,
+	.is_meteorlake = true,
+	.codename = "meteorlake",
+};
+
+static const struct intel_device_info intel_pontevecchio_info = {
+	.graphics_ver = 12,
+	.graphics_rel = 60,
+	.is_pontevecchio = true,
+	.codename = "pontevecchio",
+};
+
+static const struct intel_device_info intel_lunarlake_info = {
+	.graphics_ver = 20,
+	.graphics_rel = 4,
+	.display_ver = 20,
+	.has_4tile = true,
+	.has_flatccs = true,
+	.has_oam = true,
+	.is_lunarlake = true,
+	.codename = "lunarlake",
+};
+
+static const struct intel_device_info intel_battlemage_info = {
+	.graphics_ver = 20,
+	.graphics_rel = 1,
+	.display_ver = 14,
+	.has_4tile = true,
+	.has_flatccs = true,
+	.is_battlemage = true,
+	.codename = "battlemage",
+};
+
+static const struct pci_id_match intel_device_match[] = {
+	INTEL_I810_IDS(INTEL_VGA_DEVICE, &intel_i810_info),
+	INTEL_I815_IDS(INTEL_VGA_DEVICE, &intel_i815_info),
+
+	INTEL_I830_IDS(INTEL_VGA_DEVICE, &intel_i830_info),
+	INTEL_I845G_IDS(INTEL_VGA_DEVICE, &intel_i845_info),
+	INTEL_I85X_IDS(INTEL_VGA_DEVICE, &intel_i855_info),
+	INTEL_I865G_IDS(INTEL_VGA_DEVICE, &intel_i865_info),
+
+	INTEL_I915G_IDS(INTEL_VGA_DEVICE, &intel_i915_info),
+	INTEL_I915GM_IDS(INTEL_VGA_DEVICE, &intel_i915m_info),
+	INTEL_I945G_IDS(INTEL_VGA_DEVICE, &intel_i945_info),
+	INTEL_I945GM_IDS(INTEL_VGA_DEVICE, &intel_i945m_info),
+
+	INTEL_G33_IDS(INTEL_VGA_DEVICE, &intel_g33_info),
+	INTEL_PNV_G_IDS(INTEL_VGA_DEVICE, &intel_pineview_g_info),
+	INTEL_PNV_M_IDS(INTEL_VGA_DEVICE, &intel_pineview_m_info),
+
+	INTEL_I965G_IDS(INTEL_VGA_DEVICE, &intel_i965_info),
+	INTEL_I965GM_IDS(INTEL_VGA_DEVICE, &intel_i965m_info),
+
+	INTEL_G45_IDS(INTEL_VGA_DEVICE, &intel_g45_info),
+	INTEL_GM45_IDS(INTEL_VGA_DEVICE, &intel_gm45_info),
+
+	INTEL_ILK_D_IDS(INTEL_VGA_DEVICE, &intel_ironlake_info),
+	INTEL_ILK_M_IDS(INTEL_VGA_DEVICE, &intel_ironlake_m_info),
+
+	INTEL_SNB_D_IDS(INTEL_VGA_DEVICE, &intel_sandybridge_info),
+	INTEL_SNB_M_IDS(INTEL_VGA_DEVICE, &intel_sandybridge_m_info),
+
+	INTEL_IVB_D_IDS(INTEL_VGA_DEVICE, &intel_ivybridge_info),
+	INTEL_IVB_M_IDS(INTEL_VGA_DEVICE, &intel_ivybridge_m_info),
+
+	INTEL_HSW_GT1_IDS(INTEL_VGA_DEVICE, &intel_haswell_gt1_info),
+	INTEL_HSW_GT2_IDS(INTEL_VGA_DEVICE, &intel_haswell_gt2_info),
+	INTEL_HSW_GT3_IDS(INTEL_VGA_DEVICE, &intel_haswell_gt3_info),
+
+	INTEL_VLV_IDS(INTEL_VGA_DEVICE, &intel_valleyview_info),
+
+	INTEL_BDW_GT1_IDS(INTEL_VGA_DEVICE, &intel_broadwell_gt1_info),
+	INTEL_BDW_GT2_IDS(INTEL_VGA_DEVICE, &intel_broadwell_gt2_info),
+	INTEL_BDW_GT3_IDS(INTEL_VGA_DEVICE, &intel_broadwell_gt3_info),
+	INTEL_BDW_RSVD_IDS(INTEL_VGA_DEVICE, &intel_broadwell_unknown_info),
+
+	INTEL_CHV_IDS(INTEL_VGA_DEVICE, &intel_cherryview_info),
+
+	INTEL_SKL_GT1_IDS(INTEL_VGA_DEVICE, &intel_skylake_gt1_info),
+	INTEL_SKL_GT2_IDS(INTEL_VGA_DEVICE, &intel_skylake_gt2_info),
+	INTEL_SKL_GT3_IDS(INTEL_VGA_DEVICE, &intel_skylake_gt3_info),
+	INTEL_SKL_GT4_IDS(INTEL_VGA_DEVICE, &intel_skylake_gt4_info),
+
+	INTEL_BXT_IDS(INTEL_VGA_DEVICE, &intel_broxton_info),
+
+	INTEL_KBL_GT1_IDS(INTEL_VGA_DEVICE, &intel_kabylake_gt1_info),
+	INTEL_KBL_GT2_IDS(INTEL_VGA_DEVICE, &intel_kabylake_gt2_info),
+	INTEL_KBL_GT3_IDS(INTEL_VGA_DEVICE, &intel_kabylake_gt3_info),
+	INTEL_KBL_GT4_IDS(INTEL_VGA_DEVICE, &intel_kabylake_gt4_info),
+	INTEL_AML_KBL_GT2_IDS(INTEL_VGA_DEVICE, &intel_kabylake_gt2_info),
+
+	INTEL_GLK_IDS(INTEL_VGA_DEVICE, &intel_geminilake_info),
+
+	INTEL_CFL_S_GT1_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt1_info),
+	INTEL_CFL_S_GT2_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt2_info),
+	INTEL_CFL_H_GT1_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt1_info),
+	INTEL_CFL_H_GT2_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt2_info),
+	INTEL_CFL_U_GT2_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt2_info),
+	INTEL_CFL_U_GT3_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt3_info),
+	INTEL_WHL_U_GT1_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt1_info),
+	INTEL_WHL_U_GT2_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt2_info),
+	INTEL_WHL_U_GT3_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt3_info),
+	INTEL_AML_CFL_GT2_IDS(INTEL_VGA_DEVICE, &intel_coffeelake_gt2_info),
+
+	INTEL_CML_GT1_IDS(INTEL_VGA_DEVICE, &intel_cometlake_gt1_info),
+	INTEL_CML_GT2_IDS(INTEL_VGA_DEVICE, &intel_cometlake_gt2_info),
+	INTEL_CML_U_GT1_IDS(INTEL_VGA_DEVICE, &intel_cometlake_gt1_info),
+	INTEL_CML_U_GT2_IDS(INTEL_VGA_DEVICE, &intel_cometlake_gt2_info),
+
+	INTEL_CNL_IDS(INTEL_VGA_DEVICE, &intel_cannonlake_info),
+
+	INTEL_ICL_IDS(INTEL_VGA_DEVICE, &intel_icelake_info),
+
+	INTEL_EHL_IDS(INTEL_VGA_DEVICE, &intel_elkhartlake_info),
+	INTEL_JSL_IDS(INTEL_VGA_DEVICE, &intel_jasperlake_info),
+
+	INTEL_TGL_GT1_IDS(INTEL_VGA_DEVICE, &intel_tigerlake_gt1_info),
+	INTEL_TGL_GT2_IDS(INTEL_VGA_DEVICE, &intel_tigerlake_gt2_info),
+	INTEL_RKL_IDS(INTEL_VGA_DEVICE, &intel_rocketlake_info),
+
+	INTEL_DG1_IDS(INTEL_VGA_DEVICE, &intel_dg1_info),
+	INTEL_DG2_IDS(INTEL_VGA_DEVICE, &intel_dg2_info),
+
+	INTEL_ADLS_IDS(INTEL_VGA_DEVICE, &intel_alderlake_s_info),
+	INTEL_RPLS_IDS(INTEL_VGA_DEVICE, &intel_raptorlake_s_info),
+	INTEL_ADLP_IDS(INTEL_VGA_DEVICE, &intel_alderlake_p_info),
+	INTEL_RPLU_IDS(INTEL_VGA_DEVICE, &intel_alderlake_p_info),
+	INTEL_RPLP_IDS(INTEL_VGA_DEVICE, &intel_alderlake_p_info),
+	INTEL_ADLN_IDS(INTEL_VGA_DEVICE, &intel_alderlake_n_info),
+
+	INTEL_ATS_M_IDS(INTEL_VGA_DEVICE, &intel_ats_m_info),
+
+	INTEL_MTL_IDS(INTEL_VGA_DEVICE, &intel_meteorlake_info),
+
+	INTEL_PVC_IDS(INTEL_VGA_DEVICE, &intel_pontevecchio_info),
+
+	XE_LNL_IDS(INTEL_VGA_DEVICE, &intel_lunarlake_info),
+
+	XE_BMG_IDS(INTEL_VGA_DEVICE, &intel_battlemage_info),
+
+	INTEL_VGA_DEVICE(PCI_MATCH_ANY, &intel_generic_info),
+};
+
+/**
+ * intel_get_device_info:
+ * @devid: pci device id
+ *
+ * Looks up the Intel GFX device info for the given device id.
+ *
+ * Returns:
+ * The associated intel_get_device_info
+ */
+const struct intel_device_info *intel_get_device_info(uint16_t devid)
+{
+	static const struct intel_device_info *cache = &intel_generic_info;
+	static uint16_t cached_devid;
+	int i;
+
+	if (cached_devid == devid)
+		goto out;
+
+	/* XXX Presort table and bsearch! */
+	for (i = 0; intel_device_match[i].device_id != PCI_MATCH_ANY; i++) {
+		if (devid == intel_device_match[i].device_id)
+			break;
+	}
+
+	cached_devid = devid;
+	cache = (void *)intel_device_match[i].match_data;
+
+out:
+	return cache;
+}

+ 697 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/intel_gpu_top.c

@@ -0,0 +1,697 @@
+/*
+ * Copyright © 2007-2023 Intel Corporation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ */
+
+#include <assert.h>
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <limits.h>
+#include <locale.h>
+#include <math.h>
+#include <poll.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <termios.h>
+#include <time.h>
+#include <sys/sysmacros.h>
+
+#include <stdarg.h>
+
+#include "intel_gpu_top.h"
+#include "i915_drm.h"
+#include "igt_perf.h"
+
+#ifdef __clang__ //? Workaround for missing asprintf when compiling with clang, taken from https://stackoverflow.com/a/4899487
+int asprintf(char **ret, const char *format, ...)
+{
+    va_list ap;
+
+    *ret = NULL;  /* Ensure value can be passed to free() */
+
+    va_start(ap, format);
+    int count = vsnprintf(NULL, 0, format, ap);
+    va_end(ap);
+
+    if (count >= 0)
+    {
+        char* buffer = malloc(count + 1);
+        if (buffer == NULL)
+            return -1;
+
+        va_start(ap, format);
+        count = vsnprintf(buffer, count + 1, format, ap);
+        va_end(ap);
+
+        if (count < 0)
+        {
+            free(buffer);
+            return count;
+        }
+        *ret = buffer;
+    }
+
+    return count;
+}
+#endif
+
+__attribute__((format(scanf,3,4)))
+static int igt_sysfs_scanf(int dir, const char *attr, const char *fmt, ...)
+{
+	FILE *file;
+	int fd;
+	int ret = -1;
+
+	fd = openat(dir, attr, O_RDONLY);
+	if (fd < 0)
+		return -1;
+
+	file = fdopen(fd, "r");
+	if (file) {
+		va_list ap;
+
+		va_start(ap, fmt);
+		ret = vfscanf(file, fmt, ap);
+		va_end(ap);
+
+		fclose(file);
+	} else {
+		close(fd);
+	}
+
+	return ret;
+}
+
+static int pmu_parse(struct pmu_counter *pmu, const char *path, const char *str)
+{
+	locale_t locale, oldlocale;
+	bool result = true;
+	char buf[128] = {};
+	int dir;
+
+	dir = open(path, O_RDONLY);
+	if (dir < 0)
+		return -errno;
+
+	/* Replace user environment with plain C to match kernel format */
+	locale = newlocale(LC_ALL, "C", 0);
+	oldlocale = uselocale(locale);
+
+	result &= igt_sysfs_scanf(dir, "type", "%"PRIu64, &pmu->type) == 1;
+
+	snprintf(buf, sizeof(buf) - 1, "events/%s", str);
+	result &= igt_sysfs_scanf(dir, buf, "event=%"PRIx64, &pmu->config) == 1;
+
+	snprintf(buf, sizeof(buf) - 1, "events/%s.scale", str);
+	result &= igt_sysfs_scanf(dir, buf, "%lf", &pmu->scale) == 1;
+
+	snprintf(buf, sizeof(buf) - 1, "events/%s.unit", str);
+	result &= igt_sysfs_scanf(dir, buf, "%127s", buf) == 1;
+	pmu->units = strdup(buf);
+
+	uselocale(oldlocale);
+	freelocale(locale);
+
+	close(dir);
+
+	if (!result)
+		return -EINVAL;
+
+	if (isnan(pmu->scale) || !pmu->scale)
+		return -ERANGE;
+
+	return 0;
+}
+
+static int rapl_parse(struct pmu_counter *pmu, const char *str)
+{
+	const char *expected_units = "Joules";
+	int err;
+
+	err = pmu_parse(pmu, "/sys/devices/power", str);
+	if (err < 0)
+		return err;
+
+	if (!pmu->units || strcmp(pmu->units, expected_units)) {
+		fprintf(stderr,
+			"Unexpected units for RAPL %s: found '%s', expected '%s'\n",
+			str, pmu->units, expected_units);
+	}
+
+	return 0;
+}
+
+static void
+rapl_open(struct pmu_counter *pmu,
+	  const char *domain,
+	  struct engines *engines)
+{
+	int fd;
+
+	if (rapl_parse(pmu, domain) < 0)
+		return;
+
+	fd = igt_perf_open_group(pmu->type, pmu->config, engines->rapl_fd);
+	if (fd < 0)
+		return;
+
+	if (engines->rapl_fd == -1)
+		engines->rapl_fd = fd;
+
+	pmu->idx = engines->num_rapl++;
+	pmu->present = true;
+}
+
+static void gpu_power_open(struct pmu_counter *pmu,
+			   struct engines *engines)
+{
+	rapl_open(pmu, "energy-gpu", engines);
+}
+
+static void pkg_power_open(struct pmu_counter *pmu,
+			   struct engines *engines)
+{
+	rapl_open(pmu, "energy-pkg", engines);
+}
+
+static uint64_t
+get_pmu_config(int dirfd, const char *name, const char *counter)
+{
+	char buf[128], *p;
+	int fd, ret;
+
+	ret = snprintf(buf, sizeof(buf), "%s-%s", name, counter);
+	if (ret < 0 || ret == sizeof(buf))
+		return -1;
+
+	fd = openat(dirfd, buf, O_RDONLY);
+	if (fd < 0)
+		return -1;
+
+	ret = read(fd, buf, sizeof(buf));
+	close(fd);
+	if (ret <= 0)
+		return -1;
+
+	p = index(buf, '0');
+	if (!p)
+		return -1;
+
+	return strtoul(p, NULL, 0);
+}
+
+#define engine_ptr(engines, n) (&engines->engine + (n))
+
+static const char *class_display_name(unsigned int class)
+{
+	switch (class) {
+	case I915_ENGINE_CLASS_RENDER:
+		return "Render/3D";
+	case I915_ENGINE_CLASS_COPY:
+		return "Blitter";
+	case I915_ENGINE_CLASS_VIDEO:
+		return "Video";
+	case I915_ENGINE_CLASS_VIDEO_ENHANCE:
+		return "VideoEnhance";
+	case I915_ENGINE_CLASS_COMPUTE:
+		return "Compute";
+	default:
+		return "[unknown]";
+	}
+}
+
+static const char *class_short_name(unsigned int class)
+{
+	switch (class) {
+	case I915_ENGINE_CLASS_RENDER:
+		return "RCS";
+	case I915_ENGINE_CLASS_COPY:
+		return "BCS";
+	case I915_ENGINE_CLASS_VIDEO:
+		return "VCS";
+	case I915_ENGINE_CLASS_VIDEO_ENHANCE:
+		return "VECS";
+	case I915_ENGINE_CLASS_COMPUTE:
+		return "CCS";
+	default:
+		return "UNKN";
+	}
+}
+
+static int engine_cmp(const void *__a, const void *__b)
+{
+	const struct engine *a = (struct engine *)__a;
+	const struct engine *b = (struct engine *)__b;
+
+	if (a->class != b->class)
+		return a->class - b->class;
+	else
+		return a->instance - b->instance;
+}
+
+#define is_igpu(x) (strcmp(x, "i915") == 0)
+
+struct engines *discover_engines(const char *device)
+{
+	char sysfs_root[PATH_MAX];
+	struct engines *engines;
+	struct dirent *dent;
+	int ret = 0;
+	DIR *d;
+
+	snprintf(sysfs_root, sizeof(sysfs_root),
+		 "/sys/devices/%s/events", device);
+
+	engines = malloc(sizeof(struct engines));
+	if (!engines)
+		return NULL;
+
+	memset(engines, 0, sizeof(*engines));
+
+	engines->num_engines = 0;
+	engines->device = device;
+	engines->discrete = !is_igpu(device);
+
+	d = opendir(sysfs_root);
+	if (!d)
+		goto err;
+
+	while ((dent = readdir(d)) != NULL) {
+		const char *endswith = "-busy";
+		const unsigned int endlen = strlen(endswith);
+		struct engine *engine =
+				engine_ptr(engines, engines->num_engines);
+		char buf[256];
+
+		if (dent->d_type != DT_REG)
+			continue;
+
+		if (strlen(dent->d_name) >= sizeof(buf)) {
+			ret = ENAMETOOLONG;
+			break;
+		}
+
+		strcpy(buf, dent->d_name);
+
+		/* xxxN-busy */
+		if (strlen(buf) < (endlen + 4))
+			continue;
+		if (strcmp(&buf[strlen(buf) - endlen], endswith))
+			continue;
+
+		memset(engine, 0, sizeof(*engine));
+
+		buf[strlen(buf) - endlen] = 0;
+		engine->name = strdup(buf);
+		if (!engine->name) {
+			ret = errno;
+			break;
+		}
+
+		engine->busy.config = get_pmu_config(dirfd(d), engine->name,
+						     "busy");
+		if (engine->busy.config == -1) {
+			ret = ENOENT;
+			break;
+		}
+
+		/* Double check config is an engine config. */
+		if (engine->busy.config >= __I915_PMU_OTHER(0)) {
+			free((void *)engine->name);
+			continue;
+		}
+
+		engine->class = (engine->busy.config &
+				 (__I915_PMU_OTHER(0) - 1)) >>
+				I915_PMU_CLASS_SHIFT;
+
+		engine->instance = (engine->busy.config >>
+				    I915_PMU_SAMPLE_BITS) &
+				    ((1 << I915_PMU_SAMPLE_INSTANCE_BITS) - 1);
+
+		ret = asprintf(&engine->display_name, "%s/%u",
+			       class_display_name(engine->class),
+			       engine->instance);
+		if (ret <= 0) {
+			ret = errno;
+			break;
+		}
+
+		ret = asprintf(&engine->short_name, "%s/%u",
+			       class_short_name(engine->class),
+			       engine->instance);
+		if (ret <= 0) {
+			ret = errno;
+			break;
+		}
+
+		engines->num_engines++;
+		engines = realloc(engines, sizeof(struct engines) +
+				  engines->num_engines * sizeof(struct engine));
+		if (!engines) {
+			ret = errno;
+			break;
+		}
+
+		ret = 0;
+	}
+
+	if (ret) {
+		errno = ret;
+		goto err;
+	}
+
+	qsort(engine_ptr(engines, 0), engines->num_engines,
+	      sizeof(struct engine), engine_cmp);
+
+	engines->root = d;
+
+	return engines;
+
+err:
+	free(engines);
+
+	return NULL;
+}
+
+void free_engines(struct engines *engines)
+{
+	struct pmu_counter **pmu, *free_list[] = {
+		&engines->r_gpu,
+		&engines->r_pkg,
+		&engines->imc_reads,
+		&engines->imc_writes,
+		NULL
+	};
+	unsigned int i;
+
+	if (!engines)
+		return;
+
+	for (pmu = &free_list[0]; *pmu; pmu++) {
+		if ((*pmu)->present)
+			free((char *)(*pmu)->units);
+	}
+
+	for (i = 0; i < engines->num_engines; i++) {
+		struct engine *engine = engine_ptr(engines, i);
+
+		free((char *)engine->name);
+		free((char *)engine->short_name);
+		free((char *)engine->display_name);
+	}
+
+	closedir(engines->root);
+
+	free(engines->class);
+	free(engines);
+}
+
+#define _open_pmu(type, cnt, pmu, fd) \
+({ \
+	int fd__; \
+\
+	fd__ = igt_perf_open_group((type), (pmu)->config, (fd)); \
+	if (fd__ >= 0) { \
+		if ((fd) == -1) \
+			(fd) = fd__; \
+		(pmu)->present = true; \
+		(pmu)->idx = (cnt)++; \
+	} \
+\
+	fd__; \
+})
+
+static int imc_parse(struct pmu_counter *pmu, const char *str)
+{
+	return pmu_parse(pmu, "/sys/devices/uncore_imc", str);
+}
+
+static void
+imc_open(struct pmu_counter *pmu,
+	 const char *domain,
+	 struct engines *engines)
+{
+	int fd;
+
+	if (imc_parse(pmu, domain) < 0)
+		return;
+
+	fd = igt_perf_open_group(pmu->type, pmu->config, engines->imc_fd);
+	if (fd < 0)
+		return;
+
+	if (engines->imc_fd == -1)
+		engines->imc_fd = fd;
+
+	pmu->idx = engines->num_imc++;
+	pmu->present = true;
+}
+
+static void imc_writes_open(struct pmu_counter *pmu, struct engines *engines)
+{
+	imc_open(pmu, "data_writes", engines);
+}
+
+static void imc_reads_open(struct pmu_counter *pmu, struct engines *engines)
+{
+	imc_open(pmu, "data_reads", engines);
+}
+
+static int get_num_gts(uint64_t type)
+{
+	int fd, cnt;
+
+	errno = 0;
+	for (cnt = 0; cnt < MAX_GTS; cnt++) {
+		fd = igt_perf_open(type, __I915_PMU_INTERRUPTS(cnt));
+		if (fd < 0)
+			break;
+
+		close(fd);
+	}
+
+	if (!cnt || (errno && errno != ENOENT))
+		cnt = -errno;
+
+	return cnt;
+}
+
+static void init_aggregate_counters(struct engines *engines)
+{
+	struct pmu_counter *pmu;
+
+	pmu = &engines->freq_req;
+	pmu->type = igt_perf_type_id(engines->device);
+	pmu->config = I915_PMU_REQUESTED_FREQUENCY;
+	pmu->present = true;
+
+	pmu = &engines->freq_act;
+	pmu->type = igt_perf_type_id(engines->device);
+	pmu->config = I915_PMU_ACTUAL_FREQUENCY;
+	pmu->present = true;
+
+	pmu = &engines->rc6;
+	pmu->type = igt_perf_type_id(engines->device);
+	pmu->config = I915_PMU_RC6_RESIDENCY;
+	pmu->present = true;
+}
+
+int pmu_init(struct engines *engines)
+{
+	unsigned int i;
+	int fd;
+	uint64_t type = igt_perf_type_id(engines->device);
+
+	engines->fd = -1;
+	engines->num_counters = 0;
+	engines->num_gts = get_num_gts(type);
+	if (engines->num_gts <= 0)
+		return -1;
+
+	engines->irq.config = I915_PMU_INTERRUPTS;
+	fd = _open_pmu(type, engines->num_counters, &engines->irq, engines->fd);
+	if (fd < 0)
+		return -1;
+
+	init_aggregate_counters(engines);
+
+	for (i = 0; i < engines->num_gts; i++) {
+		engines->freq_req_gt[i].config = __I915_PMU_REQUESTED_FREQUENCY(i);
+		_open_pmu(type, engines->num_counters, &engines->freq_req_gt[i], engines->fd);
+
+		engines->freq_act_gt[i].config = __I915_PMU_ACTUAL_FREQUENCY(i);
+		_open_pmu(type, engines->num_counters, &engines->freq_act_gt[i], engines->fd);
+
+		engines->rc6_gt[i].config = __I915_PMU_RC6_RESIDENCY(i);
+		_open_pmu(type, engines->num_counters, &engines->rc6_gt[i], engines->fd);
+	}
+
+	for (i = 0; i < engines->num_engines; i++) {
+		struct engine *engine = engine_ptr(engines, i);
+		struct {
+			struct pmu_counter *pmu;
+			const char *counter;
+		} *cnt, counters[] = {
+			{ .pmu = &engine->busy, .counter = "busy" },
+			{ .pmu = &engine->wait, .counter = "wait" },
+			{ .pmu = &engine->sema, .counter = "sema" },
+			{ .pmu = NULL, .counter = NULL },
+		};
+
+		for (cnt = counters; cnt->pmu; cnt++) {
+			if (!cnt->pmu->config)
+				cnt->pmu->config =
+					get_pmu_config(dirfd(engines->root),
+						       engine->name,
+						       cnt->counter);
+			fd = _open_pmu(type, engines->num_counters, cnt->pmu,
+				       engines->fd);
+			if (fd >= 0)
+				engine->num_counters++;
+		}
+	}
+
+	engines->rapl_fd = -1;
+	if (!engines->discrete) {
+		gpu_power_open(&engines->r_gpu, engines);
+		pkg_power_open(&engines->r_pkg, engines);
+	}
+
+	engines->imc_fd = -1;
+	imc_reads_open(&engines->imc_reads, engines);
+	imc_writes_open(&engines->imc_writes, engines);
+
+	return 0;
+}
+
+static uint64_t pmu_read_multi(int fd, unsigned int num, uint64_t *val)
+{
+	uint64_t buf[2 + num];
+	unsigned int i;
+	ssize_t len;
+
+	memset(buf, 0, sizeof(buf));
+
+	len = read(fd, buf, sizeof(buf));
+	assert(len == sizeof(buf));
+
+	for (i = 0; i < num; i++)
+		val[i] = buf[2 + i];
+
+	return buf[1];
+}
+
+double pmu_calc(struct pmu_pair *p, double d, double t, double s)
+{
+	double v;
+
+	v = p->cur - p->prev;
+	v /= d;
+	v /= t;
+	v *= s;
+
+	if (s == 100.0 && v > 100.0)
+		v = 100.0;
+
+	return v;
+}
+
+static void __update_sample(struct pmu_counter *counter, uint64_t val)
+{
+	counter->val.prev = counter->val.cur;
+	counter->val.cur = val;
+}
+
+static void update_sample(struct pmu_counter *counter, uint64_t *val)
+{
+	if (counter->present)
+		__update_sample(counter, val[counter->idx]);
+}
+
+void pmu_sample(struct engines *engines)
+{
+	const int num_val = engines->num_counters;
+	uint64_t val[2 + num_val];
+	unsigned int i;
+
+	engines->ts.prev = engines->ts.cur;
+	engines->ts.cur = pmu_read_multi(engines->fd, num_val, val);
+
+	engines->freq_req.val.cur = engines->freq_req.val.prev = 0;
+	engines->freq_act.val.cur = engines->freq_act.val.prev = 0;
+	engines->rc6.val.cur = engines->rc6.val.prev = 0;
+
+	for (i = 0; i < engines->num_gts; i++) {
+		update_sample(&engines->freq_req_gt[i], val);
+		engines->freq_req.val.cur += engines->freq_req_gt[i].val.cur;
+		engines->freq_req.val.prev += engines->freq_req_gt[i].val.prev;
+
+		update_sample(&engines->freq_act_gt[i], val);
+		engines->freq_act.val.cur += engines->freq_act_gt[i].val.cur;
+		engines->freq_act.val.prev += engines->freq_act_gt[i].val.prev;
+
+		update_sample(&engines->rc6_gt[i], val);
+		engines->rc6.val.cur += engines->rc6_gt[i].val.cur;
+		engines->rc6.val.prev += engines->rc6_gt[i].val.prev;
+	}
+
+	engines->freq_req.val.cur /= engines->num_gts;
+	engines->freq_req.val.prev /= engines->num_gts;
+
+	engines->freq_act.val.cur /= engines->num_gts;
+	engines->freq_act.val.prev /= engines->num_gts;
+
+	engines->rc6.val.cur /= engines->num_gts;
+	engines->rc6.val.prev /= engines->num_gts;
+
+	update_sample(&engines->irq, val);
+
+	for (i = 0; i < engines->num_engines; i++) {
+		struct engine *engine = engine_ptr(engines, i);
+
+		update_sample(&engine->busy, val);
+		update_sample(&engine->sema, val);
+		update_sample(&engine->wait, val);
+	}
+
+	if (engines->num_rapl) {
+		pmu_read_multi(engines->rapl_fd, engines->num_rapl, val);
+		update_sample(&engines->r_gpu, val);
+		update_sample(&engines->r_pkg, val);
+	}
+
+	if (engines->num_imc) {
+		pmu_read_multi(engines->imc_fd, engines->num_imc, val);
+		update_sample(&engines->imc_reads, val);
+		update_sample(&engines->imc_writes, val);
+	}
+}

+ 95 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/intel_gpu_top.h

@@ -0,0 +1,95 @@
+#ifndef INTEL_GPU_TOP_H
+#define INTEL_GPU_TOP_H
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <dirent.h>
+
+struct pmu_pair {
+	uint64_t cur;
+	uint64_t prev;
+};
+
+struct pmu_counter {
+	uint64_t type;
+	uint64_t config;
+	unsigned int idx;
+	struct pmu_pair val;
+	double scale;
+	const char *units;
+	bool present;
+};
+
+struct engine_class {
+	unsigned int engine_class;
+	const char *name;
+	unsigned int num_engines;
+};
+
+struct engine {
+	const char *name;
+	char *display_name;
+	char *short_name;
+
+	unsigned int class;
+	unsigned int instance;
+
+	unsigned int num_counters;
+
+	struct pmu_counter busy;
+	struct pmu_counter wait;
+	struct pmu_counter sema;
+};
+
+#define MAX_GTS 4
+struct engines {
+	unsigned int num_engines;
+	unsigned int num_classes;
+	struct engine_class *class;
+	unsigned int num_counters;
+	DIR *root;
+	int fd;
+	struct pmu_pair ts;
+
+	int rapl_fd;
+	struct pmu_counter r_gpu, r_pkg;
+	unsigned int num_rapl;
+
+	int imc_fd;
+	struct pmu_counter imc_reads;
+	struct pmu_counter imc_writes;
+	unsigned int num_imc;
+
+	struct pmu_counter freq_req;
+	struct pmu_counter freq_req_gt[MAX_GTS];
+	struct pmu_counter freq_act;
+	struct pmu_counter freq_act_gt[MAX_GTS];
+	struct pmu_counter irq;
+	struct pmu_counter rc6;
+	struct pmu_counter rc6_gt[MAX_GTS];
+
+	bool discrete;
+	char *device;
+
+	int num_gts;
+
+	/* Do not edit below this line.
+	 * This structure is reallocated every time a new engine is
+	 * found and size is increased by sizeof (engine).
+	 */
+
+	struct engine engine;
+
+};
+
+struct engines *discover_engines(const char *device);
+void free_engines(struct engines *engines);
+int pmu_init(struct engines *engines);
+void pmu_sample(struct engines *engines);
+double pmu_calc(struct pmu_pair *p, double d, double t, double s);
+
+char* find_intel_gpu_dir();
+char* get_intel_device_id(const char* vendor_path);
+char *get_intel_device_name(const char *device_id);
+
+#endif

+ 97 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/intel_name_lookup_shim.c

@@ -0,0 +1,97 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <dirent.h>
+#include <unistd.h>
+#include <ctype.h>
+
+#include "intel_gpu_top.h"
+#include "intel_chipset.h"
+
+#define VENDOR_ID "0x8086"
+#define SYSFS_PATH "/sys/class/drm"
+#define VENDOR_FILE "vendor"
+#define DEVICE_FILE "device"
+
+char* find_intel_gpu_dir() {
+    DIR *dir;
+    struct dirent *entry;
+    static char path[256];
+    char vendor_path[256];
+    char vendor_id[16];
+
+    if ((dir = opendir(SYSFS_PATH)) == NULL) {
+        perror("opendir");
+        return NULL;
+    }
+
+    while ((entry = readdir(dir)) != NULL) {
+        // Construct the path to the vendor file
+        snprintf(vendor_path, sizeof(vendor_path), "%s/%s/device/%s", SYSFS_PATH, entry->d_name, VENDOR_FILE);
+
+        // Check if the vendor file exists
+        if (access(vendor_path, F_OK) != -1) {
+            FILE *file = fopen(vendor_path, "r");
+            if (file) {
+                if (fgets(vendor_id, sizeof(vendor_id), file)) {
+                    // Trim the newline character
+                    vendor_id[strcspn(vendor_id, "\n")] = 0;
+
+                    if (strcmp(vendor_id, VENDOR_ID) == 0) {
+                        // Return the parent directory (i.e., /sys/class/drm/card*)
+                        snprintf(path, sizeof(path), "%s/%s", SYSFS_PATH, entry->d_name);
+                        fclose(file);
+                        closedir(dir);
+                        return path;
+                    }
+                }
+                fclose(file);
+            }
+        }
+    }
+
+    closedir(dir);
+    return NULL;  // Intel GPU not found
+}
+
+char* get_intel_device_id(const char* gpu_dir) {
+    static char device_path[256];
+    char device_id[16];
+
+    // Construct the path to the device file
+    snprintf(device_path, sizeof(device_path), "%s/device/%s", gpu_dir, DEVICE_FILE);
+
+    FILE *file = fopen(device_path, "r");
+    if (file) {
+        if (fgets(device_id, sizeof(device_id), file)) {
+            fclose(file);
+            // Trim the newline character
+            device_id[strcspn(device_id, "\n")] = 0;
+            // Return a copy of the device ID
+            return strdup(device_id);
+        }
+        fclose(file);
+    } else {
+        perror("fopen");
+    }
+
+    return NULL;
+}
+
+char *get_intel_device_name(const char *device_id) {
+    uint16_t devid = strtol(device_id, NULL, 16);
+    char dev_name[256];
+    char full_name[256];
+    const struct intel_device_info *info = intel_get_device_info(devid);
+    if (info) {
+        if (info->codename == NULL) {
+            strcpy(dev_name, "(unknown)");
+        } else {
+            strcpy(dev_name, info->codename);
+            dev_name[0] = toupper(dev_name[0]);
+        }
+        snprintf(full_name, sizeof(full_name), "Intel %s (Gen%u)", dev_name, info->graphics_ver);
+        return strdup(full_name);
+    }
+    return NULL;
+}

+ 2 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/source.txt

@@ -0,0 +1,2 @@
+0f02dc176959e6296866b1bafd3982e277a5e44b
+https://gitlab.freedesktop.org/drm/igt-gpu-tools.git

+ 218 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/linux/intel_gpu_top/xe_pciids.h

@@ -0,0 +1,218 @@
+/* SPDX-License-Identifier: MIT */
+/*
+ * Copyright © 2022 Intel Corporation
+ */
+
+#ifndef _XE_PCIIDS_H_
+#define _XE_PCIIDS_H_
+
+/*
+ * Lists below can be turned into initializers for a struct pci_device_id
+ * by defining INTEL_VGA_DEVICE:
+ *
+ * #define INTEL_VGA_DEVICE(id, info) { \
+ *	0x8086, id,			\
+ *	~0, ~0,				\
+ *	0x030000, 0xff0000,		\
+ *	(unsigned long) info }
+ *
+ * And then calling like:
+ *
+ * XE_TGL_12_GT1_IDS(INTEL_VGA_DEVICE, ## __VA_ARGS__)
+ *
+ * To turn them into something else, just provide a different macro passed as
+ * first argument.
+ */
+
+/* TGL */
+#define XE_TGL_GT1_IDS(MACRO__, ...)		\
+	MACRO__(0x9A60, ## __VA_ARGS__),	\
+	MACRO__(0x9A68, ## __VA_ARGS__),	\
+	MACRO__(0x9A70, ## __VA_ARGS__)
+
+#define XE_TGL_GT2_IDS(MACRO__, ...)		\
+	MACRO__(0x9A40, ## __VA_ARGS__),	\
+	MACRO__(0x9A49, ## __VA_ARGS__),	\
+	MACRO__(0x9A59, ## __VA_ARGS__),	\
+	MACRO__(0x9A78, ## __VA_ARGS__),	\
+	MACRO__(0x9AC0, ## __VA_ARGS__),	\
+	MACRO__(0x9AC9, ## __VA_ARGS__),	\
+	MACRO__(0x9AD9, ## __VA_ARGS__),	\
+	MACRO__(0x9AF8, ## __VA_ARGS__)
+
+#define XE_TGL_IDS(MACRO__, ...)		\
+	XE_TGL_GT1_IDS(MACRO__, ## __VA_ARGS__),\
+	XE_TGL_GT2_IDS(MACRO__, ## __VA_ARGS__)
+
+/* RKL */
+#define XE_RKL_IDS(MACRO__, ...)		\
+	MACRO__(0x4C80, ## __VA_ARGS__),	\
+	MACRO__(0x4C8A, ## __VA_ARGS__),	\
+	MACRO__(0x4C8B, ## __VA_ARGS__),	\
+	MACRO__(0x4C8C, ## __VA_ARGS__),	\
+	MACRO__(0x4C90, ## __VA_ARGS__),	\
+	MACRO__(0x4C9A, ## __VA_ARGS__)
+
+/* DG1 */
+#define XE_DG1_IDS(MACRO__, ...)		\
+	MACRO__(0x4905, ## __VA_ARGS__),	\
+	MACRO__(0x4906, ## __VA_ARGS__),	\
+	MACRO__(0x4907, ## __VA_ARGS__),	\
+	MACRO__(0x4908, ## __VA_ARGS__),	\
+	MACRO__(0x4909, ## __VA_ARGS__)
+
+/* ADL-S */
+#define XE_ADLS_IDS(MACRO__, ...)		\
+	MACRO__(0x4680, ## __VA_ARGS__),	\
+	MACRO__(0x4682, ## __VA_ARGS__),	\
+	MACRO__(0x4688, ## __VA_ARGS__),	\
+	MACRO__(0x468A, ## __VA_ARGS__),	\
+	MACRO__(0x468B, ## __VA_ARGS__),	\
+	MACRO__(0x4690, ## __VA_ARGS__),	\
+	MACRO__(0x4692, ## __VA_ARGS__),	\
+	MACRO__(0x4693, ## __VA_ARGS__)
+
+/* ADL-P */
+#define XE_ADLP_IDS(MACRO__, ...)		\
+	MACRO__(0x46A0, ## __VA_ARGS__),	\
+	MACRO__(0x46A1, ## __VA_ARGS__),	\
+	MACRO__(0x46A2, ## __VA_ARGS__),	\
+	MACRO__(0x46A3, ## __VA_ARGS__),	\
+	MACRO__(0x46A6, ## __VA_ARGS__),	\
+	MACRO__(0x46A8, ## __VA_ARGS__),	\
+	MACRO__(0x46AA, ## __VA_ARGS__),	\
+	MACRO__(0x462A, ## __VA_ARGS__),	\
+	MACRO__(0x4626, ## __VA_ARGS__),	\
+	MACRO__(0x4628, ## __VA_ARGS__),	\
+	MACRO__(0x46B0, ## __VA_ARGS__),	\
+	MACRO__(0x46B1, ## __VA_ARGS__),	\
+	MACRO__(0x46B2, ## __VA_ARGS__),	\
+	MACRO__(0x46B3, ## __VA_ARGS__),	\
+	MACRO__(0x46C0, ## __VA_ARGS__),	\
+	MACRO__(0x46C1, ## __VA_ARGS__),	\
+	MACRO__(0x46C2, ## __VA_ARGS__),	\
+	MACRO__(0x46C3, ## __VA_ARGS__)
+
+/* ADL-N */
+#define XE_ADLN_IDS(MACRO__, ...)		\
+	MACRO__(0x46D0, ## __VA_ARGS__),	\
+	MACRO__(0x46D1, ## __VA_ARGS__),	\
+	MACRO__(0x46D2, ## __VA_ARGS__)
+
+/* RPL-S */
+#define XE_RPLS_IDS(MACRO__, ...)		\
+	MACRO__(0xA780, ## __VA_ARGS__),	\
+	MACRO__(0xA781, ## __VA_ARGS__),	\
+	MACRO__(0xA782, ## __VA_ARGS__),	\
+	MACRO__(0xA783, ## __VA_ARGS__),	\
+	MACRO__(0xA788, ## __VA_ARGS__),	\
+	MACRO__(0xA789, ## __VA_ARGS__),	\
+	MACRO__(0xA78A, ## __VA_ARGS__),	\
+	MACRO__(0xA78B, ## __VA_ARGS__)
+
+/* RPL-U */
+#define XE_RPLU_IDS(MACRO__, ...)		\
+	MACRO__(0xA721, ## __VA_ARGS__),	\
+	MACRO__(0xA7A1, ## __VA_ARGS__),	\
+	MACRO__(0xA7A9, ## __VA_ARGS__),	\
+	MACRO__(0xA7AC, ## __VA_ARGS__),	\
+	MACRO__(0xA7AD, ## __VA_ARGS__)
+
+/* RPL-P */
+#define XE_RPLP_IDS(MACRO__, ...)		\
+	XE_RPLU_IDS(MACRO__, ## __VA_ARGS__),	\
+	MACRO__(0xA720, ## __VA_ARGS__),	\
+	MACRO__(0xA7A0, ## __VA_ARGS__),	\
+	MACRO__(0xA7A8, ## __VA_ARGS__),	\
+	MACRO__(0xA7AA, ## __VA_ARGS__),	\
+	MACRO__(0xA7AB, ## __VA_ARGS__)
+
+/* DG2 */
+#define XE_DG2_G10_IDS(MACRO__, ...)		\
+	MACRO__(0x5690, ## __VA_ARGS__),	\
+	MACRO__(0x5691, ## __VA_ARGS__),	\
+	MACRO__(0x5692, ## __VA_ARGS__),	\
+	MACRO__(0x56A0, ## __VA_ARGS__),	\
+	MACRO__(0x56A1, ## __VA_ARGS__),	\
+	MACRO__(0x56A2, ## __VA_ARGS__),	\
+	MACRO__(0x56BE, ## __VA_ARGS__),	\
+	MACRO__(0x56BF, ## __VA_ARGS__)
+
+#define XE_DG2_G11_IDS(MACRO__, ...)		\
+	MACRO__(0x5693, ## __VA_ARGS__),	\
+	MACRO__(0x5694, ## __VA_ARGS__),	\
+	MACRO__(0x5695, ## __VA_ARGS__),	\
+	MACRO__(0x56A5, ## __VA_ARGS__),	\
+	MACRO__(0x56A6, ## __VA_ARGS__),	\
+	MACRO__(0x56B0, ## __VA_ARGS__),	\
+	MACRO__(0x56B1, ## __VA_ARGS__),	\
+	MACRO__(0x56BA, ## __VA_ARGS__),	\
+	MACRO__(0x56BB, ## __VA_ARGS__),	\
+	MACRO__(0x56BC, ## __VA_ARGS__),	\
+	MACRO__(0x56BD, ## __VA_ARGS__)
+
+#define XE_DG2_G12_IDS(MACRO__, ...)		\
+	MACRO__(0x5696, ## __VA_ARGS__),	\
+	MACRO__(0x5697, ## __VA_ARGS__),	\
+	MACRO__(0x56A3, ## __VA_ARGS__),	\
+	MACRO__(0x56A4, ## __VA_ARGS__),	\
+	MACRO__(0x56B2, ## __VA_ARGS__),	\
+	MACRO__(0x56B3, ## __VA_ARGS__)
+
+#define XE_DG2_IDS(MACRO__, ...)		\
+	XE_DG2_G10_IDS(MACRO__, ## __VA_ARGS__),\
+	XE_DG2_G11_IDS(MACRO__, ## __VA_ARGS__),\
+	XE_DG2_G12_IDS(MACRO__, ## __VA_ARGS__)
+
+#define XE_ATS_M150_IDS(MACRO__, ...)		\
+	MACRO__(0x56C0, ## __VA_ARGS__),	\
+	MACRO__(0x56C2, ## __VA_ARGS__)
+
+#define XE_ATS_M75_IDS(MACRO__, ...)		\
+	MACRO__(0x56C1, ## __VA_ARGS__)
+
+#define XE_ATS_M_IDS(MACRO__, ...)		\
+	XE_ATS_M150_IDS(MACRO__, ## __VA_ARGS__),\
+	XE_ATS_M75_IDS(MACRO__, ## __VA_ARGS__)
+
+/* MTL / ARL */
+#define XE_MTL_IDS(MACRO__, ...)		\
+	MACRO__(0x7D40, ## __VA_ARGS__),	\
+	MACRO__(0x7D41, ## __VA_ARGS__),	\
+	MACRO__(0x7D45, ## __VA_ARGS__),	\
+	MACRO__(0x7D51, ## __VA_ARGS__),        \
+	MACRO__(0x7D55, ## __VA_ARGS__),	\
+	MACRO__(0x7D60, ## __VA_ARGS__),	\
+	MACRO__(0x7D67, ## __VA_ARGS__),	\
+	MACRO__(0x7DD1, ## __VA_ARGS__),        \
+	MACRO__(0x7DD5, ## __VA_ARGS__)
+
+/* PVC */
+#define XE_PVC_IDS(MACRO__, ...)		\
+	MACRO__(0x0B69, ## __VA_ARGS__),	\
+	MACRO__(0x0B6E, ## __VA_ARGS__),	\
+	MACRO__(0x0BD4, ## __VA_ARGS__),	\
+	MACRO__(0x0BD5, ## __VA_ARGS__),	\
+	MACRO__(0x0BD6, ## __VA_ARGS__),	\
+	MACRO__(0x0BD7, ## __VA_ARGS__),	\
+	MACRO__(0x0BD8, ## __VA_ARGS__),	\
+	MACRO__(0x0BD9, ## __VA_ARGS__),	\
+	MACRO__(0x0BDA, ## __VA_ARGS__),	\
+	MACRO__(0x0BDB, ## __VA_ARGS__),	\
+	MACRO__(0x0BE0, ## __VA_ARGS__),	\
+	MACRO__(0x0BE1, ## __VA_ARGS__),	\
+	MACRO__(0x0BE5, ## __VA_ARGS__)
+
+#define XE_LNL_IDS(MACRO__, ...) \
+	MACRO__(0x6420, ## __VA_ARGS__), \
+	MACRO__(0x64A0, ## __VA_ARGS__), \
+	MACRO__(0x64B0, ## __VA_ARGS__)
+
+#define XE_BMG_IDS(MACRO__, ...) \
+	MACRO__(0xE202, ## __VA_ARGS__), \
+	MACRO__(0xE20B, ## __VA_ARGS__), \
+	MACRO__(0xE20C, ## __VA_ARGS__), \
+	MACRO__(0xE20D, ## __VA_ARGS__), \
+	MACRO__(0xE212, ## __VA_ARGS__)
+
+#endif

+ 12 - 0
libs/external/chat-vault/monitoring/grafana/monitor-tui/src/main.cpp

@@ -0,0 +1,12 @@
+// SPDX-License-Identifier: Apache-2.0
+
+#include "btop.hpp"
+
+#include <iterator>
+#include <ranges>
+#include <string_view>
+#include <vector>
+
+auto main(int argc, const char* argv[]) -> int {
+	return btop_main(std::views::counted(std::next(argv), argc - 1) | std::ranges::to<std::vector<std::string_view>>());
+}

Деякі файли не було показано, через те що забагато файлів було змінено