Compare commits

..

136 Commits

Author SHA1 Message Date
Carter Li de18a07938 Release: v2.52.0 2025-09-05 13:04:53 +08:00
李通洲 88147f80ac Doc: update changelog 2025-09-05 12:38:14 +08:00
李通洲 505ff6ff65 Global: renames fractionTrailingZeros enum to always/never for consistance 2025-09-05 12:27:03 +08:00
李通洲 390549394d Fastfetch: removes redundant assignment in display config parsing
found by copilot
2025-09-05 11:08:37 +08:00
Carter Li f7e7d54c16 Release: v2.52.0 2025-09-05 10:46:30 +08:00
Carter Li 5e068d22c8 Btrfs (Linux): refactors Btrfs allocation to use profile string
Fixes #1941
2025-09-05 10:46:23 +08:00
李通洲 b77646f23e Btrfs (Linux): adds tracking of Btrfs data copy counts
Fixes(?) #1941
2025-09-05 00:18:00 +08:00
李通洲 aa40366a49 Terminal: ignores WSL2 unknown process for terminal detection 2025-09-04 22:31:59 +08:00
Carter Li a64a82f215 WMTheme (Linux): supports labwc on XFCE4 2025-09-04 18:50:23 +08:00
Qing Yun 0a4d6220e9 CPU (Linux): add cpu name detection for ia64 2025-09-04 18:34:14 +08:00
李通洲 6b037c595f Doc: update README 2025-09-04 16:36:55 +08:00
李通洲 f628f5c382 Settings: renames GNOME settings accessor for clarity 2025-09-04 16:17:01 +08:00
李通洲 cf713e32e1 Wallpaper (Linux): improves XFCE wallpaper detection via property enumeration 2025-09-04 13:54:49 +08:00
Carter Li 7d08f81075 Settings: removes direct XFConf support in favor of DBus backend 2025-09-04 09:43:57 +08:00
Carter Li 8822653335 DBus: adds function ffDBusGetInt 2025-09-04 09:35:52 +08:00
李通洲 75ff054255 Dbus: adds 2nd argument to ffDBusGetMethodReply 2025-09-04 08:45:09 +08:00
李通洲 c51cc8ce6b CI: bump dependencies 2025-09-03 16:01:09 +08:00
李通洲 44e23412b5 Doc: update changelog 2025-09-03 16:01:09 +08:00
李通洲 59742bca00 Fastfetch: improves frequency display config validation and schema 2025-09-03 16:01:09 +08:00
李通洲 303edb97ce Fastfetch: add option --faction-trailing-zeros 2025-09-03 14:20:23 +08:00
李通洲 37ab380a6f Logo (Chafa): fixes setting logo.width with chafa
Regression in v2.51.0

Fixes #1947
2025-09-03 10:49:58 +08:00
Carter Li a06e245c34 JsonSchema: update 2025-09-03 09:58:50 +08:00
Carter Li 5de432b083 Fastfetch: defaults display.fraction.ndigits to 2 2025-09-03 09:58:40 +08:00
Carter Li 817285ac01 Fastfetch: informs users that module-specific CLI options are no longer supported
... and provides guidance on transitioning to JSON config
2025-09-03 09:36:16 +08:00
李通洲 8687505505 LocalIP (Linux): skips interfaces without IPs unless MAC display is enabled 2025-09-02 15:00:35 +08:00
李通洲 34c34d25c4 JsonConfig: fixes fractionNdigits will be incorrectly set to 0 when specifying null 2025-09-02 14:44:15 +08:00
李通洲 21b15ee944 Display: rearranges default format; removes scaled resolution 2025-09-02 14:15:37 +08:00
李通洲 8e0a65126e LocalIP: honors fractionTrailingZeros 2025-09-02 14:13:37 +08:00
李通洲 54d8b0a95d Global: adds configurable trailing zeros for double formatting 2025-09-02 14:12:58 +08:00
李通洲 48fc72e95c DisplayServer: improves display size rounding and argument clarity 2025-09-02 09:36:19 +08:00
Carter Li e3d6a85888 Display (Linux): detect scale factor for X11 2025-09-01 21:20:34 +08:00
李通洲 7d92da8829 Global (Android): enable X11 related stuff 2025-09-01 16:28:13 +08:00
李通洲 2f3a361b1f CMake: enable zlib on all platforms 2025-09-01 09:59:06 +08:00
李通洲 ac71f21e6c DisplayServer (Android): update WM name accurately
See #1933
2025-08-30 14:14:48 +08:00
李通洲 8d5316f6aa CMake (Android): link to libm
Fix #1939
2025-08-30 13:31:37 +08:00
Carter Li 1242fda66f Merge pull request #1938 from fastfetch-cli/dev
Release: v2.51.1
2025-08-29 14:05:34 +08:00
李通洲 5a2b618d27 Release: v2.51.1 2025-08-29 13:55:52 +08:00
李通洲 d836d7569f CPU (macOS): removes reliance on unavailable ARM capability headers on macOS
Fixes https://github.com/Homebrew/homebrew-core/pull/235425
2025-08-29 13:45:16 +08:00
Carter Li 8a412e6823 Packaging: update debian stuff [ci skip] 2025-08-29 08:56:30 +08:00
Carter Li 16b6aac764 Merge pull request #1933 from fastfetch-cli/dev
Release: v2.51.0
2025-08-29 08:43:08 +08:00
Carter Li 9f5046d69f CPU/GPU (Linux): Improves CPU/GPU temp detection accuracy on Linux/Android 2025-08-28 18:58:00 +08:00
李通洲 cace1a7156 Revert "Uptime (Windows): use QueryUnbiasedInterruptTime"
Fixes #1935

This reverts commit b812f3ccde.
2025-08-28 18:22:06 +08:00
李通洲 9c0cf863ba JsonSchema: update 2025-08-28 16:36:00 +08:00
Carter Li ffe55d9eee DisplayServer (Linux): upgrade kde-output-device-v2 2025-08-28 16:09:47 +08:00
李通洲 28bc9523d6 Release: v2.51.0 2025-08-28 14:40:31 +08:00
李通洲 ebf810ad4b GPU (Android): adds GPU temp detection support 2025-08-28 14:29:00 +08:00
Carter Li 5c9a0a1f88 Fastfetch: clarify that --debug is debug-mode only 2025-08-28 09:32:01 +08:00
李通洲 bc05a30724 CPU (Linux): improve temp detection
Support Android
2025-08-28 09:29:33 +08:00
李通洲 98c7803a24 Battery (Android): fix battery temp detection 2025-08-27 16:28:54 +08:00
李通洲 0893013e78 DisplayServer (Android): fix display server name 2025-08-27 15:43:50 +08:00
李通洲 e6985a8832 Global: handles missing config directories more gracefully 2025-08-27 15:29:38 +08:00
Carter Li 7a87638fec InitSystem (GNU): support shepherd detection 2025-08-27 14:46:20 +08:00
李通洲 00f163be32 CPU (Windows): detects march on WoA
Tested in VM
2025-08-27 09:22:02 +08:00
李通洲 68bbb2980e CPU (macOS): detects march on Apple Silicon 2025-08-27 09:22:02 +08:00
Carter Li dd1a799abb CPU (Linux): detects march on aarch64 2025-08-27 09:22:02 +08:00
Carter Li 7611d672b7 Merge pull request #1931 from CarterLi/dev
Add GNU/Hurd support
2025-08-25 13:41:53 +08:00
carter bfb93cd8f5 Processing (Linux): enhances robustness when extracting process name and related fields
... by accurately handling process names with spaces or special characters.
2025-08-25 10:39:56 +08:00
李通洲 0998b1e59e DiskIO (Linux): trim trailing white spaces 2025-08-25 09:26:04 +08:00
李通洲 588c4c0026 Chore: silense compiler warnings 2025-08-25 09:25:25 +08:00
Carter Li a80ea2b117 CPUUsage: adds user guidance when CPU time fails to increase 2025-08-24 22:23:07 +08:00
Carter Li 13110e3074 LocalIP (GNU): adds MAC addr detection support 2025-08-24 22:15:06 +08:00
Carter Li 0b2c0445c0 InitSystem: tidy 2025-08-24 22:09:22 +08:00
Carter Li 062963d6cc CMake (GNU): disable wifi support 2025-08-24 22:04:58 +08:00
Carter Li 4b7f231b5a Processing (GNU): fix command name reading 2025-08-24 21:52:38 +08:00
Carter Li 74e0732390 Common (GNU): more __GNU__ tests 2025-08-24 21:40:22 +08:00
Carter Li e9104c38c6 Terminal (GNU): enable version detection 2025-08-24 13:04:12 +01:00
Carter Li 4a7b3a8493 Processing (GNU): hurd uses cmdline instead of comm 2025-08-24 19:57:54 +08:00
Carter Li 20fafa5a21 WM (GNU): enable 2025-08-24 19:56:52 +08:00
Carter Li 1d32344cf7 Global (GNU): code cleanups 2025-08-24 19:37:06 +08:00
Carter Li 82a1eaf276 Chore: tidy tabs 2025-08-24 19:09:51 +08:00
Carter Li 75a023f4d7 CMake (GNU): enable a lot of things 2025-08-24 12:05:14 +01:00
Yelninei 53424300e3 localip: Remove AF_LINK on GNU.
https://salsa.debian.org/glibc-team/glibc/-/blob/sid/debian/patches/hurd-i386/submitted-AF_LINK.diff
2025-08-24 11:29:02 +01:00
Yelninei d553bc4893 WIP: shepherd initsystem 2025-08-24 11:29:01 +01:00
Yelninei add2bfd108 Fix localip_linux on GNU 2025-08-24 11:29:01 +01:00
Yelninei e508100a15 disable ffPackagesGetNix on when it is not defined 2025-08-24 11:29:01 +01:00
Yelninei 1a2f4b4c1f Port netif_gnu to the new api. 2025-08-24 11:29:01 +01:00
Yelninei e968bca89d Fork netif_linux to netif_gnu.
netif_linux now uses linux specifics which do not work on GNU.
2025-08-24 11:29:01 +01:00
Yelninei 71fbe04367 Start work on GNU 2025-08-24 11:29:01 +01:00
李通洲 f2f9b10b18 TerminalShell: remove special handling of hyfetch
Ref: https://github.com/search?q=repo%3Ahykilpikonna%2Fhyfetch%20FFTS_IGNORE_PARENT&type=code
2025-08-24 00:00:10 +08:00
李通洲 fae4892643 Fastfetch: improves config file generation message with tips 2025-08-23 20:37:29 +08:00
李通洲 8589bf2392 Chore: silence compiler warnings 2025-08-23 15:31:42 +08:00
李通洲 8b18e69980 CPU: fix building on non-x86 2025-08-23 15:28:48 +08:00
李通洲 9ae968fbd3 CPU: adds CPU microarchitecture detection for x64 and reporting
Fixes #1928
2025-08-23 15:17:57 +08:00
李通洲 8f6608db74 Disk: adds formatted free and available disk size fields
Fixes #1929
2025-08-23 13:59:48 +08:00
李通洲 45b6a333ec Logo (Builtin): adds AerynOS
Fixes #1926
2025-08-22 14:23:52 +08:00
李通洲 5012bc250b Processes (Linux): be compatible with Hurd 2025-08-22 14:08:18 +08:00
李通洲 5775409cb9 DisplayServer (Android): update WM name 2025-08-22 14:07:58 +08:00
李通洲 64da80d520 Fastfetch: improves format help output for config and variables
Fixes #1927
2025-08-21 23:57:37 +08:00
Carter Li 8b1bfcb34b WM (Linux): uses the same X11 props as neofetch to query WM name
Fixes twin detection
2025-08-21 18:35:09 +08:00
Carter Li 784a7a92c8 DE (Linux): adds Trinity version detection support 2025-08-21 18:19:23 +08:00
李通洲 8331242f42 GPU (BSD): fallbacks to pciids/pci.ids 2025-08-21 10:54:34 +08:00
李通洲 79fea61c90 Merge remote-tracking branch 'origin' into dev 2025-08-21 10:41:04 +08:00
Carter Li a8e7d38afd Packaging: update debian stuff [ci skip] 2025-08-21 10:39:59 +08:00
Carter Li 24467e8c46 GPU (BSD): always use pci.ids provided by hwdata
Fixes #1924
2025-08-21 09:23:01 +08:00
李通洲 6867b87c3e Disk: disable hyperlink by default and move it to custom keys 2025-08-21 08:53:51 +08:00
Carter Li cb13d43a7a TerminalShell (Linux): always ignore pid1 (v2) 2025-08-21 00:19:52 +08:00
Carter Li bd7190ca6d TerminalShell (Linux): always ignore pid1 2025-08-21 00:12:41 +08:00
Carter Li 49982588cf Disk (Linux): remove unused headers 2025-08-20 23:52:53 +08:00
Carter Li de2dff5da0 Common: corrects the position for appending milliseconds 2025-08-20 11:07:53 +08:00
Carter Li b05c54486f LocalIP (Linux): improves netlink route parsing by avoiding possible message truncation
Fixes #1919
2025-08-20 11:07:06 +08:00
Carter Li 1f1d7cf936 FFstrbuf: handles double rounding and zero representation in formatter 2025-08-20 10:10:30 +08:00
李通洲 26253f8863 GPU (Windows): improves GPU detection by refining device filtering 2025-08-19 19:03:55 +08:00
李通洲 08e6db090b Shell (Windows): be compatible with fish 4 built by MSYS2 2025-08-19 17:25:04 +08:00
李通洲 ec0fa89cc8 Common: refactors number formatting to use type-specific append functions 2025-08-19 17:22:11 +08:00
李通洲 7f48500cfd Format: replaces format specifiers with type-safe append functions 2025-08-19 16:04:00 +08:00
李通洲 a7eecf6fc7 FFstrbuf: improves double formatting precision handling 2025-08-19 16:03:04 +08:00
李通洲 8e282a3865 Duration: use ffStrbufAppendUInt 2025-08-19 15:19:12 +08:00
李通洲 dcbf76b233 FFstrbuf: adds number appending functions 2025-08-19 15:00:30 +08:00
李通洲 70b11d953c Logo (Builtin): honor logo.width 2025-08-19 10:35:11 +08:00
李通洲 fa3b634c07 JsonConfig: support JSON5 2025-08-19 10:25:52 +08:00
李通洲 ea86273a0e Common: refactors time formatting to use a shared buffer and utility macro 2025-08-19 09:49:43 +08:00
李通洲 4f88e1f26d 3rdparty: upgrade yyjson to 0.12.0 2025-08-19 08:43:38 +08:00
李通洲 805e277429 JsonConfig: adds 'succeeded' module condition to JSON config
Fixes #1908
2025-08-18 14:18:37 +08:00
李通洲 3ce3de2963 OS: set the icon of unknown OS type as a cog 2025-08-18 14:03:52 +08:00
李通洲 3b5e9c74d6 Modules: return bool to indicate whether the detection is succeeded 2025-08-18 13:38:30 +08:00
李通洲 a9aaa36b2c CI (DFBSD): enable 2025-08-17 23:08:43 +08:00
李通洲 bef4ee1fbc CI (SunOS): fix build 2025-08-17 23:03:45 +08:00
李通洲 b3ddd084ba Merge remote-tracking branch 'upstream/master' into dev 2025-08-17 23:03:17 +08:00
Mathias Korsbäck fef3b7c647 CPU (macOS): changes CPU to M2 Pro for Mac14,12 host (#1915)
Currently states it's a M2 but according to https://support.apple.com/en-us/102852 and https://everymac.com/ultimate-mac-lookup/?search_keywords=Mac14%2C12 it's a M2 Pro.
2025-08-17 21:37:17 +08:00
Carter Li 4dfba31cae Merge pull request #1911 from fastfetch-cli/dev
Release: v2.50.2
2025-08-16 21:50:39 +08:00
Carter Li 3004f29c08 Release: v2.50.2 2025-08-16 21:18:07 +08:00
李通洲 b994ce5b55 LocalIP: refines default route detection and JSON output for local IPs
Add verbose log for Windows
2025-08-16 18:27:30 +08:00
李通洲 6356f9d0e5 Netif (Linux): improves default route detection and error handling
Ref: #1902
2025-08-16 17:15:44 +08:00
李通洲 597c6f3dbc Netif (Linux): add verbose logs 2025-08-16 15:13:07 +08:00
李通洲 41cffac80c CI: adds default build type to CI environment 2025-08-16 13:10:35 +08:00
李通洲 c4cb6c65a9 LocalIP (Linux): add verbose debug log 2025-08-16 04:43:28 +00:00
李通洲 46081a3e52 LocalIP (Linux): fixes incorrect return and ensures struct initialization 2025-08-16 04:24:26 +00:00
李通洲 a5fd671b92 LocalIP: fix showMac does not honor defaultRouteOnly 2025-08-15 20:20:43 +08:00
李通洲 8319512c83 Merge remote-tracking branch 'origin' into dev 2025-08-15 08:58:15 +08:00
Ashish SHUKLA c1db692982 FFstrbuf: wrap yyjson.h include in conditional 2025-08-15 08:49:53 +08:00
Guiling Qiyu aec2bfd2a4 Packages (Linux): fixes Linglong detection by counting linglong layers (#1903)
* Packages (Linux): fixes Linglong detection on Deepin

* Packages (Linux): fixes Linglong detection to count layers

* Update src/detection/packages/packages_linux.c

---------

Co-authored-by: Carter Li <CarterLi@users.noreply.github.com>
2025-08-14 19:47:20 -05:00
Carter Li 7bacf20f72 Merge pull request #1901 from fastfetch-cli/dev
Release: v2.50.1
2025-08-14 22:35:06 +08:00
Carter Li 1479de19ef Release: v2.50.1 2025-08-14 18:34:30 +08:00
Guiling Qiyu bb9ca73db1 Packages (Linux): fixes Linglong detection on Debian (#1899)
Fixes #1898
2025-08-14 18:06:42 +08:00
李通洲 81bac8bca4 Percent: refactors bar color logic for clarity and consistency; update examples 2025-08-14 16:47:30 +08:00
李通洲 56d22292b0 Revert "Percent: fix a copy-paste error"
This reverts commit 3345c1e9dd.
2025-08-14 16:04:55 +08:00
263 changed files with 8729 additions and 5830 deletions
+18 -15
View File
@@ -4,6 +4,9 @@ on:
- push
- pull_request
env:
CMAKE_BUILD_TYPE: ${{ vars.CMAKE_BUILD_TYPE || 'RelWithDebInfo' }}
jobs:
spellcheck:
runs-on: ubuntu-latest
@@ -35,7 +38,7 @@ jobs:
run: uname -a
- name: configure project
run: cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DCMAKE_INSTALL_PREFIX=/usr . -DENABLE_VULKAN=OFF -DENABLE_WAYLAND=OFF -DENABLE_XCB_RANDR=OFF -DENABLE_XCB=OFF -DENABLE_XRANDR=OFF -DENABLE_X11=OFF -DENABLE_DRM=OFF -DENABLE_DRM_AMDGPU=OFF -DENABLE_GIO=OFF -DENABLE_DCONF=OFF -DENABLE_DBUS=OFF -DENABLE_XFCONF=OFF -DENABLE_SQLITE3=OFF -DENABLE_RPM=OFF -DENABLE_IMAGEMAGICK7=OFF -DENABLE_IMAGEMAGICK6=OFF -DENABLE_CHAFA=OFF -DENABLE_ZLIB=OFF -DENABLE_EGL=OFF -DENABLE_GLX=OFF -DENABLE_OPENCL=OFF -DENABLE_FREETYPE=OFF -DENABLE_PULSE=OFF -DENABLE_DDCUTIL=OFF -DENABLE_ELF=OFF -DENABLE_DIRECTX_HEADERS=OFF -DENABLE_THREADS=OFF
run: cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DCMAKE_INSTALL_PREFIX=/usr . -DENABLE_VULKAN=OFF -DENABLE_WAYLAND=OFF -DENABLE_XCB_RANDR=OFF -DENABLE_XCB=OFF -DENABLE_XRANDR=OFF -DENABLE_X11=OFF -DENABLE_DRM=OFF -DENABLE_DRM_AMDGPU=OFF -DENABLE_GIO=OFF -DENABLE_DCONF=OFF -DENABLE_DBUS=OFF -DENABLE_SQLITE3=OFF -DENABLE_RPM=OFF -DENABLE_IMAGEMAGICK7=OFF -DENABLE_IMAGEMAGICK6=OFF -DENABLE_CHAFA=OFF -DENABLE_ZLIB=OFF -DENABLE_EGL=OFF -DENABLE_GLX=OFF -DENABLE_OPENCL=OFF -DENABLE_FREETYPE=OFF -DENABLE_PULSE=OFF -DENABLE_DDCUTIL=OFF -DENABLE_ELF=OFF -DENABLE_DIRECTX_HEADERS=OFF -DENABLE_THREADS=OFF
- name: build project
run: cmake --build . --target package --verbose -j4
@@ -80,7 +83,7 @@ jobs:
run: cat /proc/cpuinfo
- name: install required packages
run: sudo apt-get update && sudo apt-get install -y libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libxfconf-0-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libelf-dev libddcutil-dev directx-headers-dev
run: sudo apt-get update && sudo apt-get install -y libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libelf-dev libddcutil-dev directx-headers-dev
- name: install linuxbrew packages
run: |
@@ -149,7 +152,7 @@ jobs:
run: cat /proc/cpuinfo
- name: install required packages
run: sudo apt-get update && sudo apt-get install -y libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libxfconf-0-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libelf-dev directx-headers-dev libchafa-dev libddcutil-dev rpm
run: sudo apt-get update && sudo apt-get install -y libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libelf-dev directx-headers-dev libchafa-dev libddcutil-dev rpm
- name: install linuxbrew packages
run: |
@@ -213,7 +216,7 @@ jobs:
# CMake installed by apt has bug `list sub-command REMOVE_ITEM requires two or more arguments`
wget --no-check-certificate https://apt.kitware.com/ubuntu/pool/main/c/cmake/{cmake_3.29.2-0kitware1ubuntu20.04.1_armhf.deb,cmake-data_3.29.2-0kitware1ubuntu20.04.1_all.deb}
dpkg -i *.deb
apt-get install -y make g++ libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libxfconf-0-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libelf-dev directx-headers-dev rpm
apt-get install -y make g++ libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libelf-dev directx-headers-dev rpm
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DCMAKE_INSTALL_PREFIX=/usr .
cmake --build . --target package --verbose -j4
./fastfetch --list-features
@@ -249,7 +252,7 @@ jobs:
run: |
uname -a
apt-get update && apt-get install -y wget
apt-get install -y cmake make g++ libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libxfconf-0-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libelf-dev directx-headers-dev rpm
apt-get install -y cmake make g++ libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libelf-dev directx-headers-dev rpm
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DCMAKE_INSTALL_PREFIX=/usr .
cmake --build . --target package --verbose -j4
./fastfetch --list-features
@@ -284,7 +287,7 @@ jobs:
githubToken: ${{ github.token }}
run: |
uname -a
apt-get update && apt-get install -y cmake make g++ libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libxfconf-0-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libddcutil-dev libchafa-dev libelf-dev directx-headers-dev rpm
apt-get update && apt-get install -y cmake make g++ libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libddcutil-dev libchafa-dev libelf-dev directx-headers-dev rpm
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DCMAKE_INSTALL_PREFIX=/usr .
cmake --build . --target package --verbose -j4
./fastfetch --list-features
@@ -319,7 +322,7 @@ jobs:
githubToken: ${{ github.token }}
run: |
uname -a
apt-get update && apt-get install -y cmake make g++ libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libxfconf-0-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libchafa-dev libelf-dev directx-headers-dev rpm
apt-get update && apt-get install -y cmake make g++ libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libchafa-dev libelf-dev directx-headers-dev rpm
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DCMAKE_INSTALL_PREFIX=/usr .
cmake --build . --target package --verbose -j4
./fastfetch --list-features
@@ -354,7 +357,7 @@ jobs:
githubToken: ${{ github.token }}
run: |
uname -a
apt-get update && apt-get install -y cmake make g++ libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libxfconf-0-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libchafa-dev libelf-dev directx-headers-dev rpm
apt-get update && apt-get install -y cmake make g++ libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libchafa-dev libelf-dev directx-headers-dev rpm
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DCMAKE_INSTALL_PREFIX=/usr .
cmake --build . --target package --verbose -j4
./fastfetch --list-features
@@ -383,7 +386,7 @@ jobs:
run: |
cat /etc/alpine-release
uname -a
apk add cmake samurai vulkan-loader-dev libxcb-dev libxrandr-dev rpm-dev wayland-dev libdrm-dev dconf-dev imagemagick-dev chafa-dev zlib-dev dbus-dev mesa-dev opencl-dev xfconf-dev sqlite-dev networkmanager-dev pulseaudio-dev ddcutil-dev elfutils-dev gcc g++
apk add cmake samurai vulkan-loader-dev libxcb-dev libxrandr-dev rpm-dev wayland-dev libdrm-dev dconf-dev imagemagick-dev chafa-dev zlib-dev dbus-dev mesa-dev opencl-dev sqlite-dev networkmanager-dev pulseaudio-dev ddcutil-dev elfutils-dev gcc g++
shell: alpine.sh --root {0}
- name: build
@@ -515,8 +518,9 @@ jobs:
usesh: true
prepare: |
uname -a
pkg install pkg:/package/pkg
pkg update --accept
pkg install gcc13 cmake git pkg-config glib2 dbus sqlite-3 imagemagick
pkg install gcc14 cmake git pkg-config glib2 dbus sqlite-3 imagemagick
run: |
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On .
@@ -556,7 +560,7 @@ jobs:
run: |
uname -a
sudo pkg update
sudo pkg install -y cmake git pkgconf binutils wayland vulkan-headers vulkan-loader libxcb libXrandr libX11 libdrm glib dconf dbus sqlite3-tcl xfce4-conf egl opencl ocl-icd v4l_compat chafa
sudo pkg install -y cmake git pkgconf binutils wayland vulkan-headers vulkan-loader libxcb libXrandr libX11 libdrm glib dconf dbus sqlite3-tcl egl opencl ocl-icd v4l_compat chafa
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DENABLE_EMBEDDED_PCIIDS=On -DENABLE_EMBEDDED_AMDGPUIDS=On .
cmake --build . --target package --verbose -j4
./fastfetch --list-features
@@ -592,7 +596,7 @@ jobs:
version: '7.7'
run: |
uname -a
sudo pkg_add -r cmake git pkgconf wayland vulkan-headers vulkan-loader glib2 dconf dbus sqlite3 xfconf imagemagick chafa
sudo pkg_add -r cmake git pkgconf wayland vulkan-headers vulkan-loader glib2 dconf dbus sqlite3 imagemagick chafa
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DENABLE_EMBEDDED_PCIIDS=On -DENABLE_EMBEDDED_AMDGPUIDS=On .
cmake --build . --target package --verbose -j4
./fastfetch --list-features
@@ -647,7 +651,6 @@ jobs:
dragonfly-amd64:
name: DragonFly-amd64
runs-on: ubuntu-latest
if: false
permissions:
security-events: write
contents: read
@@ -662,7 +665,7 @@ jobs:
prepare: |
uname -a
pkg update
pkg install -y cmake git pkgconf binutils wayland vulkan-headers vulkan-loader libxcb libXrandr libX11 libdrm glib dconf dbus sqlite3-tcl xfce4-conf egl opencl ocl-icd v4l_compat chafa libelf
pkg install -y cmake git pkgconf binutils wayland vulkan-headers vulkan-loader libxcb libXrandr libX11 libdrm glib dconf dbus sqlite3-tcl egl opencl ocl-icd v4l_compat chafa libelf
run: |
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DENABLE_EMBEDDED_PCIIDS=On -DENABLE_EMBEDDED_AMDGPUIDS=On .
@@ -872,7 +875,7 @@ jobs:
- name: download artifacts
if: needs.linux-amd64.outputs.ffversion != steps.get_version_release.outputs.release
uses: actions/download-artifact@v4
uses: actions/download-artifact@v5
- name: create release
if: needs.linux-amd64.outputs.ffversion != steps.get_version_release.outputs.release
+108
View File
@@ -1,3 +1,111 @@
# 2.52.0
Changes:
* New optional build dependencies on Android
* main: chafa dbus glib imagemagick libelf libxcb libxrandr pulseaudio zlib
* x11: dconf (Optional)
* Dependency on `libxfconf` is removed. XFCE related detection now uses `libdbus` instead (Linux)
* The default format of `Display` module is updated to `{width}x{height} @ {scale-factor}x in {inch}", {refresh-rate} Hz`
* Replaced scaled resolution with scale factor for shorter texts and avoiding potential confusion.
Bugfixes:
* Fixes linking on 32-bit Android (#1939)
* Skips network interfaces without IPs unless MAC address is requested (#1949, LocalIP)
* Fixes unexpected padding when setting `logo.width` with chafa logos (#1947, Logo)
* Regression from v2.51.0
* Improves Wallpaper detection on XFCE4 (Wallpaper, Linux)
* Ignores process `Relay(xxx)` when detecting terminal on WSL2 (Terminal, Linux)
Features:
* Enables X11-related info (i.e., WM/DE) detection on Android (Global, Android)
* This requires many dependencies. See above.
* Adds scale factors detection for X11 (Display, Linux)
* X11 doesn't natively report scale factor as Wayland does. Instead, Fastfetch tries to detect `Xft.dpi` (DPI used by X FreeType for scaling fonts), which is usually set by the WM when DPI scaling is enabled.
* It's not always accurate. For example, XFCE4 has a separate config for text scaling, which is unaffected by the global DPI scaling setting.
* Adds `display.fraction.trailingZeros: [always|never]` option for fraction formatting
* The default value of `display.fraction.ndigits` is changed from `-1` (unlimited) to `2` for usability.
* Used for displaying scale factor in Display module mentioned above, alongside other places for printing raw fraction numbers.
* Informs users that module-specific CLI options are no longer supported and provide guidance for transitioning to JSON config
* Adds CPU name detection support for IA64 (CPU, Linux)
* Support Btrfs allocation profile detection (#1941, Btrfs, Linux)
# 2.51.1
Bugfixes:
* Fix building on macOS 14 or older; no functional changes (CPU, macOS)
# 2.51.0
Changes:
* Fastfetch now requires [yyjson 0.12](https://github.com/ibireme/yyjson/releases/tag/0.12.0) to build when using `-DENABLE_SYSTEM_YYJSON=ON`.
* The Disk module no longer shows hyperlink mountpoints by default, which cause issues on some real consoles (Disk)
* Instead, the custom key for the Disk module now supports `{mountpoint-link}` and `{name-link}` to show hyperlinks for mountpoints and names. For example, `{ "type": "disk", "key": "Disk ({mountpoint-link})" }` can be used to restore the old behavior.
Features:
* Adds `succeeded` module condition to JSONC config. When set to `false`, the module will only run if the last module failed (#1908)
* Useful for displaying fallback placeholders when a module fails. For example:
```jsonc
{
"host",
// If fastfetch fails to detect host info, display "DIY PC" instead
{
"type": "custom",
"condition": {
"succeeded": false
},
"key": "Host",
"format": "DIY PC"
}
}
```
* By upgrading to yyjson 0.12, fastfetch now adds [JSON5](https://json5.org/) format support for configuration files (#1907)
* [JSON5](https://json5.org/) is a superset of JSONC that allows unquoted keys, single quotes, multi-line strings, etc., and is fully compatible with JSONC and strict JSON.
* To use JSON5, simply name your config file with a `.json5` extension. The `.jsonc` extension is still supported and used as the default extension for better IDE syntax highlighting support.
* Fastfetch has been ported to [`GNU/Hurd`](https://www.gnu.org/software/hurd/) (#1895)
* Thanks to the efforts of @yelninei!
* Built-in logos now honor `logo.width` (#1905)
* When its value is larger than the actual logo width, the logo will be padded with spaces to the right
* Adds Trinity DE version detection (#1917, DE, Linux)
* Adds formatted free and available disk size fields (#1929, Disk)
* `{size-free}`: free size of the disk
* `{size-available}`: available size of the disk
* See [askubuntu.com](https://askubuntu.com/questions/249387/df-h-used-space-avail-free-space-is-less-than-the-total-size-of-home) for the difference between free and available size
* Adds [x86_64 micro-architecture level](https://en.wikipedia.org/wiki/X86-64#Microarchitecture_levels) detection (#1928, CPU)
* Useful when installing software that requires or is optimized for specific CPU features. E.g., [CachyOS](https://wiki.cachyos.org/features/optimized_repos/)
* Exposed via `{march}` in custom format
* Adds [Aarch64 micro-architecture level](https://en.wikipedia.org/wiki/AArch64#Profiles) detection (CPU)
* Supported on Linux (including Android), macOS and Windows
* This is not fully accurate because there are many optional features across different levels, and not all levels are detectable.
* Exposed via `{march}` in custom format.
* Adds shepherd detection support (InitSystem, Linux)
Bugfixes:
* Refines GPU detection logic to correctly handle virtual devices (#1920, GPU, Windows)
* Fixes possible default route detection failure when the route table is very large (#1919, LocalIP, Linux)
* Fastfetch now correctly parses `hwdata/pci.ids` files alongside `pciids/pci.ids` on FreeBSD when detecting GPU names (#1924, GPU, FreeBSD)
* Fixes twin WM detection (#1917, WM, Linux)
* Various fixes for Android support
* Corrects WM name for Android (WM, Android)
* Fixes battery temperature detection when running in ADB (Battery, Android)
* Adds CPU and GPU temperature detection support (CPU, Android)
Logos:
* Adds AerynOS
# 2.50.2
Bugfixes:
* Fixes linglong package detection V2 (#1903, Packages, Linux)
* Fixes building with `-DENABLE_SYSTEM_YYJSON=ON` (#1904)
* Fixes `showMac` does not honor `defaultRouteOnly` (#1902, LocalIP, Linux)
* Fixes failing to acquire default route on Linux in certain cases (#1902, LocalIP, Linux)
# 2.50.1
Bugfixes:
* Fixes percentage bar not displaying correctly in certain cases
* Fixes linglong package detection on Debian 13 (#1899, Packages, Linux)
# 2.50.0
Changes:
+137 -36
View File
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.12.0) # target_link_libraries with OBJECT libs & project homepage url
project(fastfetch
VERSION 2.50.0
VERSION 2.52.0
LANGUAGES C
DESCRIPTION "Fast neofetch-like system information tool"
HOMEPAGE_URL "https://github.com/fastfetch-cli/fastfetch"
@@ -32,6 +32,8 @@ elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "SunOS")
set(SunOS TRUE CACHE BOOL "..." FORCE)
elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Haiku")
set(Haiku TRUE CACHE BOOL "..." FORCE)
elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "GNU")
set(GNU TRUE CACHE BOOL "..." FORCE)
elseif(NOT APPLE AND NOT WIN32)
message(FATAL_ERROR "Unsupported platform: ${CMAKE_SYSTEM_NAME}")
endif()
@@ -56,34 +58,33 @@ include(CheckIncludeFile)
include(CMakeDependentOption)
cmake_dependent_option(ENABLE_VULKAN "Enable vulkan" ON "LINUX OR APPLE OR FreeBSD OR OpenBSD OR NetBSD OR WIN32 OR ANDROID OR SunOS OR Haiku" OFF)
cmake_dependent_option(ENABLE_WAYLAND "Enable wayland-client" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD" OFF)
cmake_dependent_option(ENABLE_XCB_RANDR "Enable xcb-randr" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR SunOS" OFF)
cmake_dependent_option(ENABLE_XRANDR "Enable xrandr" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR SunOS" OFF)
cmake_dependent_option(ENABLE_DRM "Enable libdrm" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR SunOS" OFF)
cmake_dependent_option(ENABLE_DRM_AMDGPU "Enable libdrm_amdgpu" ON "LINUX OR FreeBSD" OFF)
cmake_dependent_option(ENABLE_GIO "Enable gio-2.0" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR SunOS" OFF)
cmake_dependent_option(ENABLE_DCONF "Enable dconf" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR SunOS" OFF)
cmake_dependent_option(ENABLE_DBUS "Enable dbus-1" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR SunOS OR Haiku" OFF)
cmake_dependent_option(ENABLE_XFCONF "Enable libxfconf-0" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR SunOS" OFF)
cmake_dependent_option(ENABLE_SQLITE3 "Enable sqlite3" ON "LINUX OR FreeBSD OR APPLE OR OpenBSD OR NetBSD OR SunOS" OFF)
cmake_dependent_option(ENABLE_RPM "Enable rpm" ON "LINUX" OFF)
cmake_dependent_option(ENABLE_IMAGEMAGICK7 "Enable imagemagick 7" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR APPLE OR WIN32 OR SunOS OR Haiku" OFF)
cmake_dependent_option(ENABLE_IMAGEMAGICK6 "Enable imagemagick 6" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR APPLE OR SunOS" OFF)
cmake_dependent_option(ENABLE_VULKAN "Enable vulkan" ON "LINUX OR APPLE OR FreeBSD OR OpenBSD OR NetBSD OR WIN32 OR ANDROID OR SunOS OR Haiku OR GNU" OFF)
cmake_dependent_option(ENABLE_WAYLAND "Enable wayland-client" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR GNU" OFF)
cmake_dependent_option(ENABLE_XCB_RANDR "Enable xcb-randr" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR SunOS OR GNU" OFF)
cmake_dependent_option(ENABLE_XRANDR "Enable xrandr" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR SunOS OR GNU" OFF)
cmake_dependent_option(ENABLE_DRM "Enable libdrm" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR SunOS OR GNU" OFF)
cmake_dependent_option(ENABLE_DRM_AMDGPU "Enable libdrm_amdgpu" ON "LINUX OR FreeBSD OR GNU" OFF)
cmake_dependent_option(ENABLE_GIO "Enable gio-2.0" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR SunOS OR GNU" OFF)
cmake_dependent_option(ENABLE_DCONF "Enable dconf" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR SunOS OR GNU" OFF)
cmake_dependent_option(ENABLE_DBUS "Enable dbus-1" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR SunOS OR Haiku OR GNU" OFF)
cmake_dependent_option(ENABLE_SQLITE3 "Enable sqlite3" ON "LINUX OR FreeBSD OR APPLE OR OpenBSD OR NetBSD OR SunOS OR GNU" OFF)
cmake_dependent_option(ENABLE_RPM "Enable rpm" ON "LINUX OR GNU" OFF)
cmake_dependent_option(ENABLE_IMAGEMAGICK7 "Enable imagemagick 7" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR APPLE OR ANDROID OR WIN32 OR SunOS OR Haiku OR GNU" OFF)
cmake_dependent_option(ENABLE_IMAGEMAGICK6 "Enable imagemagick 6" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR APPLE OR SunOS OR GNU" OFF)
cmake_dependent_option(ENABLE_CHAFA "Enable chafa" ON "ENABLE_IMAGEMAGICK6 OR ENABLE_IMAGEMAGICK7" OFF)
cmake_dependent_option(ENABLE_ZLIB "Enable zlib" ON "ENABLE_IMAGEMAGICK6 OR ENABLE_IMAGEMAGICK7" OFF)
cmake_dependent_option(ENABLE_EGL "Enable egl" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR WIN32 OR SunOS OR Haiku" OFF)
cmake_dependent_option(ENABLE_GLX "Enable glx" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR SunOS" OFF)
cmake_dependent_option(ENABLE_OPENCL "Enable opencl" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR WIN32 OR ANDROID OR SunOS OR Haiku" OFF)
cmake_dependent_option(ENABLE_EGL "Enable egl" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR WIN32 OR SunOS OR Haiku OR GNU" OFF)
cmake_dependent_option(ENABLE_GLX "Enable glx" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR SunOS OR GNU" OFF)
cmake_dependent_option(ENABLE_OPENCL "Enable opencl" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR WIN32 OR ANDROID OR SunOS OR Haiku OR GNU" OFF)
cmake_dependent_option(ENABLE_FREETYPE "Enable freetype" ON "ANDROID" OFF)
cmake_dependent_option(ENABLE_PULSE "Enable pulse" ON "LINUX" OFF)
cmake_dependent_option(ENABLE_PULSE "Enable pulse" ON "LINUX OR ANDROID OR GNU" OFF)
cmake_dependent_option(ENABLE_DDCUTIL "Enable ddcutil" ON "LINUX" OFF)
cmake_dependent_option(ENABLE_DIRECTX_HEADERS "Enable DirectX headers for WSL" ON "LINUX" OFF)
cmake_dependent_option(ENABLE_ELF "Enable libelf" ON "LINUX OR ANDROID OR DragonFly OR Haiku" OFF)
cmake_dependent_option(ENABLE_ELF "Enable libelf" ON "LINUX OR ANDROID OR DragonFly OR Haiku OR GNU" OFF)
cmake_dependent_option(ENABLE_THREADS "Enable multithreading" ON "Threads_FOUND" OFF)
cmake_dependent_option(ENABLE_LIBZFS "Enable libzfs" ON "LINUX OR FreeBSD OR SunOS" OFF)
cmake_dependent_option(ENABLE_PCIACCESS "Enable libpciaccess" ON "NetBSD OR OpenBSD" OFF)
option(ENABLE_ZLIB "Enable zlib" ON)
option(ENABLE_SYSTEM_YYJSON "Use system provided (instead of fastfetch embedded) yyjson library" OFF)
option(ENABLE_ASAN "Build fastfetch with ASAN (address sanitizer)" OFF)
option(ENABLE_LTO "Enable link-time optimization in release mode if supported" ON)
@@ -370,6 +371,7 @@ set(LIBFASTFETCH_SRC
src/common/settings.c
src/common/size.c
src/common/temps.c
src/common/time.c
src/detection/bluetoothradio/bluetoothradio.c
src/detection/bootmgr/bootmgr.c
src/detection/chassis/chassis.c
@@ -512,6 +514,7 @@ if(LINUX)
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/diskio/diskio_linux.c
src/detection/displayserver/linux/displayserver_linux.c
src/detection/displayserver/linux/common.c
src/detection/displayserver/linux/drm.c
src/detection/displayserver/linux/wayland/wayland.c
src/detection/displayserver/linux/wayland/global-output.c
@@ -572,6 +575,7 @@ if(LINUX)
)
elseif(ANDROID)
list(APPEND LIBFASTFETCH_SRC
src/common/dbus.c
src/common/io/io_unix.c
src/common/netif/netif_linux.c
src/common/networking/networking_linux.c
@@ -587,7 +591,7 @@ elseif(ANDROID)
src/detection/chassis/chassis_nosupport.c
src/detection/cpu/cpu_linux.c
src/detection/cpucache/cpucache_linux.c
src/detection/cursor/cursor_nosupport.c
src/detection/cursor/cursor_linux.c
src/detection/cpuusage/cpuusage_linux.c
src/detection/disk/disk_linux.c
src/detection/dns/dns_linux.c
@@ -595,10 +599,16 @@ elseif(ANDROID)
src/detection/physicalmemory/physicalmemory_nosupport.c
src/detection/diskio/diskio_linux.c
src/detection/displayserver/displayserver_android.c
src/detection/font/font_nosupport.c
src/detection/gpu/gpu_nosupport.c
src/detection/displayserver/linux/common.c
src/detection/displayserver/linux/wmde.c
src/detection/displayserver/linux/xcb.c
src/detection/displayserver/linux/xlib.c
src/detection/gtk_qt/gtk.c
src/detection/gtk_qt/qt.c
src/detection/font/font_linux.c
src/detection/gpu/gpu_android.c
src/detection/host/host_android.c
src/detection/icons/icons_nosupport.c
src/detection/icons/icons_linux.c
src/detection/initsystem/initsystem_linux.c
src/detection/keyboard/keyboard_nosupport.c
src/detection/libc/libc_android.c
@@ -607,7 +617,7 @@ elseif(ANDROID)
src/detection/locale/locale_linux.c
src/detection/localip/localip_linux.c
src/detection/gamepad/gamepad_nosupport.c
src/detection/media/media_nosupport.c
src/detection/media/media_linux.c
src/detection/memory/memory_linux.c
src/detection/mouse/mouse_nosupport.c
src/detection/netio/netio_linux.c
@@ -617,20 +627,21 @@ elseif(ANDROID)
src/detection/packages/packages_nix.c
src/detection/poweradapter/poweradapter_nosupport.c
src/detection/processes/processes_linux.c
src/detection/sound/sound_nosupport.c
src/detection/sound/sound_linux.c
src/detection/swap/swap_linux.c
src/detection/terminalfont/terminalfont_android.c
src/detection/terminalfont/terminalfont_linux.c
src/detection/terminalshell/terminalshell_linux.c
src/detection/terminalsize/terminalsize_linux.c
src/detection/theme/theme_nosupport.c
src/detection/theme/theme_linux.c
src/detection/tpm/tpm_nosupport.c
src/detection/uptime/uptime_linux.c
src/detection/users/users_linux.c
src/detection/wallpaper/wallpaper_nosupport.c
src/detection/wallpaper/wallpaper_linux.c
src/detection/wifi/wifi_android.c
src/detection/wm/wm_nosupport.c
src/detection/de/de_nosupport.c
src/detection/wmtheme/wmtheme_nosupport.c
src/detection/wm/wm_linux.c
src/detection/de/de_linux.c
src/detection/wmtheme/wmtheme_linux.c
src/detection/camera/camera_android.c
src/detection/zpool/zpool_nosupport.c
src/util/platform/FFPlatform_unix.c
@@ -662,6 +673,7 @@ elseif(FreeBSD)
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/diskio/diskio_bsd.c
src/detection/displayserver/linux/displayserver_linux.c
src/detection/displayserver/linux/common.c
src/detection/displayserver/linux/drm.c
src/detection/displayserver/linux/wayland/wayland.c
src/detection/displayserver/linux/wayland/global-output.c
@@ -756,6 +768,7 @@ elseif(NetBSD)
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/diskio/diskio_nbsd.c
src/detection/displayserver/linux/displayserver_linux.c
src/detection/displayserver/linux/common.c
src/detection/displayserver/linux/drm.c
src/detection/displayserver/linux/wayland/wayland.c
src/detection/displayserver/linux/wayland/global-output.c
@@ -838,6 +851,7 @@ elseif(OpenBSD)
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/diskio/diskio_obsd.c
src/detection/displayserver/linux/displayserver_linux.c
src/detection/displayserver/linux/common.c
src/detection/displayserver/linux/drm.c
src/detection/displayserver/linux/wayland/wayland.c
src/detection/displayserver/linux/wayland/global-output.c
@@ -1066,6 +1080,7 @@ elseif(SunOS)
src/detection/physicalmemory/physicalmemory_linux.c
src/detection/diskio/diskio_sunos.c
src/detection/displayserver/linux/displayserver_linux.c
src/detection/displayserver/linux/common.c
src/detection/displayserver/linux/drm.c
src/detection/displayserver/linux/wayland/wayland.c
src/detection/displayserver/linux/wayland/global-output.c
@@ -1191,6 +1206,85 @@ elseif(Haiku)
src/util/binary_linux.c
src/util/haiku/version.cpp
)
elseif(GNU)
list(APPEND LIBFASTFETCH_SRC
src/common/dbus.c
src/common/io/io_unix.c
src/common/netif/netif_gnu.c
src/common/networking/networking_linux.c
src/common/processing_linux.c
src/detection/battery/battery_nosupport.c
src/detection/bios/bios_nosupport.c
src/detection/board/board_nosupport.c
src/detection/bootmgr/bootmgr_nosupport.c
src/detection/brightness/brightness_nosupport.c
src/detection/btrfs/btrfs_nosupport.c
src/detection/chassis/chassis_nosupport.c
src/detection/cpu/cpu_linux.c
src/detection/cpucache/cpucache_nosupport.c
src/detection/cpuusage/cpuusage_linux.c
src/detection/cursor/cursor_linux.c
src/detection/bluetooth/bluetooth_linux.c
src/detection/bluetoothradio/bluetoothradio_linux.c
src/detection/disk/disk_linux.c
src/detection/dns/dns_linux.c
src/detection/physicaldisk/physicaldisk_nosupport.c
src/detection/physicalmemory/physicalmemory_nosupport.c
src/detection/diskio/diskio_nosupport.c
src/detection/displayserver/linux/displayserver_linux.c
src/detection/displayserver/linux/common.c
src/detection/displayserver/linux/drm.c
src/detection/displayserver/linux/wayland/wayland.c
src/detection/displayserver/linux/wayland/global-output.c
src/detection/displayserver/linux/wayland/zwlr-output.c
src/detection/displayserver/linux/wayland/wlr-output-management-unstable-v1-protocol.c
src/detection/displayserver/linux/wmde.c
src/detection/displayserver/linux/xcb.c
src/detection/displayserver/linux/xlib.c
src/detection/font/font_linux.c
src/detection/gpu/gpu_nosupport.c
src/detection/gpu/gpu_pci.c
src/detection/gtk_qt/gtk.c
src/detection/host/host_nosupport.c
src/detection/icons/icons_linux.c
src/detection/initsystem/initsystem_linux.c
src/detection/keyboard/keyboard_nosupport.c
src/detection/libc/libc_linux.c
src/detection/lm/lm_linux.c
src/detection/loadavg/loadavg_linux.c
src/detection/locale/locale_linux.c
src/detection/localip/localip_linux.c
src/detection/gamepad/gamepad_nosupport.c
src/detection/media/media_linux.c
src/detection/memory/memory_linux.c
src/detection/mouse/mouse_nosupport.c
src/detection/netio/netio_nosupport.c
src/detection/opengl/opengl_linux.c
src/detection/os/os_linux.c
src/detection/packages/packages_linux.c
src/detection/packages/packages_nix.c
src/detection/poweradapter/poweradapter_nosupport.c
src/detection/processes/processes_linux.c
src/detection/gtk_qt/qt.c
src/detection/sound/sound_linux.c
src/detection/swap/swap_linux.c
src/detection/terminalfont/terminalfont_linux.c
src/detection/terminalshell/terminalshell_linux.c
src/detection/terminalsize/terminalsize_linux.c
src/detection/theme/theme_linux.c
src/detection/tpm/tpm_nosupport.c
src/detection/uptime/uptime_linux.c
src/detection/users/users_linux.c
src/detection/wallpaper/wallpaper_linux.c
src/detection/wifi/wifi_nosupport.c
src/detection/wm/wm_linux.c
src/detection/de/de_linux.c
src/detection/wmtheme/wmtheme_linux.c
src/detection/camera/camera_nosupport.c
src/detection/zpool/zpool_nosupport.c
src/util/platform/FFPlatform_unix.c
src/util/binary_linux.c
)
endif()
if(ENABLE_DIRECTX_HEADERS)
@@ -1314,6 +1408,10 @@ elseif(NetBSD)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath,/usr/X11R7/lib -Wl,-rpath,/usr/pkg/lib") # ditto
elseif(Haiku)
target_compile_definitions(libfastfetch PUBLIC _GNU_SOURCE)
elseif(GNU)
target_compile_definitions(libfastfetch PUBLIC _GNU_SOURCE)
# On Hurd PATH_MAX is not defined. Set an arbitrary limit as workaround.
target_compile_definitions(libfastfetch PUBLIC PATH_MAX=4096)
endif()
if(FreeBSD OR OpenBSD OR NetBSD)
@@ -1440,10 +1538,6 @@ ff_lib_enable(DBUS
"dbus-1"
"DBus"
)
ff_lib_enable(XFCONF
"libxfconf-0"
"XFConf"
)
ff_lib_enable(SQLITE3
"sqlite3"
"SQLite3"
@@ -1638,7 +1732,14 @@ elseif(SunOS)
PRIVATE "nvpair"
PRIVATE "devinfo"
)
elseif(GNU)
target_link_libraries(libfastfetch
PRIVATE "m"
)
elseif(ANDROID)
target_link_libraries(libfastfetch
PRIVATE "m"
)
CHECK_LIBRARY_EXISTS(-l:libandroid-wordexp.a wordexp "" HAVE_LIBANDROID_WORDEXP_STATIC)
if(HAVE_LIBANDROID_WORDEXP_STATIC)
target_link_libraries(libfastfetch
+12
View File
@@ -1,3 +1,15 @@
fastfetch (2.51.0) jammy; urgency=medium
* Update to 2.51.0
-- Carter Li <zhangsongcui@live.cn> Fri, 29 Aug 2025 08:55:03 +0800
fastfetch (2.50.2) jammy; urgency=medium
* Update to 2.50.2
-- Carter Li <zhangsongcui@live.cn> Thu, 21 Aug 2025 10:33:07 +0800
fastfetch (2.49.0) jammy; urgency=medium
* Update to 2.49.0
+1 -1
View File
@@ -1 +1 @@
fastfetch_2.49.0_source.buildinfo universe/utils optional
fastfetch_2.51.0_source.buildinfo universe/utils optional
+63 -11
View File
@@ -2,11 +2,19 @@
"$schema": "https://json-schema.org/draft-07/schema",
"$defs": {
"colors": {
"type": "string",
"description": "https://github.com/fastfetch-cli/fastfetch/wiki/Color-Format-Specification",
"examples": [
"reset_", "bright_", "dim_", "italic_", "underline_", "blink_", "inverse_", "hidden_", "strike_", "light_",
"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "default"
"oneOf": [
{
"type": "string",
"$comment": "https://github.com/fastfetch-cli/fastfetch/wiki/Color-Format-Specification",
"examples": [
"reset_", "bright_", "dim_", "italic_", "underline_", "blink_", "inverse_", "hidden_", "strike_", "light_",
"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "default"
]
},
{
"type": "null",
"$comment": "Disable default color"
}
]
},
"key": {
@@ -229,6 +237,19 @@
"description": "Null to disable this condition"
}
]
},
"succeeded": {
"description": "Whether the module succeeded in the last run",
"oneOf": [
{
"type": "boolean",
"description": "True to only show the module if it succeeded, false to only show it if it failed"
},
{
"type": "null",
"description": "Null to disable this condition"
}
]
}
}
},
@@ -297,7 +318,7 @@
"type": "string"
},
"cpuFormat": {
"description": "Output format of the module `CPU`. See Wiki for formatting syntax\n 1. {name}: Name\n 2. {vendor}: Vendor\n 3. {cores-physical}: Physical core count\n 4. {cores-logical}: Logical core count\n 5. {cores-online}: Online core count\n 6. {freq-base}: Base frequency (formatted)\n 7. {freq-max}: Max frequency (formatted)\n 8. {temperature}: Temperature (formatted)\n 9. {core-types}: Logical core count grouped by frequency\n 10. {packages}: Processor package count",
"description": "Output format of the module `CPU`. See Wiki for formatting syntax\n 1. {name}: Name\n 2. {vendor}: Vendor\n 3. {cores-physical}: Physical core count\n 4. {cores-logical}: Logical core count\n 5. {cores-online}: Online core count\n 6. {freq-base}: Base frequency (formatted)\n 7. {freq-max}: Max frequency (formatted)\n 8. {temperature}: Temperature (formatted)\n 9. {core-types}: Logical core count grouped by frequency\n 10. {packages}: Processor package count\n 11. {march}: X86-64 CPU microarchitecture",
"type": "string"
},
"cpucacheFormat": {
@@ -325,7 +346,7 @@
"type": "string"
},
"diskFormat": {
"description": "Output format of the module `Disk`. See Wiki for formatting syntax\n 1. {size-used}: Size used\n 2. {size-total}: Size total\n 3. {size-percentage}: Size percentage num\n 4. {files-used}: Files used\n 5. {files-total}: Files total\n 6. {files-percentage}: Files percentage num\n 7. {is-external}: True if external volume\n 8. {is-hidden}: True if hidden volume\n 9. {filesystem}: Filesystem\n 10. {name}: Label / name\n 11. {is-readonly}: True if read-only\n 12. {create-time}: Create time in local timezone\n 13. {size-percentage-bar}: Size percentage bar\n 14. {files-percentage-bar}: Files percentage bar\n 15. {days}: Days after creation\n 16. {hours}: Hours after creation\n 17. {minutes}: Minutes after creation\n 18. {seconds}: Seconds after creation\n 19. {milliseconds}: Milliseconds after creation\n 20. {mountpoint}: Mount point / drive letter\n 21. {mount-from}: Mount from (device path)\n 22. {years}: Years integer after creation\n 23. {days-of-year}: Days of year after creation\n 24. {years-fraction}: Years fraction after creation",
"description": "Output format of the module `Disk`. See Wiki for formatting syntax\n 1. {size-used}: Size used\n 2. {size-total}: Size total\n 3. {size-percentage}: Size percentage num\n 4. {files-used}: Files used\n 5. {files-total}: Files total\n 6. {files-percentage}: Files percentage num\n 7. {is-external}: True if external volume\n 8. {is-hidden}: True if hidden volume\n 9. {filesystem}: Filesystem\n 10. {name}: Label / name\n 11. {is-readonly}: True if read-only\n 12. {create-time}: Create time in local timezone\n 13. {size-percentage-bar}: Size percentage bar\n 14. {files-percentage-bar}: Files percentage bar\n 15. {days}: Days after creation\n 16. {hours}: Hours after creation\n 17. {minutes}: Minutes after creation\n 18. {seconds}: Seconds after creation\n 19. {milliseconds}: Milliseconds after creation\n 20. {mountpoint}: Mount point / drive letter\n 21. {mount-from}: Mount from (device path)\n 22. {years}: Years integer after creation\n 23. {days-of-year}: Days of year after creation\n 24. {years-fraction}: Years fraction after creation\n 25. {size-free}: Size free\n 26. {size-available}: Size available",
"type": "string"
},
"diskioFormat": {
@@ -1269,10 +1290,19 @@
"description": "Set how frequency values should be displayed",
"properties": {
"ndigits": {
"type": "integer",
"description": "Set the number of digits to keep after the decimal point when formatting frequency values\nA positive value will show the frequency in GHz with decimal\n-1 will show the frequency in MHz",
"minimum": -1,
"maximum": 9,
"description": "Set the number of decimal places to display when formatting frequency values",
"oneOf": [
{
"type": "integer",
"minimum": 0,
"maximum": 9,
"description": "Integer value displays the frequency in GHz with specified decimal places"
},
{
"type": "null",
"description": "Null value display the frequency as integer MHz"
}
],
"default": 2
},
"spaceBeforeUnit": {
@@ -1312,6 +1342,28 @@
"description": "The number of digits will be automatically determined based on the value"
}
],
"default": 2
},
"trailingZeros": {
"description": "Set when to keep trailing zeros",
"oneOf": [
{
"type": "null",
"description": "Same as `default`"
},
{
"const": "default",
"description": "Use the behavior defined internally"
},
{
"const": "always",
"description": "Always keep trailing zeros"
},
{
"const": "never",
"description": "Never keep trailing zeros"
}
],
"default": null
}
}
+3 -3
View File
@@ -15,9 +15,9 @@
"bar": {
"border": {
"left": "[",
"leftElapsed": "[",
"leftElapsed": "[",
"right": "]",
"rightElapsed": "]"
"rightElapsed": "]"
},
"char": {
"elapsed": "─",
@@ -27,7 +27,7 @@
"elapsed": "default",
"total": "light_black"
},
"width": 14
"width": 16
},
"color": {
"separator": "default",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"home": "https://github.com/ibireme/yyjson",
"license": "MIT ( embed in source )",
"version": "0.11.1",
"version": "0.12.0",
"author": "ibireme"
}
+4196 -3943
View File
File diff suppressed because it is too large Load Diff
+174 -116
View File
@@ -32,7 +32,7 @@
/*==============================================================================
* Header Files
* MARK: - Header Files
*============================================================================*/
#include <stdio.h>
@@ -45,7 +45,7 @@
/*==============================================================================
* Compile-time Options
* MARK: - Compile-time Options
*============================================================================*/
/*
@@ -89,14 +89,8 @@
#endif
/*
Define as 1 to disable non-standard JSON features support at compile-time:
- YYJSON_READ_ALLOW_INF_AND_NAN
- YYJSON_READ_ALLOW_COMMENTS
- YYJSON_READ_ALLOW_TRAILING_COMMAS
- YYJSON_READ_ALLOW_INVALID_UNICODE
- YYJSON_READ_ALLOW_BOM
- YYJSON_WRITE_ALLOW_INF_AND_NAN
- YYJSON_WRITE_ALLOW_INVALID_UNICODE
Define as 1 to disable non-standard JSON features support at compile-time,
such as YYJSON_READ_ALLOW_XXX and YYJSON_WRITE_ALLOW_XXX.
This reduces binary size by about 10%, and slightly improves performance.
*/
@@ -151,7 +145,7 @@
/*==============================================================================
* Compiler Macros
* MARK: - Compiler Macros
*============================================================================*/
/** compiler version (MSVC) */
@@ -179,8 +173,10 @@
#endif
/** real gcc check */
#if !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__ICC) && \
defined(__GNUC__)
#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \
!defined(__clang__) && !defined(__llvm__) && \
!defined(__INTEL_COMPILER) && !defined(__ICC) && \
!defined(__NVCC__) && !defined(__PGI) && !defined(__TINYC__)
# define YYJSON_IS_REAL_GCC 1
#else
# define YYJSON_IS_REAL_GCC 0
@@ -465,7 +461,7 @@
/*==============================================================================
* Compile Hint Begin
* MARK: - Compile Hint Begin
*============================================================================*/
/* extern "C" begin */
@@ -492,23 +488,23 @@ extern "C" {
/*==============================================================================
* Version
* MARK: - Version
*============================================================================*/
/** The major version of yyjson. */
#define YYJSON_VERSION_MAJOR 0
/** The minor version of yyjson. */
#define YYJSON_VERSION_MINOR 11
#define YYJSON_VERSION_MINOR 12
/** The patch version of yyjson. */
#define YYJSON_VERSION_PATCH 1
#define YYJSON_VERSION_PATCH 0
/** The version of yyjson in hex: `(major << 16) | (minor << 8) | (patch)`. */
#define YYJSON_VERSION_HEX 0x000B01
#define YYJSON_VERSION_HEX 0x000C00
/** The version string of yyjson. */
#define YYJSON_VERSION_STRING "0.11.1"
#define YYJSON_VERSION_STRING "0.12.0"
/** The version of yyjson in hex, same as `YYJSON_VERSION_HEX`. */
yyjson_api uint32_t yyjson_version(void);
@@ -516,7 +512,7 @@ yyjson_api uint32_t yyjson_version(void);
/*==============================================================================
* JSON Types
* MARK: - JSON Types
*============================================================================*/
/** Type of a JSON value (3 bit). */
@@ -578,7 +574,7 @@ typedef uint8_t yyjson_subtype;
/*==============================================================================
* Allocator
* MARK: - Allocator
*============================================================================*/
/**
@@ -662,7 +658,7 @@ yyjson_api void yyjson_alc_dyn_free(yyjson_alc *alc);
/*==============================================================================
* Text Locating
* MARK: - Text Locating
*============================================================================*/
/**
@@ -686,7 +682,7 @@ yyjson_api bool yyjson_locate_pos(const char *str, size_t len, size_t pos,
/*==============================================================================
* JSON Structure
* MARK: - JSON Structure
*============================================================================*/
/**
@@ -720,7 +716,7 @@ typedef struct yyjson_mut_val yyjson_mut_val;
/*==============================================================================
* JSON Reader API
* MARK: - JSON Reader API
*============================================================================*/
/** Run-time options for JSON reader. */
@@ -734,7 +730,7 @@ typedef uint32_t yyjson_read_flag;
- Report error if double number is infinity.
- Report error if string contains invalid UTF-8 character or BOM.
- Report error on trailing commas, comments, inf and nan literals. */
static const yyjson_read_flag YYJSON_READ_NOFLAG = 0;
static const yyjson_read_flag YYJSON_READ_NOFLAG = 0;
/** Read the input data in-situ.
This option allows the reader to modify and use input data to store string
@@ -742,27 +738,27 @@ static const yyjson_read_flag YYJSON_READ_NOFLAG = 0;
The caller should hold the input data before free the document.
The input data must be padded by at least `YYJSON_PADDING_SIZE` bytes.
For example: `[1,2]` should be `[1,2]\0\0\0\0`, input length should be 5. */
static const yyjson_read_flag YYJSON_READ_INSITU = 1 << 0;
static const yyjson_read_flag YYJSON_READ_INSITU = 1 << 0;
/** Stop when done instead of issuing an error if there's additional content
after a JSON document. This option may be used to parse small pieces of JSON
in larger data, such as `NDJSON`. */
static const yyjson_read_flag YYJSON_READ_STOP_WHEN_DONE = 1 << 1;
static const yyjson_read_flag YYJSON_READ_STOP_WHEN_DONE = 1 << 1;
/** Allow single trailing comma at the end of an object or array,
such as `[1,2,3,]`, `{"a":1,"b":2,}` (non-standard). */
static const yyjson_read_flag YYJSON_READ_ALLOW_TRAILING_COMMAS = 1 << 2;
static const yyjson_read_flag YYJSON_READ_ALLOW_TRAILING_COMMAS = 1 << 2;
/** Allow C-style single line and multiple line comments (non-standard). */
static const yyjson_read_flag YYJSON_READ_ALLOW_COMMENTS = 1 << 3;
/** Allow C-style single-line and mult-line comments (non-standard). */
static const yyjson_read_flag YYJSON_READ_ALLOW_COMMENTS = 1 << 3;
/** Allow inf/nan number and literal, case-insensitive,
such as 1e999, NaN, inf, -Infinity (non-standard). */
static const yyjson_read_flag YYJSON_READ_ALLOW_INF_AND_NAN = 1 << 4;
static const yyjson_read_flag YYJSON_READ_ALLOW_INF_AND_NAN = 1 << 4;
/** Read all numbers as raw strings (value with `YYJSON_TYPE_RAW` type),
inf/nan literal is also read as raw with `ALLOW_INF_AND_NAN` flag. */
static const yyjson_read_flag YYJSON_READ_NUMBER_AS_RAW = 1 << 5;
static const yyjson_read_flag YYJSON_READ_NUMBER_AS_RAW = 1 << 5;
/** Allow reading invalid unicode when parsing string values (non-standard).
Invalid characters will be allowed to appear in the string values, but
@@ -772,16 +768,62 @@ static const yyjson_read_flag YYJSON_READ_NUMBER_AS_RAW = 1 << 5;
@warning Strings in JSON values may contain incorrect encoding when this
option is used, you need to handle these strings carefully to avoid security
risks. */
static const yyjson_read_flag YYJSON_READ_ALLOW_INVALID_UNICODE = 1 << 6;
static const yyjson_read_flag YYJSON_READ_ALLOW_INVALID_UNICODE = 1 << 6;
/** Read big numbers as raw strings. These big numbers include integers that
cannot be represented by `int64_t` and `uint64_t`, and floating-point
numbers that cannot be represented by finite `double`.
The flag will be overridden by `YYJSON_READ_NUMBER_AS_RAW` flag. */
static const yyjson_read_flag YYJSON_READ_BIGNUM_AS_RAW = 1 << 7;
static const yyjson_read_flag YYJSON_READ_BIGNUM_AS_RAW = 1 << 7;
/** Allow UTF-8 BOM and skip it before parsing if any (non-standard). */
static const yyjson_read_flag YYJSON_READ_ALLOW_BOM = 1 << 8;
static const yyjson_read_flag YYJSON_READ_ALLOW_BOM = 1 << 8;
/** Allow extended number formats (non-standard):
- Hexadecimal numbers, such as `0x7B`.
- Numbers with leading or trailing decimal point, such as `.123`, `123.`.
- Numbers with a leading plus sign, such as `+123`. */
static const yyjson_read_flag YYJSON_READ_ALLOW_EXT_NUMBER = 1 << 9;
/** Allow extended escape sequences in strings (non-standard):
- Additional escapes: `\a`, `\e`, `\v`, ``\'``, `\?`, `\0`.
- Hex escapes: `\xNN`, such as `\x7B`.
- Line continuation: backslash followed by line terminator sequences.
- Unknown escape: if backslash is followed by an unsupported character,
the backslash will be removed and the character will be kept as-is.
However, `\1`-`\9` will still trigger an error. */
static const yyjson_read_flag YYJSON_READ_ALLOW_EXT_ESCAPE = 1 << 10;
/** Allow extended whitespace characters (non-standard):
- Vertical tab `\v` and form feed `\f`.
- Line separator `\u2028` and paragraph separator `\u2029`.
- Non-breaking space `\xA0`.
- Byte order mark: `\uFEFF`.
- Other Unicode characters in the Zs (Separator, space) category. */
static const yyjson_read_flag YYJSON_READ_ALLOW_EXT_WHITESPACE = 1 << 11;
/** Allow strings enclosed in single quotes (non-standard), such as ``'ab'``. */
static const yyjson_read_flag YYJSON_READ_ALLOW_SINGLE_QUOTED_STR = 1 << 12;
/** Allow object keys without quotes (non-standard), such as `{a:1,b:2}`.
This extends the ECMAScript IdentifierName rule by allowing any
non-whitespace character with code point above `U+007F`. */
static const yyjson_read_flag YYJSON_READ_ALLOW_UNQUOTED_KEY = 1 << 13;
/** Allow JSON5 format, see: [https://json5.org].
This flag supports all JSON5 features with some additional extensions:
- Accepts more escape sequences than JSON5 (e.g. `\a`, `\e`).
- Unquoted keys are not limited to ECMAScript IdentifierName.
- Allow case-insensitive `NaN`, `Inf` and `Infinity` literals. */
static const yyjson_read_flag YYJSON_READ_JSON5 =
(1 << 2) | /* YYJSON_READ_ALLOW_TRAILING_COMMAS */
(1 << 3) | /* YYJSON_READ_ALLOW_COMMENTS */
(1 << 4) | /* YYJSON_READ_ALLOW_INF_AND_NAN */
(1 << 9) | /* YYJSON_READ_ALLOW_EXT_NUMBER */
(1 << 10) | /* YYJSON_READ_ALLOW_EXT_ESCAPE */
(1 << 11) | /* YYJSON_READ_ALLOW_EXT_WHITESPACE */
(1 << 12) | /* YYJSON_READ_ALLOW_SINGLE_QUOTED_STR */
(1 << 13); /* YYJSON_READ_ALLOW_UNQUOTED_KEY */
@@ -794,7 +836,7 @@ static const yyjson_read_code YYJSON_READ_SUCCESS = 0;
/** Invalid parameter, such as NULL input string or 0 input length. */
static const yyjson_read_code YYJSON_READ_ERROR_INVALID_PARAMETER = 1;
/** Memory allocation failure occurs. */
/** Memory allocation failed. */
static const yyjson_read_code YYJSON_READ_ERROR_MEMORY_ALLOCATION = 2;
/** Input JSON string is empty. */
@@ -803,7 +845,7 @@ static const yyjson_read_code YYJSON_READ_ERROR_EMPTY_CONTENT = 3;
/** Unexpected content after document, such as `[123]abc`. */
static const yyjson_read_code YYJSON_READ_ERROR_UNEXPECTED_CONTENT = 4;
/** Unexpected ending, such as `[123`. */
/** Unexpected end of input, the parsed part is valid, such as `[123`. */
static const yyjson_read_code YYJSON_READ_ERROR_UNEXPECTED_END = 5;
/** Unexpected character inside the document, such as `[abc]`. */
@@ -812,7 +854,7 @@ static const yyjson_read_code YYJSON_READ_ERROR_UNEXPECTED_CHARACTER = 6;
/** Invalid JSON structure, such as `[1,]`. */
static const yyjson_read_code YYJSON_READ_ERROR_JSON_STRUCTURE = 7;
/** Invalid comment, such as unclosed multi-line comment. */
/** Invalid comment, deprecated, use `UNEXPECTED_END` for unclosed comment. */
static const yyjson_read_code YYJSON_READ_ERROR_INVALID_COMMENT = 8;
/** Invalid number, such as `123.e12`, `000`. */
@@ -830,7 +872,7 @@ static const yyjson_read_code YYJSON_READ_ERROR_FILE_OPEN = 12;
/** Failed to read a file. */
static const yyjson_read_code YYJSON_READ_ERROR_FILE_READ = 13;
/** Unexpected ending during incremental parsing. Parsing state is saved. */
/** Incomplete input during incremental parsing; parsing state is preserved. */
static const yyjson_read_code YYJSON_READ_ERROR_MORE = 14;
/** Error information for JSON reader. */
@@ -884,6 +926,7 @@ yyjson_api yyjson_doc *yyjson_read_opts(char *dat,
2. The `alc` is thread-safe or NULL.
@param path The JSON file's path.
This should be a null-terminated string using the system's native encoding.
If this path is NULL or invalid, the function will fail and return NULL.
@param flg The JSON read options.
Multiple options can be combined with `|` operator. 0 means no options.
@@ -960,6 +1003,9 @@ typedef struct yyjson_incr_state yyjson_incr_state;
2. Call `yyjson_incr_read()` repeatedly.
3. Call `yyjson_incr_free()` to free the state.
Note: The incremental JSON reader only supports standard JSON.
Flags for non-standard features (e.g. comments, trailing commas) are ignored.
@param buf The JSON data, null-terminator is not required.
If this parameter is NULL, the function will fail and return NULL.
@param buf_len The length of the JSON data in `buf`.
@@ -1088,27 +1134,7 @@ yyjson_api const char *yyjson_read_number(const char *dat,
const yyjson_alc *alc,
yyjson_read_err *err);
/**
Read a JSON number.
This function is thread-safe when data is not modified by other threads.
@param dat The JSON data (UTF-8 without BOM), null-terminator is required.
If this parameter is NULL, the function will fail and return NULL.
@param val The output value where result is stored.
If this parameter is NULL, the function will fail and return NULL.
The value will hold either UINT or SINT or REAL number;
@param flg The JSON read options.
Multiple options can be combined with `|` operator. 0 means no options.
Supports `YYJSON_READ_NUMBER_AS_RAW` and `YYJSON_READ_ALLOW_INF_AND_NAN`.
@param alc The memory allocator used for long number.
It is only used when the built-in floating point reader is disabled.
Pass NULL to use the libc's default allocator.
@param err A pointer to receive error information.
Pass NULL if you don't need error information.
@return If successful, a pointer to the character after the last character
used in the conversion, NULL if an error occurs.
*/
/** Same as `yyjson_read_number()`. */
yyjson_api_inline const char *yyjson_mut_read_number(const char *dat,
yyjson_mut_val *val,
yyjson_read_flag flg,
@@ -1122,7 +1148,7 @@ yyjson_api_inline const char *yyjson_mut_read_number(const char *dat,
/*==============================================================================
* JSON Writer API
* MARK: - JSON Writer API
*============================================================================*/
/** Run-time options for JSON writer. */
@@ -1230,7 +1256,7 @@ typedef struct yyjson_write_err {
#if !defined(YYJSON_DISABLE_WRITER) || !YYJSON_DISABLE_WRITER
/*==============================================================================
* JSON Document Writer API
* MARK: - JSON Document Writer API
*============================================================================*/
/**
@@ -1267,6 +1293,7 @@ yyjson_api char *yyjson_write_opts(const yyjson_doc *doc,
2. The `alc` is thread-safe or NULL.
@param path The JSON file's path.
This should be a null-terminated string using the system's native encoding.
If this path is NULL or invalid, the function will fail and return false.
If this file is not empty, the content will be discarded.
@param doc The JSON document.
@@ -1370,6 +1397,7 @@ yyjson_api char *yyjson_mut_write_opts(const yyjson_mut_doc *doc,
3. The `alc` is thread-safe or NULL.
@param path The JSON file's path.
This should be a null-terminated string using the system's native encoding.
If this path is NULL or invalid, the function will fail and return false.
If this file is not empty, the content will be discarded.
@param doc The mutable JSON document.
@@ -1439,7 +1467,7 @@ yyjson_api_inline char *yyjson_mut_write(const yyjson_mut_doc *doc,
/*==============================================================================
* JSON Value Writer API
* MARK: - JSON Value Writer API
*============================================================================*/
/**
@@ -1476,6 +1504,7 @@ yyjson_api char *yyjson_val_write_opts(const yyjson_val *val,
2. The `alc` is thread-safe or NULL.
@param path The JSON file's path.
This should be a null-terminated string using the system's native encoding.
If this path is NULL or invalid, the function will fail and return false.
If this file is not empty, the content will be discarded.
@param val The JSON root value.
@@ -1577,6 +1606,7 @@ yyjson_api char *yyjson_mut_val_write_opts(const yyjson_mut_val *val,
3. The `alc` is thread-safe or NULL.
@param path The JSON file's path.
This should be a null-terminated string using the system's native encoding.
If this path is NULL or invalid, the function will fail and return false.
If this file is not empty, the content will be discarded.
@param val The mutable JSON root value.
@@ -1643,12 +1673,40 @@ yyjson_api_inline char *yyjson_mut_val_write(const yyjson_mut_val *val,
return yyjson_mut_val_write_opts(val, flg, NULL, len, NULL);
}
/**
Write a JSON number.
@param val A JSON number value to be converted to a string.
If this parameter is invalid, the function will fail and return NULL.
@param buf A buffer to store the resulting null-terminated string.
If this parameter is NULL, the function will fail and return NULL.
For integer values, the buffer must be at least 21 bytes.
For floating-point values, the buffer must be at least 40 bytes.
@return On success, returns a pointer to the character after the last
written character. On failure, returns NULL.
@note
- This function is thread-safe and does not allocate memory
(when `YYJSON_DISABLE_FAST_FP_CONV` is not defined).
- This function will fail and return NULL only in the following cases:
1) `val` or `buf` is NULL;
2) `val` is not a number type;
3) `val` is `inf` or `nan`, and non-standard JSON is explicitly disabled
via the `YYJSON_DISABLE_NON_STANDARD` flag.
*/
yyjson_api char *yyjson_write_number(const yyjson_val *val, char *buf);
/** Same as `yyjson_write_number()`. */
yyjson_api_inline char *yyjson_mut_write_number(const yyjson_mut_val *val,
char *buf) {
return yyjson_write_number((const yyjson_val *)val, buf);
}
#endif /* YYJSON_DISABLE_WRITER */
/*==============================================================================
* JSON Document API
* MARK: - JSON Document API
*============================================================================*/
/** Returns the root value of this JSON document.
@@ -1673,7 +1731,7 @@ yyjson_api_inline void yyjson_doc_free(yyjson_doc *doc);
/*==============================================================================
* JSON Value Type API
* MARK: - JSON Value Type API
*============================================================================*/
/** Returns whether the JSON value is raw.
@@ -1735,7 +1793,7 @@ yyjson_api_inline bool yyjson_is_ctn(yyjson_val *val);
/*==============================================================================
* JSON Value Content API
* MARK: - JSON Value Content API
*============================================================================*/
/** Returns the JSON value's type.
@@ -1760,7 +1818,7 @@ yyjson_api_inline const char *yyjson_get_type_desc(yyjson_val *val);
yyjson_api_inline const char *yyjson_get_raw(yyjson_val *val);
/** Returns the content if the value is bool.
Returns NULL if `val` is NULL or type is not bool. */
Returns false if `val` is NULL or type is not bool. */
yyjson_api_inline bool yyjson_get_bool(yyjson_val *val);
/** Returns the content and cast to uint64_t.
@@ -1888,7 +1946,7 @@ yyjson_api_inline bool yyjson_set_str_noesc(yyjson_val *val, bool noesc);
/*==============================================================================
* JSON Array API
* MARK: - JSON Array API
*============================================================================*/
/** Returns the number of elements in this array.
@@ -1914,7 +1972,7 @@ yyjson_api_inline yyjson_val *yyjson_arr_get_last(yyjson_val *arr);
/*==============================================================================
* JSON Array Iterator API
* MARK: - JSON Array Iterator API
*============================================================================*/
/**
@@ -1996,7 +2054,7 @@ yyjson_api_inline yyjson_val *yyjson_arr_iter_next(yyjson_arr_iter *iter);
/*==============================================================================
* JSON Object API
* MARK: - JSON Object API
*============================================================================*/
/** Returns the number of key-value pairs in this object.
@@ -2026,7 +2084,7 @@ yyjson_api_inline yyjson_val *yyjson_obj_getn(yyjson_val *obj, const char *key,
/*==============================================================================
* JSON Object Iterator API
* MARK: - JSON Object Iterator API
*============================================================================*/
/**
@@ -2169,7 +2227,7 @@ yyjson_api_inline yyjson_val *yyjson_obj_iter_getn(yyjson_obj_iter *iter,
/*==============================================================================
* Mutable JSON Document API
* MARK: - Mutable JSON Document API
*============================================================================*/
/** Returns the root value of this JSON document.
@@ -2273,7 +2331,7 @@ yyjson_api yyjson_doc *yyjson_mut_val_imut_copy(yyjson_mut_val *val,
/*==============================================================================
* Mutable JSON Value Type API
* MARK: - Mutable JSON Value Type API
*============================================================================*/
/** Returns whether the JSON value is raw.
@@ -2335,7 +2393,7 @@ yyjson_api_inline bool yyjson_mut_is_ctn(yyjson_mut_val *val);
/*==============================================================================
* Mutable JSON Value Content API
* MARK: - Mutable JSON Value Content API
*============================================================================*/
/** Returns the JSON value's type.
@@ -2504,7 +2562,7 @@ yyjson_api_inline bool yyjson_mut_set_obj(yyjson_mut_val *val);
/*==============================================================================
* Mutable JSON Value Creation API
* MARK: - Mutable JSON Value Creation API
*============================================================================*/
/** Creates and returns a raw value, returns NULL on error.
@@ -2605,7 +2663,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_strncpy(yyjson_mut_doc *doc,
/*==============================================================================
* Mutable JSON Array API
* MARK: - Mutable JSON Array API
*============================================================================*/
/** Returns the number of elements in this array.
@@ -2629,7 +2687,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_arr_get_last(yyjson_mut_val *arr);
/*==============================================================================
* Mutable JSON Array Iterator API
* MARK: - Mutable JSON Array Iterator API
*============================================================================*/
/**
@@ -2731,7 +2789,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_arr_iter_remove(
/*==============================================================================
* Mutable JSON Array Creation API
* MARK: - Mutable JSON Array Creation API
*============================================================================*/
/**
@@ -3092,7 +3150,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_strncpy(
/*==============================================================================
* Mutable JSON Array Modification API
* MARK: - Mutable JSON Array Modification API
*============================================================================*/
/**
@@ -3205,7 +3263,7 @@ yyjson_api_inline bool yyjson_mut_arr_rotate(yyjson_mut_val *arr,
/*==============================================================================
* Mutable JSON Array Modification Convenience API
* MARK: - Mutable JSON Array Modification Convenience API
*============================================================================*/
/**
@@ -3411,7 +3469,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_arr_add_obj(yyjson_mut_doc *doc,
/*==============================================================================
* Mutable JSON Object API
* MARK: - Mutable JSON Object API
*============================================================================*/
/** Returns the number of key-value pairs in this object.
@@ -3443,7 +3501,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_obj_getn(yyjson_mut_val *obj,
/*==============================================================================
* Mutable JSON Object Iterator API
* MARK: - Mutable JSON Object Iterator API
*============================================================================*/
/**
@@ -3605,7 +3663,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_obj_iter_getn(
/*==============================================================================
* Mutable JSON Object Creation API
* MARK: - Mutable JSON Object Creation API
*============================================================================*/
/** Creates and returns a mutable object, returns NULL on error. */
@@ -3652,7 +3710,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_obj_with_kv(yyjson_mut_doc *doc,
/*==============================================================================
* Mutable JSON Object Modification API
* MARK: - Mutable JSON Object Modification API
*============================================================================*/
/**
@@ -3762,7 +3820,7 @@ yyjson_api_inline bool yyjson_mut_obj_rotate(yyjson_mut_val *obj,
/*==============================================================================
* Mutable JSON Object Modification Convenience API
* MARK: - Mutable JSON Object Modification Convenience API
*============================================================================*/
/** Adds a `null` value at the end of the object.
@@ -4002,7 +4060,7 @@ yyjson_api_inline bool yyjson_mut_obj_rename_keyn(yyjson_mut_doc *doc,
#if !defined(YYJSON_DISABLE_UTILS) || !YYJSON_DISABLE_UTILS
/*==============================================================================
* JSON Pointer API (RFC 6901)
* MARK: - JSON Pointer API (RFC 6901)
* https://tools.ietf.org/html/rfc6901
*============================================================================*/
@@ -4587,7 +4645,7 @@ yyjson_api_inline bool yyjson_ptr_ctx_remove(yyjson_ptr_ctx *ctx);
/*==============================================================================
* JSON Patch API (RFC 6902)
* MARK: - JSON Patch API (RFC 6902)
* https://tools.ietf.org/html/rfc6902
*============================================================================*/
@@ -4655,7 +4713,7 @@ yyjson_api yyjson_mut_val *yyjson_mut_patch(yyjson_mut_doc *doc,
/*==============================================================================
* JSON Merge-Patch API (RFC 7386)
* MARK: - JSON Merge-Patch API (RFC 7386)
* https://tools.ietf.org/html/rfc7386
*============================================================================*/
@@ -4688,7 +4746,7 @@ yyjson_api yyjson_mut_val *yyjson_mut_merge_patch(yyjson_mut_doc *doc,
/*==============================================================================
* JSON Structure (Implementation)
* MARK: - JSON Structure (Implementation)
*============================================================================*/
/** Payload of a JSON value (8 bytes). */
@@ -4725,7 +4783,7 @@ struct yyjson_doc {
/*==============================================================================
* Unsafe JSON Value API (Implementation)
* MARK: - Unsafe JSON Value API (Implementation)
*============================================================================*/
/*
@@ -5054,7 +5112,7 @@ yyjson_api_inline void unsafe_yyjson_set_obj(void *val, size_t size) {
/*==============================================================================
* JSON Document API (Implementation)
* MARK: - JSON Document API (Implementation)
*============================================================================*/
yyjson_api_inline yyjson_val *yyjson_doc_get_root(yyjson_doc *doc) {
@@ -5081,7 +5139,7 @@ yyjson_api_inline void yyjson_doc_free(yyjson_doc *doc) {
/*==============================================================================
* JSON Value Type API (Implementation)
* MARK: - JSON Value Type API (Implementation)
*============================================================================*/
yyjson_api_inline bool yyjson_is_raw(yyjson_val *val) {
@@ -5143,7 +5201,7 @@ yyjson_api_inline bool yyjson_is_ctn(yyjson_val *val) {
/*==============================================================================
* JSON Value Content API (Implementation)
* MARK: - JSON Value Content API (Implementation)
*============================================================================*/
yyjson_api_inline yyjson_type yyjson_get_type(yyjson_val *val) {
@@ -5326,7 +5384,7 @@ yyjson_api_inline bool yyjson_set_str_noesc(yyjson_val *val, bool noesc) {
/*==============================================================================
* JSON Array API (Implementation)
* MARK: - JSON Array API (Implementation)
*============================================================================*/
yyjson_api_inline size_t yyjson_arr_size(yyjson_val *arr) {
@@ -5376,7 +5434,7 @@ yyjson_api_inline yyjson_val *yyjson_arr_get_last(yyjson_val *arr) {
/*==============================================================================
* JSON Array Iterator API (Implementation)
* MARK: - JSON Array Iterator API (Implementation)
*============================================================================*/
yyjson_api_inline bool yyjson_arr_iter_init(yyjson_val *arr,
@@ -5415,7 +5473,7 @@ yyjson_api_inline yyjson_val *yyjson_arr_iter_next(yyjson_arr_iter *iter) {
/*==============================================================================
* JSON Object API (Implementation)
* MARK: - JSON Object API (Implementation)
*============================================================================*/
yyjson_api_inline size_t yyjson_obj_size(yyjson_val *obj) {
@@ -5444,7 +5502,7 @@ yyjson_api_inline yyjson_val *yyjson_obj_getn(yyjson_val *obj,
/*==============================================================================
* JSON Object Iterator API (Implementation)
* MARK: - JSON Object Iterator API (Implementation)
*============================================================================*/
yyjson_api_inline bool yyjson_obj_iter_init(yyjson_val *obj,
@@ -5521,7 +5579,7 @@ yyjson_api_inline yyjson_val *yyjson_obj_iter_getn(yyjson_obj_iter *iter,
/*==============================================================================
* Mutable JSON Structure (Implementation)
* MARK: - Mutable JSON Structure (Implementation)
*============================================================================*/
/**
@@ -5637,7 +5695,7 @@ yyjson_api_inline yyjson_mut_val *unsafe_yyjson_mut_val(yyjson_mut_doc *doc,
/*==============================================================================
* Mutable JSON Document API (Implementation)
* MARK: - Mutable JSON Document API (Implementation)
*============================================================================*/
yyjson_api_inline yyjson_mut_val *yyjson_mut_doc_get_root(yyjson_mut_doc *doc) {
@@ -5652,7 +5710,7 @@ yyjson_api_inline void yyjson_mut_doc_set_root(yyjson_mut_doc *doc,
/*==============================================================================
* Mutable JSON Value Type API (Implementation)
* MARK: - Mutable JSON Value Type API (Implementation)
*============================================================================*/
yyjson_api_inline bool yyjson_mut_is_raw(yyjson_mut_val *val) {
@@ -5714,7 +5772,7 @@ yyjson_api_inline bool yyjson_mut_is_ctn(yyjson_mut_val *val) {
/*==============================================================================
* Mutable JSON Value Content API (Implementation)
* MARK: - Mutable JSON Value Content API (Implementation)
*============================================================================*/
yyjson_api_inline yyjson_type yyjson_mut_get_type(yyjson_mut_val *val) {
@@ -5893,7 +5951,7 @@ yyjson_api_inline bool yyjson_mut_set_obj(yyjson_mut_val *val) {
/*==============================================================================
* Mutable JSON Value Creation API (Implementation)
* MARK: - Mutable JSON Value Creation API (Implementation)
*============================================================================*/
#define yyjson_mut_val_one(func) \
@@ -6034,7 +6092,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_strncpy(yyjson_mut_doc *doc,
/*==============================================================================
* Mutable JSON Array API (Implementation)
* MARK: - Mutable JSON Array API (Implementation)
*============================================================================*/
yyjson_api_inline size_t yyjson_mut_arr_size(yyjson_mut_val *arr) {
@@ -6070,7 +6128,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_arr_get_last(
/*==============================================================================
* Mutable JSON Array Iterator API (Implementation)
* MARK: - Mutable JSON Array Iterator API (Implementation)
*============================================================================*/
yyjson_api_inline bool yyjson_mut_arr_iter_init(yyjson_mut_val *arr,
@@ -6130,7 +6188,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_arr_iter_remove(
/*==============================================================================
* Mutable JSON Array Creation API (Implementation)
* MARK: - Mutable JSON Array Creation API (Implementation)
*============================================================================*/
yyjson_api_inline yyjson_mut_val *yyjson_mut_arr(yyjson_mut_doc *doc) {
@@ -6310,7 +6368,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_arr_with_strncpy(
/*==============================================================================
* Mutable JSON Array Modification API (Implementation)
* MARK: - Mutable JSON Array Modification API (Implementation)
*============================================================================*/
yyjson_api_inline bool yyjson_mut_arr_insert(yyjson_mut_val *arr,
@@ -6520,7 +6578,7 @@ yyjson_api_inline bool yyjson_mut_arr_rotate(yyjson_mut_val *arr,
/*==============================================================================
* Mutable JSON Array Modification Convenience API (Implementation)
* MARK: - Mutable JSON Array Modification Convenience API (Implementation)
*============================================================================*/
yyjson_api_inline bool yyjson_mut_arr_add_val(yyjson_mut_val *arr,
@@ -6686,7 +6744,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_arr_add_obj(yyjson_mut_doc *doc,
/*==============================================================================
* Mutable JSON Object API (Implementation)
* MARK: - Mutable JSON Object API (Implementation)
*============================================================================*/
yyjson_api_inline size_t yyjson_mut_obj_size(yyjson_mut_val *obj) {
@@ -6715,7 +6773,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_obj_getn(yyjson_mut_val *obj,
/*==============================================================================
* Mutable JSON Object Iterator API (Implementation)
* MARK: - Mutable JSON Object Iterator API (Implementation)
*============================================================================*/
yyjson_api_inline bool yyjson_mut_obj_iter_init(yyjson_mut_val *obj,
@@ -6806,7 +6864,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_obj_iter_getn(
/*==============================================================================
* Mutable JSON Object Creation API (Implementation)
* MARK: - Mutable JSON Object Creation API (Implementation)
*============================================================================*/
yyjson_api_inline yyjson_mut_val *yyjson_mut_obj(yyjson_mut_doc *doc) {
@@ -6886,7 +6944,7 @@ yyjson_api_inline yyjson_mut_val *yyjson_mut_obj_with_kv(yyjson_mut_doc *doc,
/*==============================================================================
* Mutable JSON Object Modification API (Implementation)
* MARK: - Mutable JSON Object Modification API (Implementation)
*============================================================================*/
yyjson_api_inline void unsafe_yyjson_mut_obj_add(yyjson_mut_val *obj,
@@ -7079,7 +7137,7 @@ yyjson_api_inline bool yyjson_mut_obj_rotate(yyjson_mut_val *obj,
/*==============================================================================
* Mutable JSON Object Modification Convenience API (Implementation)
* MARK: - Mutable JSON Object Modification Convenience API (Implementation)
*============================================================================*/
#define yyjson_mut_obj_add_func(func) \
@@ -7306,7 +7364,7 @@ yyjson_api_inline bool yyjson_mut_obj_rename_keyn(yyjson_mut_doc *doc,
#if !defined(YYJSON_DISABLE_UTILS) || !YYJSON_DISABLE_UTILS
/*==============================================================================
* JSON Pointer API (Implementation)
* MARK: - JSON Pointer API (Implementation)
*============================================================================*/
#define yyjson_ptr_set_err(_code, _msg) do { \
@@ -7965,7 +8023,7 @@ yyjson_api_inline bool yyjson_ptr_ctx_remove(yyjson_ptr_ctx *ctx) {
/*==============================================================================
* JSON Value at Pointer API (Implementation)
* MARK: - JSON Value at Pointer API (Implementation)
*============================================================================*/
/**
@@ -8068,7 +8126,7 @@ yyjson_api_inline bool yyjson_ptr_get_str(
/*==============================================================================
* Deprecated
* MARK: - Deprecated
*============================================================================*/
/** @deprecated renamed to `yyjson_doc_ptr_get` */
@@ -8152,7 +8210,7 @@ yyjson_api_inline yyjson_mut_val *unsafe_yyjson_mut_get_pointer(
/*==============================================================================
* Compiler Hint End
* MARK: - Compiler Hint End
*============================================================================*/
#if defined(__clang__)
+59
View File
@@ -10,6 +10,65 @@
#include <ctype.h>
#include <inttypes.h>
bool ffParseModuleOptions(const char* key, const char* value)
{
if (!ffStrStartsWith(key, "--") || !ffCharIsEnglishAlphabet(key[2])) return false;
if (value && !*value) value = NULL;
for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(key[2]) - 'A']; *modules; ++modules)
{
FFModuleBaseInfo* baseInfo = *modules;
const char* subKey = ffOptionTestPrefix(key, baseInfo->name);
if (subKey != NULL)
{
if (subKey[0] == '\0' || subKey[0] == '-') // Key is exactly the module name or has a leading '-'
{
fprintf(stderr, "Error: unknown module key %s\n", key);
exit(477);
}
FF_STRBUF_AUTO_DESTROY moduleName = ffStrbufCreateS(baseInfo->name);
ffStrbufLowerCase(&moduleName);
FF_STRBUF_AUTO_DESTROY jsonKey = ffStrbufCreate();
bool flag = false;
for (const char* p = subKey; *p; ++p)
{
if (*p == '-')
{
if (flag)
{
fprintf(stderr, "Error: invalid double `-` in module key %s\n", key);
exit(477);
}
flag = true;
}
else
{
if (!isalpha((unsigned char)*p) && !isdigit((unsigned char)*p))
{
fprintf(stderr, "Error: invalid character `%c` in module key %s\n", *p, key);
exit(477);
}
if (flag)
{
flag = false;
ffStrbufAppendC(&jsonKey, (char) toupper((unsigned char) *p));
}
else
ffStrbufAppendC(&jsonKey, *p);
}
}
fprintf(stderr, "Error: Unsupported module option: %s\n", key);
fputs(" Support of module options has been removed. Please add the flag to the JSON config instead.\n", stderr);
fprintf(stderr, " Example (demonstration only): `{ \"modules\": [ { \"type\": \"%s\", \"%s\": %s%s%s } ] }`\n", moduleName.chars, jsonKey.chars, value ? "\"" : "", value ? value : "true", value ? "\"" : "");
fputs(" See <https://github.com/fastfetch-cli/fastfetch/wiki/Configuration> for more information.\n", stderr);
exit(477);
}
}
return false;
}
void ffPrepareCommandOption(FFdata* data)
{
//If we don't have a custom structure, use the default one
+1
View File
@@ -12,3 +12,4 @@ typedef struct FFdata
void ffPrepareCommandOption(FFdata* data);
void ffPrintCommandOption(FFdata* data, yyjson_mut_doc* jsonDoc);
void ffMigrateCommandOptionToJsonc(FFdata* data, yyjson_mut_doc* jsonDoc);
bool ffParseModuleOptions(const char* key, const char* value);
+56 -3
View File
@@ -162,14 +162,67 @@ bool ffDBusGetUint(FFDBusData* dbus, DBusMessageIter* iter, uint32_t* result)
return ffDBusGetUint(dbus, &subIter, result);
}
DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* method, const char* arg)
bool ffDBusGetInt(FFDBusData* dbus, DBusMessageIter* iter, int32_t* result)
{
int argType = dbus->lib->ffdbus_message_iter_get_arg_type(iter);
if(argType == DBUS_TYPE_INT16)
{
int16_t value = 0;
dbus->lib->ffdbus_message_iter_get_basic(iter, &value);
*result = value;
return true;
}
if(argType == DBUS_TYPE_INT32)
{
dbus->lib->ffdbus_message_iter_get_basic(iter, result);
return true;
}
if(argType == DBUS_TYPE_BYTE)
{
uint8_t value = 0;
dbus->lib->ffdbus_message_iter_get_basic(iter, &value);
*result = value;
return true;
}
if(argType == DBUS_TYPE_UINT16)
{
uint16_t value = 0;
dbus->lib->ffdbus_message_iter_get_basic(iter, &value);
*result = (int16_t) value;
return true;
}
if(argType == DBUS_TYPE_UINT32)
{
dbus->lib->ffdbus_message_iter_get_basic(iter, result);
return true;
}
if(argType != DBUS_TYPE_VARIANT)
return false;
DBusMessageIter subIter;
dbus->lib->ffdbus_message_iter_recurse(iter, &subIter);
return ffDBusGetInt(dbus, &subIter, result);
}
DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* method, const char* arg1, const char* arg2)
{
DBusMessage* message = dbus->lib->ffdbus_message_new_method_call(busName, objectPath, interface, method);
if(message == NULL)
return NULL;
if (arg)
dbus->lib->ffdbus_message_append_args(message, DBUS_TYPE_STRING, &arg, DBUS_TYPE_INVALID);
if (arg1)
{
if (arg2)
dbus->lib->ffdbus_message_append_args(message, DBUS_TYPE_STRING, &arg1, DBUS_TYPE_STRING, &arg2, DBUS_TYPE_INVALID);
else
dbus->lib->ffdbus_message_append_args(message, DBUS_TYPE_STRING, &arg1, DBUS_TYPE_INVALID);
}
DBusMessage* reply = dbus->lib->ffdbus_connection_send_with_reply_and_block(dbus->connection, message, instance.config.general.processingTimeout, NULL);
+3 -2
View File
@@ -31,14 +31,15 @@ const char* ffDBusLoadData(DBusBusType busType, FFDBusData* data); //Returns an
bool ffDBusGetString(FFDBusData* dbus, DBusMessageIter* iter, FFstrbuf* result);
bool ffDBusGetBool(FFDBusData* dbus, DBusMessageIter* iter, bool* result);
bool ffDBusGetUint(FFDBusData* dbus, DBusMessageIter* iter, uint32_t* result);
DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* method, const char* arg);
DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* method, const char* arg1, const char* arg2);
DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property);
bool ffDBusGetPropertyString(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, FFstrbuf* result);
bool ffDBusGetInt(FFDBusData* dbus, DBusMessageIter* iter, int32_t* result);
bool ffDBusGetPropertyUint(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, uint32_t* result);
static inline DBusMessage* ffDBusGetAllProperties(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface)
{
return ffDBusGetMethodReply(dbus, busName, objectPath, "org.freedesktop.DBus.Properties", "GetAll", interface);
return ffDBusGetMethodReply(dbus, busName, objectPath, "org.freedesktop.DBus.Properties", "GetAll", interface, NULL);
}
#endif // FF_HAVE_DBUS
+27 -32
View File
@@ -4,11 +4,13 @@ void ffDurationAppendNum(uint64_t totalSeconds, FFstrbuf* result)
{
const FFOptionsDisplay* options = &instance.config.display;
const char* space = instance.config.display.durationSpaceBeforeUnit != FF_SPACE_BEFORE_UNIT_NEVER ? " " : "";
bool spaceBeforeUnit = options->durationSpaceBeforeUnit != FF_SPACE_BEFORE_UNIT_NEVER;
if(totalSeconds < 60)
if (totalSeconds < 60)
{
ffStrbufAppendF(result, options->durationAbbreviation ? "%u%ssec" : "%u%ssecond", (unsigned) totalSeconds, space);
ffStrbufAppendUInt(result, totalSeconds);
if (spaceBeforeUnit) ffStrbufAppendC(result, ' ');
ffStrbufAppendS(result, options->durationAbbreviation ? "sec" : "second");
if (totalSeconds != 1)
ffStrbufAppendC(result, 's');
return;
@@ -25,63 +27,56 @@ void ffDurationAppendNum(uint64_t totalSeconds, FFstrbuf* result)
totalSeconds /= 24;
uint32_t days = (uint32_t) totalSeconds;
if(days > 0)
if (days > 0)
{
if(options->durationAbbreviation)
ffStrbufAppendUInt(result, days);
if (spaceBeforeUnit) ffStrbufAppendC(result, ' ');
if (options->durationAbbreviation)
{
ffStrbufAppendF(result, "%u%sd", days, space);
ffStrbufAppendC(result, 'd');
if(hours > 0 || minutes > 0)
if (hours > 0 || minutes > 0)
ffStrbufAppendC(result, ' ');
}
else
{
ffStrbufAppendF(result, "%u%sday", days, space);
ffStrbufAppendS(result, days == 1 ? "day" : "days");
if(days > 1)
ffStrbufAppendC(result, 's');
if(days >= 100)
if (days >= 100)
ffStrbufAppendS(result, "(!)");
if(hours > 0 || minutes > 0)
if (hours > 0 || minutes > 0)
ffStrbufAppendS(result, ", ");
}
}
if(hours > 0)
if (hours > 0)
{
if(options->durationAbbreviation)
ffStrbufAppendUInt(result, hours);
if (spaceBeforeUnit) ffStrbufAppendC(result, ' ');
if (options->durationAbbreviation)
{
ffStrbufAppendF(result, "%u%sh", hours, space);
ffStrbufAppendC(result, 'h');
if (minutes > 0)
ffStrbufAppendC(result, ' ');
}
else
{
ffStrbufAppendF(result, "%u%shour", hours, space);
ffStrbufAppendS(result, hours == 1 ? "hour" : "hours");
if(hours > 1)
ffStrbufAppendC(result, 's');
if(minutes > 0)
if (minutes > 0)
ffStrbufAppendS(result, ", ");
}
}
if(minutes > 0)
if (minutes > 0)
{
if(options->durationAbbreviation)
{
ffStrbufAppendF(result, "%u%sm", minutes, space);
}
ffStrbufAppendUInt(result, minutes);
if (spaceBeforeUnit) ffStrbufAppendC(result, ' ');
if (options->durationAbbreviation)
ffStrbufAppendC(result, 'm');
else
{
ffStrbufAppendF(result, "%u%smin", minutes, space);
if(minutes > 1)
ffStrbufAppendC(result, 's');
}
ffStrbufAppendS(result, minutes == 1 ? "min" : "mins");
}
}
+8 -14
View File
@@ -11,37 +11,31 @@ void ffFormatAppendFormatArg(FFstrbuf* buffer, const FFformatarg* formatarg)
switch(formatarg->type)
{
case FF_FORMAT_ARG_TYPE_INT:
ffStrbufAppendF(buffer, "%" PRIi32, *(int32_t*)formatarg->value);
ffStrbufAppendSInt(buffer, *(int32_t*)formatarg->value);
break;
case FF_FORMAT_ARG_TYPE_UINT:
ffStrbufAppendF(buffer, "%" PRIu32, *(uint32_t*)formatarg->value);
ffStrbufAppendUInt(buffer, *(uint32_t*)formatarg->value);
break;
case FF_FORMAT_ARG_TYPE_UINT64:
ffStrbufAppendF(buffer, "%" PRIu64, *(uint64_t*)formatarg->value);
ffStrbufAppendUInt(buffer, *(uint64_t*)formatarg->value);
break;
case FF_FORMAT_ARG_TYPE_UINT16:
ffStrbufAppendF(buffer, "%" PRIu16, *(uint16_t*)formatarg->value);
ffStrbufAppendUInt(buffer, *(uint16_t*)formatarg->value);
break;
case FF_FORMAT_ARG_TYPE_UINT8:
ffStrbufAppendF(buffer, "%" PRIu8, *(uint8_t*)formatarg->value);
ffStrbufAppendUInt(buffer, *(uint8_t*)formatarg->value);
break;
case FF_FORMAT_ARG_TYPE_STRING:
ffStrbufAppendS(buffer, (const char*)formatarg->value);
break;
case FF_FORMAT_ARG_TYPE_STRBUF:
ffStrbufAppend(buffer, (FFstrbuf*)formatarg->value);
ffStrbufAppend(buffer, (const FFstrbuf*)formatarg->value);
break;
case FF_FORMAT_ARG_TYPE_FLOAT:
if (instance.config.display.fractionNdigits >= 0)
ffStrbufAppendF(buffer, "%.*f", instance.config.display.fractionNdigits, *(float*)formatarg->value);
else
ffStrbufAppendF(buffer, "%g", *(float*)formatarg->value);
ffStrbufAppendDouble(buffer, *(float*)formatarg->value, instance.config.display.fractionNdigits, instance.config.display.fractionTrailingZeros != FF_FRACTION_TRAILING_ZEROS_TYPE_NEVER);
break;
case FF_FORMAT_ARG_TYPE_DOUBLE:
if (instance.config.display.fractionNdigits >= 0)
ffStrbufAppendF(buffer, "%.*f", instance.config.display.fractionNdigits, *(double*)formatarg->value);
else
ffStrbufAppendF(buffer, "%g", *(double*)formatarg->value);
ffStrbufAppendDouble(buffer, *(double*)formatarg->value, instance.config.display.fractionNdigits, instance.config.display.fractionTrailingZeros != FF_FRACTION_TRAILING_ZEROS_TYPE_NEVER);
break;
case FF_FORMAT_ARG_TYPE_BOOL:
ffStrbufAppendS(buffer, *(bool*)formatarg->value ? "true" : "false");
+11 -3
View File
@@ -6,12 +6,20 @@ bool ffFreqAppendNum(uint32_t mhz, FFstrbuf* result)
return false;
const FFOptionsDisplay* options = &instance.config.display;
const char* space = options->freqSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_NEVER ? "" : " ";
bool spaceBeforeUnit = options->freqSpaceBeforeUnit != FF_SPACE_BEFORE_UNIT_NEVER;
int8_t ndigits = options->freqNdigits;
if (ndigits >= 0)
ffStrbufAppendF(result, "%.*f%sGHz", ndigits, mhz / 1000., space);
{
ffStrbufAppendDouble(result, mhz / 1000., ndigits, true);
if (spaceBeforeUnit) ffStrbufAppendC(result, ' ');
ffStrbufAppendS(result, "GHz");
}
else
ffStrbufAppendF(result, "%u%sMHz", (unsigned) mhz, space);
{
ffStrbufAppendUInt(result, mhz);
if (spaceBeforeUnit) ffStrbufAppendC(result, ' ');
ffStrbufAppendS(result, "MHz");
}
return true;
}
-3
View File
@@ -208,9 +208,6 @@ void ffListFeatures(void)
#if FF_HAVE_ZLIB
"zlib\n"
#endif
#if FF_HAVE_XFCONF
"xfconf\n"
#endif
#if FF_HAVE_SQLITE3
"sqlite3\n"
#endif
+41 -16
View File
@@ -101,16 +101,6 @@ const char* ffJsonConfigParseEnum(yyjson_val* val, int* result, FFKeyValuePair p
return "Invalid enum value type; must be a string or integer";
}
static inline void genJsonResult(FFModuleBaseInfo* baseInfo, void* options, yyjson_mut_doc* doc)
{
yyjson_mut_val* module = yyjson_mut_arr_add_obj(doc, doc->root);
yyjson_mut_obj_add_str(doc, module, "type", baseInfo->name);
if (baseInfo->generateJsonResult)
baseInfo->generateJsonResult(options, doc, module);
else
yyjson_mut_obj_add_str(doc, module, "error", "Unsupported for JSON format");
}
static bool parseModuleJsonObject(const char* type, yyjson_val* jsonVal, yyjson_mut_doc* jsonDoc)
{
if(!ffCharIsEnglishAlphabet(type[0])) return false;
@@ -123,14 +113,39 @@ static bool parseModuleJsonObject(const char* type, yyjson_val* jsonVal, yyjson_
uint8_t optionBuf[FF_OPTION_MAX_SIZE];
baseInfo->initOptions(optionBuf);
if (jsonVal) baseInfo->parseJsonObject(optionBuf, jsonVal);
if (__builtin_expect(jsonDoc != NULL, false))
genJsonResult(baseInfo, optionBuf, jsonDoc);
bool succeeded;
if (jsonDoc)
{
yyjson_mut_val* module = yyjson_mut_arr_add_obj(jsonDoc, jsonDoc->root);
yyjson_mut_obj_add_str(jsonDoc, module, "type", baseInfo->name);
if (baseInfo->generateJsonResult)
succeeded = baseInfo->generateJsonResult(optionBuf, jsonDoc, module);
else
{
yyjson_mut_obj_add_str(jsonDoc, module, "error", "Unsupported for JSON format");
succeeded = false;
}
}
else
baseInfo->printModule(optionBuf);
succeeded = baseInfo->printModule(optionBuf);
baseInfo->destroyOptions(optionBuf);
return true;
return succeeded;
}
}
if (jsonDoc)
{
yyjson_mut_val* module = yyjson_mut_arr_add_obj(jsonDoc, jsonDoc->root);
yyjson_mut_obj_add_strcpy(jsonDoc, module, "type", type);
yyjson_mut_obj_add_str(jsonDoc, module, "error", "Unknown module type");
}
else
{
FFModuleArgs moduleArgs;
ffOptionInitModuleArg(&moduleArgs, "");
ffPrintError(type, 0, &moduleArgs, FF_PRINT_TYPE_DEFAULT, "Unknown module type");
ffOptionDestroyModuleArg(&moduleArgs);
}
return false;
}
@@ -217,6 +232,7 @@ static const char* printJsonConfig(bool prepare, yyjson_mut_doc* jsonDoc)
if (!modules) return NULL;
if (!yyjson_is_arr(modules)) return "Property 'modules' must be an array of strings or objects";
bool succeeded = true;
int32_t thres = instance.config.display.stat;
yyjson_val* item;
size_t idx, max;
@@ -253,6 +269,15 @@ static const char* printJsonConfig(bool prepare, yyjson_mut_doc* jsonDoc)
arch = yyjson_obj_get(conditions, "!arch");
if (arch && matchesJsonArray(ffVersionResult.architecture, arch))
continue;
yyjson_val* previousSucceeded = yyjson_obj_get(conditions, "succeeded");
if (previousSucceeded && !unsafe_yyjson_is_null(previousSucceeded))
{
if (!unsafe_yyjson_is_bool(previousSucceeded))
return "Property 'succeeded' in 'condition' must be a boolean";
if (succeeded != unsafe_yyjson_get_bool(previousSucceeded))
continue;
}
}
type = yyjson_get_str(yyjson_obj_get(module, "type"));
@@ -265,8 +290,8 @@ static const char* printJsonConfig(bool prepare, yyjson_mut_doc* jsonDoc)
if(prepare)
prepareModuleJsonObject(type, module);
else if(!parseModuleJsonObject(type, module, jsonDoc))
return "Unknown module type";
else
succeeded = parseModuleJsonObject(type, module, jsonDoc);
if(!prepare && thres >= 0)
{
+1 -1
View File
@@ -52,7 +52,7 @@ static void* libraryLoad(const char* path, int maxVersion)
for(int i = maxVersion; i >= 0; --i)
{
uint32_t originalLength = pathbuf.length;
ffStrbufAppendF(&pathbuf, "%i", i);
ffStrbufAppendSInt(&pathbuf, i);
result = dlopen(pathbuf.chars, FF_DLOPEN_FLAGS);
if(result != NULL)
+35
View File
@@ -0,0 +1,35 @@
#include "netif.h"
#include "common/io/io.h"
#include <net/if.h>
#include <stdio.h>
#define FF_STR_INDIR(x) #x
#define FF_STR(x) FF_STR_INDIR(x)
bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result)
{
FILE* FF_AUTO_CLOSE_FILE netRoute = fopen("/proc/route", "r");
if (!netRoute) return false;
// skip first line
FF_UNUSED(fscanf(netRoute, "%*[^\n]\n"));
unsigned long long destination; //, gateway, flags, refCount, use, metric, mask, mtu, ...
while (fscanf(netRoute, "%" FF_STR(IF_NAMESIZE) "s%llx%*[^\n]", result->ifName, &destination) == 2)
{
if (destination != 0) continue;
result->ifIndex = if_nametoindex(result->ifName);
// TODO: Get the preferred source address
return true;
}
result->ifName[0] = '0';
return false;
}
bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result)
{
// TODO: AF_INET6
FF_UNUSED(result);
return false;
}
+254 -164
View File
@@ -1,34 +1,41 @@
#include "netif.h"
#include "common/io/io.h"
#include "util/mallocHelper.h"
#include "util/debug.h"
#include <arpa/inet.h>
#include <linux/rtnetlink.h>
#include <net/if.h>
#define FF_STR_INDIR(x) #x
#define FF_STR(x) FF_STR_INDIR(x)
bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result)
{
FF_DEBUG("Starting IPv4 default route detection");
FF_AUTO_CLOSE_FD int sock_fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
if (sock_fd < 0)
{
FF_DEBUG("Failed to create netlink socket: %s", strerror(errno));
return false;
}
FF_DEBUG("Created netlink socket: fd=%d", sock_fd);
unsigned pid = (unsigned) getpid();
FF_DEBUG("Process PID: %u", pid);
// Bind socket
struct sockaddr_nl addr = {
.nl_family = AF_NETLINK,
.nl_pid = pid,
.nl_pid = 0, // Let kernel choose PID
.nl_groups = 0, // No multicast groups
};
if (bind(sock_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
FF_DEBUG("Failed to bind socket: %s", strerror(errno));
return false;
}
FF_DEBUG("Successfully bound socket");
struct {
struct __attribute__((__packed__)) {
struct nlmsghdr nlh;
struct rtmsg rtm;
struct rtattr rta;
@@ -72,128 +79,173 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result)
(struct sockaddr*)&dest_addr, sizeof(dest_addr));
if (sent != sizeof(req)) {
FF_DEBUG("Failed to send netlink request: sent=%zd, expected=%zu", sent, sizeof(req));
return false;
}
FF_DEBUG("Sent netlink request: %zd bytes", sent);
struct sockaddr_nl src_addr = {};
socklen_t src_addr_len = sizeof(src_addr);
struct iovec iov = {};
struct msghdr msg = {
.msg_name = &src_addr,
.msg_namelen = sizeof(src_addr),
.msg_iov = &iov,
.msg_iovlen = 1,
};
ssize_t peek_size = recvmsg(sock_fd, &msg, MSG_PEEK | MSG_TRUNC);
if (peek_size < 0) {
return false;
}
FF_AUTO_FREE uint8_t* buffer = malloc((size_t)peek_size);
ssize_t received = recvfrom(sock_fd, buffer, (size_t)peek_size, 0,
(struct sockaddr*)&src_addr, &src_addr_len);
if (received != peek_size) {
return false;
}
struct {
uint32_t metric;
uint32_t ifindex;
uint32_t prefsrc;
} entry;
uint8_t buffer[1024 * 16]; // 16 KB buffer should be sufficient
uint32_t minMetric = UINT32_MAX;
int routeCount = 0;
for (const struct nlmsghdr* nlh = (struct nlmsghdr*)buffer;
NLMSG_OK(nlh, received);
nlh = NLMSG_NEXT(nlh, received)) {
if (nlh->nlmsg_seq != 1 || nlh->nlmsg_pid != pid)
continue;
if (nlh->nlmsg_type == NLMSG_DONE)
while (true)
{
ssize_t received = recvfrom(sock_fd, buffer, sizeof(buffer), 0,
(struct sockaddr*)&src_addr, &src_addr_len);
if (received < 0) {
FF_DEBUG("Failed to receive netlink response: %s", strerror(errno));
return false;
}
if (received >= (ssize_t)sizeof(buffer)) {
FF_DEBUG("Received truncated message: received %zd, bufsize %zu", received, sizeof(buffer));
return false;
}
FF_DEBUG("Received netlink response: %zd bytes", received);
if (received == 0) {
FF_DEBUG("Received zero-length netlink response, ending processing");
break;
}
if (nlh->nlmsg_type != RTM_NEWROUTE)
continue;
struct {
uint32_t metric;
uint32_t ifindex;
uint32_t prefsrc;
} entry;
struct rtmsg* rtm = (struct rtmsg*)NLMSG_DATA(nlh);
if (rtm->rtm_family != AF_INET)
continue;
if (rtm->rtm_dst_len != 0)
continue;
entry = (__typeof__(entry)) { .metric = UINT32_MAX };
// Parse route attributes
size_t rtm_len = RTM_PAYLOAD(nlh);
for (struct rtattr* rta = RTM_RTA(rtm);
RTA_OK(rta, rtm_len);
rta = RTA_NEXT(rta, rtm_len))
for (const struct nlmsghdr* nlh = (struct nlmsghdr*)buffer;
NLMSG_OK(nlh, received);
nlh = NLMSG_NEXT(nlh, received))
{
if (RTA_PAYLOAD(rta) < sizeof(uint32_t))
continue; // Skip invalid attributes
if (nlh->nlmsg_seq != 1 || nlh->nlmsg_pid != pid)
continue;
if (nlh->nlmsg_type == NLMSG_DONE)
{
FF_DEBUG("Received NLMSG_DONE, processed %d routes", routeCount);
goto exit;
}
uint32_t rta_data = *(uint32_t*) RTA_DATA(rta);
switch (rta->rta_type) {
case RTA_DST:
if (rta_data != 0) goto next;
break;
case RTA_OIF:
entry.ifindex = rta_data;
break;
case RTA_GATEWAY:
if (rta_data == 0) goto next;
break;
case RTA_PRIORITY:
if (rta_data >= minMetric) goto next;
entry.metric = rta_data;
break;
case RTA_PREFSRC:
entry.prefsrc = rta_data;
break;
if (nlh->nlmsg_type == NLMSG_ERROR) {
FF_DEBUG("Netlink reports error: %s", strerror(-((struct nlmsgerr*)NLMSG_DATA(nlh))->error));
continue;
}
if (nlh->nlmsg_type != RTM_NEWROUTE) {
FF_DEBUG("Skipping non-route message: type=%d", nlh->nlmsg_type);
continue;
}
routeCount++;
struct rtmsg* rtm = (struct rtmsg*)NLMSG_DATA(nlh);
if (rtm->rtm_family != AF_INET) {
FF_DEBUG("Skipping non-IPv4 route #%d (family=%d)", routeCount, rtm->rtm_family);
continue;
}
if (rtm->rtm_dst_len != 0) {
FF_DEBUG("Skipping non-default route #%d (dst_len=%d)", routeCount, rtm->rtm_dst_len);
continue;
}
FF_DEBUG("Processing IPv4 default route candidate #%d", routeCount);
entry = (__typeof__(entry)) { }; // Default to zero metric (no RTA_PRIORITY found)
// Parse route attributes
size_t rtm_len = RTM_PAYLOAD(nlh);
for (struct rtattr* rta = RTM_RTA(rtm);
RTA_OK(rta, rtm_len);
rta = RTA_NEXT(rta, rtm_len))
{
if (RTA_PAYLOAD(rta) < sizeof(uint32_t))
continue; // Skip invalid attributes
uint32_t rta_data = *(uint32_t*) RTA_DATA(rta);
switch (rta->rta_type) {
case RTA_DST:
FF_DEBUG("Unexpected RTA_DST: %s (len=%u)", inet_ntoa((struct in_addr) { .s_addr = rta_data }), rtm->rtm_dst_len);
goto next;
case RTA_OIF:
entry.ifindex = rta_data;
FF_DEBUG("Found interface index: %u", entry.ifindex);
break;
case RTA_GATEWAY:
FF_DEBUG("Found gateway: %s", inet_ntoa(*(struct in_addr*)&rta_data));
if (rta_data == 0) goto next;
break;
case RTA_PRIORITY:
FF_DEBUG("Found metric: %u", rta_data);
if (rta_data >= minMetric) goto next;
entry.metric = rta_data;
break;
case RTA_PREFSRC:
entry.prefsrc = rta_data;
FF_DEBUG("Found preferred source: %s", inet_ntoa(*(struct in_addr*)&rta_data));
break;
}
}
if (entry.ifindex == 0 || entry.metric >= minMetric)
{
next:
FF_DEBUG("Skipping route: ifindex=%u, metric=%u", entry.ifindex, entry.metric);
continue;
}
minMetric = entry.metric;
result->ifIndex = entry.ifindex;
FF_DEBUG("Updated best route: ifindex=%u, metric=%u, prefsrc=%x", entry.ifindex, entry.metric, entry.prefsrc);
result->preferredSourceAddrV4 = entry.prefsrc;
if (minMetric == 0)
{
FF_DEBUG("Found zero metric route, stopping further processing");
break; // Stop processing if we found a zero metric route
}
}
if (entry.metric >= minMetric)
{
next:
continue;
}
minMetric = entry.metric;
result->ifIndex = entry.ifindex;
result->preferredSourceAddrV4 = entry.prefsrc;
}
exit:
if (minMetric < UINT32_MAX)
{
if_indextoname(result->ifIndex, result->ifName);
FF_DEBUG("Found default IPv4 route: interface=%s, index=%u, metric=%u", result->ifName, result->ifIndex, minMetric);
return true;
}
FF_DEBUG("No IPv4 default route found");
return false;
}
bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result)
{
FF_DEBUG("Starting IPv6 default route detection");
FF_AUTO_CLOSE_FD int sock_fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
if (sock_fd < 0)
{
FF_DEBUG("Failed to create netlink socket: %s", strerror(errno));
return false;
}
FF_DEBUG("Created netlink socket: fd=%d", sock_fd);
unsigned pid = (unsigned) getpid();
FF_DEBUG("Process PID: %u", pid);
// Bind socket
struct sockaddr_nl addr = {
.nl_family = AF_NETLINK,
.nl_pid = pid,
.nl_pid = 0, // Let kernel choose PID
.nl_groups = 0, // No multicast groups
};
if (bind(sock_fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
FF_DEBUG("Failed to bind socket: %s", strerror(errno));
return false;
}
FF_DEBUG("Successfully bound socket");
struct {
struct __attribute__((__packed__)) {
struct nlmsghdr nlh;
struct rtmsg rtm;
struct rtattr rta;
@@ -237,106 +289,144 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result)
(struct sockaddr*)&dest_addr, sizeof(dest_addr));
if (sent != sizeof(req)) {
FF_DEBUG("Failed to send netlink request: sent=%zd, expected=%zu", sent, sizeof(req));
return false;
}
FF_DEBUG("Sent netlink request: %zd bytes", sent);
struct sockaddr_nl src_addr = {};
socklen_t src_addr_len = sizeof(src_addr);
struct iovec iov = {};
struct msghdr msg = {
.msg_name = &src_addr,
.msg_namelen = sizeof(src_addr),
.msg_iov = &iov,
.msg_iovlen = 1,
};
ssize_t peek_size = recvmsg(sock_fd, &msg, MSG_PEEK | MSG_TRUNC);
if (peek_size < 0) {
return false;
}
FF_AUTO_FREE uint8_t* buffer = malloc((size_t)peek_size);
ssize_t received = recvfrom(sock_fd, buffer, (size_t)peek_size, 0,
(struct sockaddr*)&src_addr, &src_addr_len);
if (received != peek_size) {
return false;
}
struct {
uint32_t metric;
uint32_t ifindex;
} entry;
uint8_t buffer[1024 * 16]; // 16 KB buffer should be sufficient
uint32_t minMetric = UINT32_MAX;
int routeCount = 0;
for (const struct nlmsghdr* nlh = (struct nlmsghdr*)buffer;
NLMSG_OK(nlh, received);
nlh = NLMSG_NEXT(nlh, received)) {
if (nlh->nlmsg_seq != 1 || nlh->nlmsg_pid != pid)
continue;
if (nlh->nlmsg_type == NLMSG_DONE)
while (true)
{
ssize_t received = recvfrom(sock_fd, buffer, sizeof(buffer), 0,
(struct sockaddr*)&src_addr, &src_addr_len);
if (received < 0) {
FF_DEBUG("Failed to receive netlink response: %s", strerror(errno));
return false;
}
if (received >= (ssize_t)sizeof(buffer)) {
FF_DEBUG("Received truncated message: received %zd, bufsize %zu", received, sizeof(buffer));
return false;
}
FF_DEBUG("Received netlink response: %zd bytes", received);
if (received == 0) {
FF_DEBUG("Received zero-length netlink response, ending processing");
break;
}
if (nlh->nlmsg_type != RTM_NEWROUTE)
continue;
struct {
uint32_t metric;
uint32_t ifindex;
} entry;
struct rtmsg* rtm = (struct rtmsg*)NLMSG_DATA(nlh);
if (rtm->rtm_family != AF_INET6)
continue;
if (rtm->rtm_dst_len != 0)
continue;
entry = (__typeof__(entry)) { .metric = UINT32_MAX };
// Parse route attributes
size_t rtm_len = RTM_PAYLOAD(nlh);
for (struct rtattr* rta = RTM_RTA(rtm);
RTA_OK(rta, rtm_len);
rta = RTA_NEXT(rta, rtm_len))
for (const struct nlmsghdr* nlh = (struct nlmsghdr*)buffer;
NLMSG_OK(nlh, received);
nlh = NLMSG_NEXT(nlh, received))
{
switch (rta->rta_type) {
case RTA_DST:
if (RTA_PAYLOAD(rta) >= sizeof(struct in6_addr)) {
struct in6_addr* dst = (struct in6_addr*) RTA_DATA(rta);
if (!IN6_IS_ADDR_UNSPECIFIED(dst)) goto next;
}
break;
case RTA_OIF:
if (RTA_PAYLOAD(rta) >= sizeof(uint32_t)) {
entry.ifindex = *(uint32_t*) RTA_DATA(rta);
}
break;
case RTA_GATEWAY:
if (RTA_PAYLOAD(rta) >= sizeof(struct in6_addr)) {
struct in6_addr* gw = (struct in6_addr*) RTA_DATA(rta);
if (IN6_IS_ADDR_UNSPECIFIED(gw)) goto next;
}
break;
case RTA_PRIORITY:
if (RTA_PAYLOAD(rta) >= sizeof(uint32_t)) {
uint32_t metric = *(uint32_t*) RTA_DATA(rta);
if (metric >= minMetric) goto next;
entry.metric = metric;
}
break;
if (nlh->nlmsg_seq != 1 || nlh->nlmsg_pid != pid)
continue;
if (nlh->nlmsg_type == NLMSG_DONE)
{
FF_DEBUG("Received NLMSG_DONE, processed %d routes", routeCount);
goto exit;
}
if (nlh->nlmsg_type == NLMSG_ERROR) {
FF_DEBUG("Netlink reports error: %s", strerror(-((struct nlmsgerr*)NLMSG_DATA(nlh))->error));
continue;
}
if (nlh->nlmsg_type != RTM_NEWROUTE) {
FF_DEBUG("Skipping non-route message: type=%d", nlh->nlmsg_type);
continue;
}
routeCount++;
struct rtmsg* rtm = (struct rtmsg*)NLMSG_DATA(nlh);
if (rtm->rtm_family != AF_INET6) {
FF_DEBUG("Skipping non-IPv6 route #%d (family=%d)", routeCount, rtm->rtm_family);
continue;
}
if (rtm->rtm_dst_len != 0) {
FF_DEBUG("Skipping non-default route #%d (dst_len=%d)", routeCount, rtm->rtm_dst_len);
continue;
}
FF_DEBUG("Processing IPv6 default route candidate #%d", routeCount);
entry = (__typeof__(entry)) { }; // Default to zero metric (no RTA_PRIORITY found)
// Parse route attributes
size_t rtm_len = RTM_PAYLOAD(nlh);
for (struct rtattr* rta = RTM_RTA(rtm);
RTA_OK(rta, rtm_len);
rta = RTA_NEXT(rta, rtm_len))
{
switch (rta->rta_type) {
case RTA_DST:
if (RTA_PAYLOAD(rta) >= sizeof(struct in6_addr)) {
FF_MAYBE_UNUSED char str[INET6_ADDRSTRLEN];
FF_DEBUG("Unexpected RTA_DST: %s", inet_ntop(AF_INET6, RTA_DATA(rta), str, sizeof(str)));
goto next;
}
break;
case RTA_OIF:
if (RTA_PAYLOAD(rta) >= sizeof(uint32_t)) {
entry.ifindex = *(uint32_t*) RTA_DATA(rta);
FF_DEBUG("Found interface index: %u", entry.ifindex);
}
break;
case RTA_GATEWAY:
if (RTA_PAYLOAD(rta) >= sizeof(struct in6_addr)) {
struct in6_addr* gw = (struct in6_addr*) RTA_DATA(rta);
if (IN6_IS_ADDR_UNSPECIFIED(gw)) goto next;
FF_MAYBE_UNUSED char str[INET6_ADDRSTRLEN];
FF_DEBUG("Found gateway: %s", inet_ntop(AF_INET6, gw, str, sizeof(str)));
}
break;
case RTA_PRIORITY:
if (RTA_PAYLOAD(rta) >= sizeof(uint32_t)) {
uint32_t metric = *(uint32_t*) RTA_DATA(rta);
FF_DEBUG("Found metric: %u", metric);
if (metric >= minMetric) goto next;
entry.metric = metric;
}
break;
}
}
if (entry.ifindex == 0 || entry.metric >= minMetric)
{
next:
FF_DEBUG("Skipping route: ifindex=%u, metric=%u", entry.ifindex, entry.metric);
continue;
}
minMetric = entry.metric;
result->ifIndex = entry.ifindex;
FF_DEBUG("Updated best route: ifindex=%u, metric=%u", entry.ifindex, entry.metric);
if (minMetric == 0)
{
FF_DEBUG("Found zero metric route, stopping further processing");
break; // Stop processing if we found a zero metric route
}
}
if (entry.metric >= minMetric)
{
next:
continue;
}
minMetric = entry.metric;
result->ifIndex = entry.ifindex;
}
exit:
if (minMetric < UINT32_MAX)
{
if_indextoname(result->ifIndex, result->ifName);
FF_DEBUG("Found default IPv6 route: interface=%s, index=%u, metric=%u", result->ifName, result->ifIndex, minMetric);
return true;
}
FF_DEBUG("No IPv6 default route found");
return false;
}
+3 -3
View File
@@ -22,7 +22,7 @@ static const char* tryNonThreadingFastPath(FFNetworkingState* state)
if (!state->tfo)
{
#ifdef __linux__
#if __linux__ || __GNU__
// Linux doesn't support sendto() on unconnected sockets
FF_DEBUG("TCP Fast Open disabled, skipping");
return "TCP Fast Open disabled";
@@ -34,7 +34,7 @@ static const char* tryNonThreadingFastPath(FFNetworkingState* state)
#ifndef __APPLE__ // On macOS, TCP_FASTOPEN doesn't seem to be needed
// Set TCP Fast Open
#ifdef __linux__
#if __linux__ || __GNU__
int flag = 5; // the queue length of pending packets
#else
int flag = 1; // enable TCP Fast Open
@@ -50,7 +50,7 @@ static const char* tryNonThreadingFastPath(FFNetworkingState* state)
FF_DEBUG("Failed to set TCP_FASTOPEN option: %s", strerror(errno));
return "setsockopt(TCP_FASTOPEN) failed";
} else {
#ifdef __linux__
#if __linux__ || __GNU__
FF_DEBUG("Successfully set TCP_FASTOPEN option, queue length: %d", flag);
#elif defined(__APPLE__)
FF_DEBUG("Successfully set TCP_FASTOPEN_FORCE_ENABLE option");
+3 -2
View File
@@ -29,11 +29,12 @@ typedef struct FFModuleBaseInfo
// This is UB, because `void*` is not compatible with `FF*Options*`.
// However we can't do it better unless we move to C++, so that `option` becomes a `this` pointer
// https://stackoverflow.com/questions/559581/casting-a-function-pointer-to-another-type
void (*initOptions)(void* options);
void (*destroyOptions)(void* options);
void (*parseJsonObject)(void* options, struct yyjson_val *module);
void (*printModule)(void* options);
void (*generateJsonResult)(void* options, struct yyjson_mut_doc* doc, struct yyjson_mut_val* module);
bool (*printModule)(void* options); // true on success
bool (*generateJsonResult)(void* options, struct yyjson_mut_doc* doc, struct yyjson_mut_val* module); // true on success
void (*generateJsonConfig)(void* options, struct yyjson_mut_doc* doc, struct yyjson_mut_val* obj);
FFModuleFormatArgList formatArgs;
} FFModuleBaseInfo;
+11 -3
View File
@@ -50,13 +50,21 @@ int8_t ffVersionCompare(const FFVersion* version1, const FFVersion* version2)
void ffVersionToPretty(const FFVersion* version, FFstrbuf* pretty)
{
if(version->major > 0 || version->minor > 0 || version->patch > 0)
ffStrbufAppendF(pretty, "%u", version->major);
{
ffStrbufAppendUInt(pretty, version->major);
}
if(version->minor > 0 || version->patch > 0)
ffStrbufAppendF(pretty, ".%u", version->minor);
{
ffStrbufAppendC(pretty, '.');
ffStrbufAppendUInt(pretty, version->minor);
}
if(version->patch > 0)
ffStrbufAppendF(pretty, ".%u", version->patch);
{
ffStrbufAppendC(pretty, '.');
ffStrbufAppendUInt(pretty, version->patch);
}
}
void ffParseGTK(FFstrbuf* buffer, const FFstrbuf* gtk2, const FFstrbuf* gtk3, const FFstrbuf* gtk4)
+31 -33
View File
@@ -97,40 +97,38 @@ void ffPercentAppendBar(FFstrbuf* buffer, double percent, FFPercentageModuleConf
bool autoColorElapsed = ffStrbufIgnCaseEqualS(&options->barColorElapsed, "auto");
bool monochrome = (percentType & FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT) || !autoColorElapsed;
if (!options->pipe && options->barColorElapsed.length > 0 && monochrome)
{
const char* color = NULL;
if (!autoColorElapsed)
color = options->barColorElapsed.chars;
else if (green <= yellow)
{
if (percent < green) color = colorGreen;
else if (percent < yellow) color = colorYellow;
else color = colorRed;
}
else
{
if (percent < yellow) color = colorRed;
else if (percent < green) color = colorYellow;
else color = colorGreen;
}
ffStrbufAppendF(buffer, "\e[%sm", color);
}
for (uint8_t i = 0; i < blocksPercent; ++i)
{
if(!options->pipe && options->barColorElapsed.length > 0)
if (!options->pipe && options->barColorElapsed.length > 0 && !monochrome)
{
if ((percentType & FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT) || !autoColorElapsed)
{
const char* color = NULL;
if (!autoColorElapsed)
color = options->barColorElapsed.chars;
else if (green <= yellow)
{
if (percent < green) color = colorGreen;
else if (percent < yellow) color = colorYellow;
else color = colorRed;
}
else
{
if (percent < yellow) color = colorRed;
else if (percent < green) color = colorYellow;
else color = colorGreen;
}
ffStrbufAppendF(buffer, "\e[%sm", color);
}
else
{
uint32_t section1Begin = (uint32_t) ((green <= yellow ? green : yellow) / 100.0 * options->barWidth + 0.5);
uint32_t section2Begin = (uint32_t) ((green > yellow ? green : yellow) / 100.0 * options->barWidth + 0.5);
if (i == section2Begin)
ffStrbufAppendF(buffer, "\e[%sm", (green > yellow ? colorGreen : colorRed));
else if (i == section1Begin)
ffStrbufAppendF(buffer, "\e[%sm", colorYellow);
else if (i == 0)
ffStrbufAppendF(buffer, "\e[%sm", (green <= yellow ? colorGreen : colorRed));
}
uint32_t section1Begin = (uint32_t) ((green <= yellow ? green : yellow) / 100.0 * options->barWidth + 0.5);
uint32_t section2Begin = (uint32_t) ((green > yellow ? green : yellow) / 100.0 * options->barWidth + 0.5);
if (i == section2Begin)
ffStrbufAppendF(buffer, "\e[%sm", (green > yellow ? colorGreen : colorRed));
else if (i == section1Begin)
ffStrbufAppendF(buffer, "\e[%sm", colorYellow);
else if (i == 0)
ffStrbufAppendF(buffer, "\e[%sm", (green <= yellow ? colorGreen : colorRed));
}
ffStrbufAppend(buffer, borderAsValue && i == 0
? &options->barBorderLeftElapsed
@@ -146,9 +144,9 @@ void ffPercentAppendBar(FFstrbuf* buffer, double percent, FFPercentageModuleConf
for (uint8_t i = blocksPercent; i < options->barWidth; ++i)
{
ffStrbufAppend(buffer, borderAsValue && i == 0
? &options->barBorderLeftElapsed
? &options->barBorderLeft
: borderAsValue && i == options->barWidth - 1
? &options->barBorderRightElapsed
? &options->barBorderRight
: &options->barCharTotal);
}
}
+66 -18
View File
@@ -234,15 +234,42 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons
assert(processName->length > 0);
ffStrbufClear(exe);
#ifdef __linux__
#if defined(__linux__) || defined(__GNU__)
char filePath[64];
snprintf(filePath, sizeof(filePath), "/proc/%d/cmdline", (int)pid);
if(ffReadFileBuffer(filePath, exe))
{
ffStrbufRecalculateLength(exe); //Trim the arguments
ffStrbufTrimRightSpace(exe);
const char* p = exe->chars;
uint32_t len = (uint32_t) strlen(p);
if (len + 1 < exe->length)
{
const char* name = memrchr(p, '/', len);
if (name) name++; else name = p;
// For interpreters, try to find the real script path in the arguments
if (ffStrStartsWith(name, "python")
#ifndef __ANDROID__
|| ffStrEquals(name, "guile") // for shepherd
#endif
)
{
// `cmdline` always ends with a trailing '\0', and ffReadFileBuffer appends another \0
// So `exe->chars` is always double '\0' terminated
for (p = p + len + 1; *p && *p == '-'; p += strlen(p) + 1) // Skip arguments
assert(p - exe->chars < exe->allocated);
if (*p)
{
len = (uint32_t) strlen(p);
memmove(exe->chars, p, len + 1);
}
}
}
assert(len < exe->allocated);
exe->length = len;
ffStrbufTrimLeft(exe, '-'); //Login shells start with a dash
}
@@ -436,33 +463,53 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i
if (pid <= 0)
return "Invalid pid";
#ifdef __linux__
#if defined(__linux__) || defined(__GNU__)
char procFilePath[64];
if (ppid)
#if __linux__
if (ppid || tty)
#endif
{
snprintf(procFilePath, sizeof(procFilePath), "/proc/%d/stat", (int)pid);
char buf[PROC_FILE_BUFFSIZ];
ssize_t nRead = ffReadFileData(procFilePath, sizeof(buf) - 1, buf);
if(nRead <= 8)
return "ffReadFileData(/proc/pid/stat, PROC_FILE_BUFFSIZ-1, buf) failed";
buf[nRead] = '\0';
buf[nRead] = '\0'; // pid (comm) state ppid pgrp session tty
*ppid = 0;
static_assert(sizeof(*ppid) == sizeof(int), "");
const char* pState = NULL;
ffStrbufEnsureFixedLengthFree(name, 255);
int tty_;
if(
sscanf(buf, "%*s (%255[^)]) %*c %d %*d %*d %d", name->chars, ppid, &tty_) < 2 || //stat (comm) state ppid pgrp session tty
name->chars[0] == '\0'
)
return "sscanf(stat) failed";
{
// comm in `/proc/pid/stat` is not encoded, and may contain ' ', ')' or even `\n`
const char* start = memchr(buf, '(', (size_t) nRead);
if (!start)
return "memchr(stat, '(') failed";
start++;
const char* end = memrchr(start, ')', (size_t) nRead - (size_t) (start - buf));
if (!end)
return "memrchr(stat, ')') failed";
ffStrbufSetNS(name, (uint32_t) (end - start), start);
ffStrbufTrimRightSpace(name);
if (name->chars[0] == '\0')
return "process name is empty";
pState = end + 2; // skip ") "
}
ffStrbufRecalculateLength(name);
if (tty)
*tty = tty_ & 0xFF;
#if !__linux__
if (ppid || tty)
#endif
{
int ppid_, tty_;
if(sscanf(pState + 2, "%d %*d %*d %d", &ppid_, &tty_) < 2)
return "sscanf(stat) failed";
if (ppid)
*ppid = (pid_t) ppid_;
if (tty)
*tty = tty_ & 0xFF;
}
}
#if __linux__
else
{
snprintf(procFilePath, sizeof(procFilePath), "/proc/%d/comm", (int)pid);
@@ -471,6 +518,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i
return "ffReadFileBuffer(/proc/pid/comm, name) failed";
ffStrbufTrimRightSpace(name);
}
#endif
#elif defined(__APPLE__)
+126 -52
View File
@@ -184,7 +184,7 @@ FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type)
}
#endif //FF_HAVE_DCONF
FFvariant ffSettingsGet(const char* dconfKey, const char* gsettingsSchemaName, const char* gsettingsPath, const char* gsettingsKey, FFvarianttype type)
FFvariant ffSettingsGetGnome(const char* dconfKey, const char* gsettingsSchemaName, const char* gsettingsPath, const char* gsettingsKey, FFvarianttype type)
{
FFvariant gsettings = ffSettingsGetGSettings(gsettingsSchemaName, gsettingsPath, gsettingsKey, type);
@@ -196,77 +196,151 @@ FFvariant ffSettingsGet(const char* dconfKey, const char* gsettingsSchemaName, c
return ffSettingsGetDConf(dconfKey, type);
}
#ifdef FF_HAVE_XFCONF
#include <xfconf/xfconf.h>
typedef struct XFConfData
{
FF_LIBRARY_SYMBOL(xfconf_channel_get)
FF_LIBRARY_SYMBOL(xfconf_channel_has_property)
FF_LIBRARY_SYMBOL(xfconf_channel_get_string)
FF_LIBRARY_SYMBOL(xfconf_channel_get_bool)
FF_LIBRARY_SYMBOL(xfconf_channel_get_int)
FF_LIBRARY_SYMBOL(xfconf_init)
bool inited;
} XFConfData;
static const XFConfData* getXFConfData(void)
{
static XFConfData data;
if (!data.inited)
{
data.inited = true;
FF_LIBRARY_LOAD(libxfconf, NULL, "libxfconf-0" FF_LIBRARY_EXTENSION, 4);
FF_LIBRARY_LOAD_SYMBOL_VAR(libxfconf, data, xfconf_channel_get, NULL)
FF_LIBRARY_LOAD_SYMBOL_VAR(libxfconf, data, xfconf_channel_has_property, NULL)
FF_LIBRARY_LOAD_SYMBOL_VAR(libxfconf, data, xfconf_channel_get_string, NULL)
FF_LIBRARY_LOAD_SYMBOL_VAR(libxfconf, data, xfconf_channel_get_bool, NULL)
FF_LIBRARY_LOAD_SYMBOL_VAR(libxfconf, data, xfconf_channel_get_int, NULL)
FF_LIBRARY_LOAD_SYMBOL_VAR(libxfconf, data, xfconf_init, NULL)
if(!data.ffxfconf_init(NULL))
data.ffxfconf_init = NULL;
else
libxfconf = NULL;
}
if(!data.ffxfconf_init)
return NULL;
return &data;
}
#ifdef FF_HAVE_DBUS
#include "common/dbus.h"
FFvariant ffSettingsGetXFConf(const char* channelName, const char* propertyName, FFvarianttype type)
{
const XFConfData* data = getXFConfData();
if(data == NULL)
FFDBusData dbus;
if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL)
return FF_VARIANT_NULL;
XfconfChannel* channel = data->ffxfconf_channel_get(channelName); // Never fails according to documentation but rather returns an empty channel
if(!data->ffxfconf_channel_has_property(channel, propertyName))
DBusMessage* reply = ffDBusGetMethodReply(&dbus, "org.xfce.Xfconf", "/org/xfce/Xfconf", "org.xfce.Xfconf", "GetProperty", channelName, propertyName);
if(!reply)
return FF_VARIANT_NULL;
DBusMessageIter rootIterator;
if(!dbus.lib->ffdbus_message_iter_init(reply, &rootIterator))
{
dbus.lib->ffdbus_message_unref(reply);
return FF_VARIANT_NULL;
}
if(type == FF_VARIANT_TYPE_INT)
return (FFvariant) {.intValue = data->ffxfconf_channel_get_int(channel, propertyName, 0)};
{
int32_t value;
if (ffDBusGetInt(&dbus, &rootIterator, &value))
{
dbus.lib->ffdbus_message_unref(reply);
return (FFvariant) { .intValue = value };
}
return FF_VARIANT_NULL;
}
if(type == FF_VARIANT_TYPE_STRING)
return (FFvariant) {.strValue = data->ffxfconf_channel_get_string(channel, propertyName, NULL)};
{
FFstrbuf value = ffStrbufCreate();
if (ffDBusGetString(&dbus, &rootIterator, &value))
{
dbus.lib->ffdbus_message_unref(reply);
return (FFvariant) { .strValue = value.chars }; // Leaks value.chars
}
return FF_VARIANT_NULL;
}
if(type == FF_VARIANT_TYPE_BOOL)
return (FFvariant) {.boolValue = data->ffxfconf_channel_get_bool(channel, propertyName, false), .boolValueSet = true};
{
bool value;
if (ffDBusGetBool(&dbus, &rootIterator, &value))
{
dbus.lib->ffdbus_message_unref(reply);
return (FFvariant) { .boolValue = value, .boolValueSet = true };
}
}
return FF_VARIANT_NULL;
}
#else //FF_HAVE_XFCONF
#define FF_DBUS_ITER_CONTINUE(dbus, iterator) \
{ \
if(!(dbus).lib->ffdbus_message_iter_next(iterator)) \
break; \
continue; \
}
FFvariant ffSettingsGetXFConfFirstMatch(const char* channelName, const char* propertyPrefix, FFvarianttype type, void* data, FFTestXfconfPropCallback* cb)
{
FFDBusData dbus;
if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL)
return FF_VARIANT_NULL;
DBusMessage* reply = ffDBusGetMethodReply(&dbus, "org.xfce.Xfconf", "/org/xfce/Xfconf", "org.xfce.Xfconf", "GetAllProperties", channelName, propertyPrefix);
if(!reply)
return FF_VARIANT_NULL;
DBusMessageIter rootIterator;
if(!dbus.lib->ffdbus_message_iter_init(reply, &rootIterator))
{
dbus.lib->ffdbus_message_unref(reply);
return FF_VARIANT_NULL;
}
DBusMessageIter arrayIterator;
dbus.lib->ffdbus_message_iter_recurse(&rootIterator, &arrayIterator);
while(true)
{
if(dbus.lib->ffdbus_message_iter_get_arg_type(&arrayIterator) != DBUS_TYPE_DICT_ENTRY)
FF_DBUS_ITER_CONTINUE(dbus, &arrayIterator)
DBusMessageIter dictIterator;
dbus.lib->ffdbus_message_iter_recurse(&arrayIterator, &dictIterator);
const char* key;
dbus.lib->ffdbus_message_iter_get_basic(&dictIterator, &key);
if (cb(data, key)) FF_DBUS_ITER_CONTINUE(dbus, &arrayIterator)
dbus.lib->ffdbus_message_iter_next(&dictIterator);
if(type == FF_VARIANT_TYPE_INT)
{
int32_t value;
if (ffDBusGetInt(&dbus, &dictIterator, &value))
{
dbus.lib->ffdbus_message_unref(reply);
return (FFvariant) { .intValue = value };
}
return FF_VARIANT_NULL;
}
if(type == FF_VARIANT_TYPE_STRING)
{
FFstrbuf value = ffStrbufCreate();
if (ffDBusGetString(&dbus, &dictIterator, &value))
{
dbus.lib->ffdbus_message_unref(reply);
return (FFvariant) { .strValue = value.chars }; // Leaks value.chars
}
return FF_VARIANT_NULL;
}
if(type == FF_VARIANT_TYPE_BOOL)
{
bool value;
if (ffDBusGetBool(&dbus, &dictIterator, &value))
{
dbus.lib->ffdbus_message_unref(reply);
return (FFvariant) { .boolValue = value, .boolValueSet = true };
}
}
return FF_VARIANT_NULL;
}
return FF_VARIANT_NULL;
}
#else //FF_HAVE_DBUS
FFvariant ffSettingsGetXFConf(const char* channelName, const char* propertyName, FFvarianttype type)
{
FF_UNUSED(channelName, propertyName, type)
return FF_VARIANT_NULL;
}
#endif //FF_HAVE_XFCONF
FFvariant ffSettingsGetXFConfFirstMatch(const char* channelName, const char* propertyPrefix, FFvarianttype type, void* data, FFTestXfconfPropCallback* cb)
{
FF_UNUSED(channelName, propertyPrefix, type, data, cb);
return FF_VARIANT_NULL;
}
#endif //FF_HAVE_DBUS
#ifdef FF_HAVE_SQLITE3
#include <sqlite3.h>
+3 -1
View File
@@ -24,8 +24,10 @@ typedef union FFvariant
FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type);
FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const char* key, FFvarianttype type);
FFvariant ffSettingsGet(const char* dconfKey, const char* gsettingsSchemaName, const char* gsettingsPath, const char* gsettingsKey, FFvarianttype type);
FFvariant ffSettingsGetGnome(const char* dconfKey, const char* gsettingsSchemaName, const char* gsettingsPath, const char* gsettingsKey, FFvarianttype type);
FFvariant ffSettingsGetXFConf(const char* channelName, const char* propertyName, FFvarianttype type);
typedef bool FFTestXfconfPropCallback(void* data, const char* propertyName); // Return false to break loop
FFvariant ffSettingsGetXFConfFirstMatch(const char* channelName, const char* propertyPrefix, FFvarianttype type, void* data, FFTestXfconfPropCallback* cb);
int ffSettingsGetSQLite3Int(const char* dbPath, const char* query);
bool ffSettingsGetSQLite3String(const char* dbPath, const char* query, FFstrbuf* result);
+6 -4
View File
@@ -14,11 +14,13 @@ static void appendNum(FFstrbuf* result, uint64_t bytes, uint32_t base, const cha
counter++;
}
const char* space = options->sizeSpaceBeforeUnit == FF_SPACE_BEFORE_UNIT_NEVER ? "" : " ";
if(counter == 0)
ffStrbufAppendF(result, "%" PRIu64 "%s%s", bytes, space, prefixes[0]);
if (counter == 0)
ffStrbufAppendUInt(result, bytes);
else
ffStrbufAppendF(result, "%.*f%s%s", options->sizeNdigits, size, space, prefixes[counter]);
ffStrbufAppendDouble(result, size, (int8_t) options->sizeNdigits, true);
if (options->sizeSpaceBeforeUnit != FF_SPACE_BEFORE_UNIT_NEVER)
ffStrbufAppendC(result, ' ');
ffStrbufAppendS(result, prefixes[counter]);
}
void ffSizeAppendNum(uint64_t bytes, FFstrbuf* result)
+3
View File
@@ -0,0 +1,3 @@
#include <time.h>
char ffTimeInternalBuffer[64]; // Reduce memory usage and prevent redundant allocations
+15 -12
View File
@@ -11,6 +11,8 @@
#include <OS.h>
#endif
#include "util/arrayUtils.h"
static inline double ffTimeGetTick(void) //In msec
{
#ifdef _WIN32
@@ -64,11 +66,12 @@ static inline const char* ffTimeToFullStr(uint64_t msec)
time_t tsec = (time_t) (msec / 1000);
const struct tm* tm = localtime(&tsec);
static char buf[32];
strftime(buf, __builtin_strlen("0000-00-00T00:00:00") + 1, "%FT%T", tm);
snprintf(buf + __builtin_strlen("0000-00-00T00:00:00"), __builtin_strlen(".000") + 1, ".%03u", (unsigned) (msec % 1000));
strftime(buf + __builtin_strlen("0000-00-00T00:00:00.000"), __builtin_strlen("+0000") + 1, "%z", tm);
return buf;
extern char ffTimeInternalBuffer[64];
uint32_t len = 0;
len += (uint32_t) strftime(ffTimeInternalBuffer, ARRAY_SIZE(ffTimeInternalBuffer) - len, "%FT%T", tm);
len += (uint32_t) snprintf(ffTimeInternalBuffer + len, ARRAY_SIZE(ffTimeInternalBuffer) - len, ".%03u", (unsigned) (msec % 1000));
len += (uint32_t) strftime(ffTimeInternalBuffer + len, ARRAY_SIZE(ffTimeInternalBuffer) - len, "%z", tm);
return ffTimeInternalBuffer;
}
// Not thread-safe
@@ -77,9 +80,9 @@ static inline const char* ffTimeToShortStr(uint64_t msec)
if (msec == 0) return "";
time_t tsec = (time_t) (msec / 1000);
static char buf[32];
strftime(buf, sizeof(buf), "%F %T", localtime(&tsec));
return buf;
extern char ffTimeInternalBuffer[64];
strftime(ffTimeInternalBuffer, ARRAY_SIZE(ffTimeInternalBuffer), "%F %T", localtime(&tsec));
return ffTimeInternalBuffer;
}
// Not thread-safe
@@ -88,10 +91,10 @@ static inline const char* ffTimeToTimeStr(uint64_t msec)
if (msec == 0) return "";
time_t tsec = (time_t) (msec / 1000);
static char buf[32];
strftime(buf, sizeof(buf), "%T", localtime(&tsec));
sprintf(buf + __builtin_strlen("00:00:00"), ".%03u", (unsigned) (msec % 1000));
return buf;
extern char ffTimeInternalBuffer[64];
uint32_t len = (uint32_t) strftime(ffTimeInternalBuffer, ARRAY_SIZE(ffTimeInternalBuffer), "%T", localtime(&tsec));
sprintf(ffTimeInternalBuffer + len, ".%03u", (unsigned) (msec % 1000));
return ffTimeInternalBuffer;
}
#ifdef _WIN32
+12
View File
@@ -846,6 +846,18 @@
"default": -1
}
},
{
"long": "fraction-trailing-zeros",
"desc": "Set when to keep trailing zeros",
"arg": {
"type": "enum",
"enum": {
"default": "Use the behavior defined internally",
"always": "Always keep trailing zeros",
"never": "Never keep trailing zeros"
}
}
},
{
"long": "temp-unit",
"desc": "Set the temperature unit",
+4
View File
@@ -139,7 +139,11 @@ static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results)
if(options->temp)
{
if (ffParsePropLines(start, "temperature: ", &temp))
{
battery->temperature = ffStrbufToDouble(&temp, FF_BATTERY_TEMP_UNSET);
if (battery->temperature != FF_BATTERY_TEMP_UNSET)
battery->temperature /= 10.0; // Android returns temperature in tenths of a degree
}
ffStrbufClear(&temp);
}
+1 -1
View File
@@ -196,7 +196,7 @@ static const char* detectBluetooth(FFlist* devices, int32_t connectedCount)
if(error)
return error;
DBusMessage* managedObjects = ffDBusGetMethodReply(&dbus, "org.bluez", "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", NULL);
DBusMessage* managedObjects = ffDBusGetMethodReply(&dbus, "org.bluez", "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", NULL, NULL);
if(!managedObjects)
return "Failed to call GetManagedObjects";
@@ -77,7 +77,7 @@ static const char* detectBluetoothRoot(FFBluetoothRadioResult* device, const cha
char objPath[300];
snprintf(objPath, sizeof(objPath), "/org/bluez/%s", hciName);
DBusMessage* properties = ffDBusGetMethodReply(dbus, "org.bluez", objPath, "org.freedesktop.DBus.Properties", "GetAll", "org.bluez.Adapter1");
DBusMessage* properties = ffDBusGetMethodReply(dbus, "org.bluez", objPath, "org.freedesktop.DBus.Properties", "GetAll", "org.bluez.Adapter1", NULL);
if(!properties)
return "Failed to call org.freedesktop.DBus.Properties.GetAll";
+2 -1
View File
@@ -8,7 +8,8 @@ typedef struct FFBtrfsDiskUsage
uint64_t total;
uint64_t used;
const char* type;
bool dup;
const char* profile; // single / dup / raidx
uint8_t copies;
} FFBtrfsDiskUsage;
typedef struct FFBtrfsResult
+33 -13
View File
@@ -73,20 +73,40 @@ static const char* detectAllocation(FFBtrfsResult* item, int dfd, FFstrbuf* buff
item->globalReservationUsed = ffStrbufToUInt(buffer, 0);
item->globalReservationUsed = item->globalReservationTotal - item->globalReservationUsed;
#define FF_BTRFS_DETECT_TYPE(index, _type) \
if (ffReadFileBufferRelative(subfd, #_type "/total_bytes", buffer)) \
item->allocation[index].total = ffStrbufToUInt(buffer, 0); \
\
if (ffReadFileBufferRelative(subfd, #_type "/bytes_used", buffer)) \
item->allocation[index].used = ffStrbufToUInt(buffer, 0); \
\
item->allocation[index].dup = faccessat(subfd, #_type "/dup/", F_OK, 0) == 0; \
\
item->allocation[index].type = #_type;
#define FF_BTRFS_DETECT_PROFILE(_index, _type, _profile, _copies) \
else if (faccessat(subfd, _type "/" _profile "/", F_OK, 0) == 0) { \
item->allocation[_index].profile = _profile; \
item->allocation[_index].copies = _copies; \
}
FF_BTRFS_DETECT_TYPE(0, data);
FF_BTRFS_DETECT_TYPE(1, metadata);
FF_BTRFS_DETECT_TYPE(2, system);
#define FF_BTRFS_DETECT_TYPE(_index, _type) \
do { \
item->allocation[_index].type = _type; \
if (ffReadFileBufferRelative(subfd, _type "/total_bytes", buffer)) \
item->allocation[_index].total = ffStrbufToUInt(buffer, 0); \
\
if (ffReadFileBufferRelative(subfd, _type "/bytes_used", buffer)) \
item->allocation[_index].used = ffStrbufToUInt(buffer, 0); \
\
if (false) {} \
FF_BTRFS_DETECT_PROFILE(_index, _type, "single", 1) \
FF_BTRFS_DETECT_PROFILE(_index, _type, "dup", 2) \
FF_BTRFS_DETECT_PROFILE(_index, _type, "raid0", 1) \
FF_BTRFS_DETECT_PROFILE(_index, _type, "raid1", 2) \
FF_BTRFS_DETECT_PROFILE(_index, _type, "raid10", 2) \
FF_BTRFS_DETECT_PROFILE(_index, _type, "raid1c3", 3) \
FF_BTRFS_DETECT_PROFILE(_index, _type, "raid1c4", 4) \
FF_BTRFS_DETECT_PROFILE(_index, _type, "raid5", 1) /* (n-1)/n */ \
FF_BTRFS_DETECT_PROFILE(_index, _type, "raid6", 1) /* (n-2)/n */ \
else { \
item->allocation[_index].profile = "unknown"; \
item->allocation[_index].copies = 1; \
} \
} while (0)
FF_BTRFS_DETECT_TYPE(0, "data");
FF_BTRFS_DETECT_TYPE(1, "metadata");
FF_BTRFS_DETECT_TYPE(2, "system");
#undef FF_BTRFS_DETECT_TYPE
+471
View File
@@ -60,3 +60,474 @@ const char* ffCPUQualcommCodeToName(uint32_t code)
default: return NULL;
}
}
#if defined(__x86_64__) || defined(__i386__)
#include <cpuid.h>
void ffCPUDetectByCpuid(FFCPUResult* cpu)
{
uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0;
if (__get_cpuid(0x16, &eax, &ebx, &ecx, &edx))
{
// WARNING: CPUID may report frequencies of efficient cores
// cpuid returns 0 MHz when hypervisor is enabled
if (eax) cpu->frequencyBase = eax;
if (ebx) cpu->frequencyMax = ebx;
}
if (__get_cpuid(1, &eax, &ebx, &ecx, &edx))
{
// Feature tests (leaf1.ecx, leaf7.ebx)
bool sse2 = (ecx & bit_SSE2) != 0;
bool sse4_2 = (ecx & bit_SSE4_2) != 0;
bool pclmul = (ecx & bit_PCLMUL) != 0;
bool popcnt = (ecx & bit_POPCNT) != 0;
bool fma = (ecx & bit_FMA) != 0;
bool osxsave = (ecx & bit_OSXSAVE) != 0;
unsigned int eax7 = 0, ebx7 = 0, ecx7 = 0, edx7 = 0;
__get_cpuid_count(7, 0, &eax7, &ebx7, &ecx7, &edx7);
bool avx2 = (ebx7 & bit_AVX2) != 0;
bool bmi2 = (ebx7 & bit_BMI2) != 0;
bool avx512f = (ebx7 & bit_AVX512F) != 0;
bool avx512bw = (ebx7 & bit_AVX512BW) != 0;
bool avx512dq = (ebx7 & bit_AVX512DQ) != 0;
// OS support for AVX/AVX512: check XGETBV (requires OSXSAVE)
bool avx_os = false;
bool avx512_os = false;
if (osxsave)
{
__asm__ __volatile__(
"xgetbv"
: "=a"(eax), "=d"(edx)
: "c"(0)
:
);
uint64_t xcr0 = ((uint64_t)edx << 32) | eax;
// AVX requires XCR0[1:2] == 11b (XMM and YMM state)
avx_os = (xcr0 & 0x6ULL) == 0x6ULL;
// AVX512 requires XCR0[7,5,6] etc. common mask 0xE6 (bits 1,2,5,6,7)
avx512_os = (xcr0 & 0xE6ULL) == 0xE6ULL;
}
cpu->march = "unknown";
if (avx512f && avx512bw && avx512dq && avx512_os) cpu->march = "x86_64-v4";
else if (avx2 && fma && bmi2 && avx_os) cpu->march = "x86_64-v3";
else if (sse4_2 && popcnt && pclmul) cpu->march = "x86_64-v2";
else if (sse2) cpu->march = "x86_64-v1";
}
}
#elif defined(__aarch64__)
// This is not accurate because a lot of flags are optional from old versions
// https://developer.arm.com/documentation/109697/2025_06/Feature-descriptions?lang=en
// https://en.wikipedia.org/wiki/AArch64#ARM-A_(application_architecture)
// Worth noting: Apple M1 is marked as ARMv8.5-A on Wikipedia, but it lacks BTI (mandatory in v8.5)
#ifdef __linux__
#include "common/io/io.h"
#include <elf.h>
#include <asm/hwcap.h>
#ifndef HWCAP2_SME
#define HWCAP2_SME (1UL << 23)
#endif
#ifndef HWCAP2_SME2
#define HWCAP2_SME2 (1UL << 37)
#endif
#ifndef HWCAP2_CSSC
#define HWCAP2_CSSC (1UL << 34)
#endif
#ifndef HWCAP2_SME2P1
#define HWCAP2_SME2P1 (1UL << 38)
#endif
#ifndef HWCAP2_MOPS
#define HWCAP2_MOPS (1UL << 43)
#endif
#ifndef HWCAP2_F8E4M3
#define HWCAP2_F8E4M3 (1UL << 55)
#endif
#ifndef HWCAP2_F8E5M2
#define HWCAP2_F8E5M2 (1UL << 56)
#endif
#ifndef HWCAP_CMPBR
#define HWCAP_CMPBR (1UL << 33)
#endif
#ifndef HWCAP_FPRCVT
#define HWCAP_FPRCVT (1UL << 34)
#endif
void ffCPUDetectByCpuid(FFCPUResult* cpu)
{
char buf[PROC_FILE_BUFFSIZ];
ssize_t nRead = ffReadFileData("/proc/self/auxv", ARRAY_SIZE(buf), buf);
if (nRead < (ssize_t) sizeof(Elf64_auxv_t)) return;
uint64_t hwcap = 0, hwcap2 = 0;
for (Elf64_auxv_t* auxv = (Elf64_auxv_t*)buf; (char*)auxv < buf + nRead; ++auxv)
{
if (auxv->a_type == AT_HWCAP)
{
hwcap = auxv->a_un.a_val;
}
else if (auxv->a_type == AT_HWCAP2)
{
hwcap2 = auxv->a_un.a_val;
}
}
if (!hwcap) return;
cpu->march = "unknown";
// ARMv8-A
bool has_fp = (hwcap & HWCAP_FP) != 0;
bool has_asimd = (hwcap & HWCAP_ASIMD) != 0;
// ARMv8.1-A
bool has_atomics = (hwcap & HWCAP_ATOMICS) != 0; // optional from v8.0
bool has_crc32 = (hwcap & HWCAP_CRC32) != 0; // optional from v8.0
bool has_asimdrdm = (hwcap & HWCAP_ASIMDRDM) != 0; // optional from v8.0
// ARMv8.2-A
bool has_fphp = (hwcap & HWCAP_FPHP) != 0; // optional
bool has_dcpop = (hwcap & HWCAP_DCPOP) != 0; // DC CVAP, optional from v8.1
// ARMv8.3-A
bool has_paca = (hwcap & HWCAP_PACA) != 0; // optional from v8.2
bool has_lrcpc = (hwcap & HWCAP_LRCPC) != 0; // optional from v8.2
bool has_fcma = (hwcap & HWCAP_FCMA) != 0; // optional from v8.2
bool has_jscvt = (hwcap & HWCAP_JSCVT) != 0; // optional from v8.2
// ARMv8.4-A
bool has_dit = (hwcap & HWCAP_DIT) != 0; // optional from v8.3
bool has_flagm = (hwcap & HWCAP_FLAGM) != 0; // optional from v8.1
bool has_ilrcpc = (hwcap & HWCAP_ILRCPC) != 0; // optional from v8.2
// ARMv8.5-A
bool has_bti = (hwcap2 & HWCAP2_BTI) != 0; // optional from v8.4
bool has_sb = (hwcap & HWCAP_SB) != 0; // optional from v8.0
bool has_dcpodp = (hwcap2 & HWCAP2_DCPODP) != 0; // optional from v8.1
bool has_flagm2 = (hwcap2 & HWCAP2_FLAGM2) != 0; // optional from v8.4
bool has_frint = (hwcap2 & HWCAP2_FRINT) != 0; // optional from v8.4
// ARMv9.0-A
bool has_sve2 = (hwcap2 & HWCAP2_SVE2) != 0;
// ARMv9.1-A
// ARMv8.6-A
bool has_bf16 = (hwcap2 & HWCAP2_BF16) != 0; // optional from v8.2
bool has_i8mm = (hwcap2 & HWCAP2_I8MM) != 0; // optional from v8.1
// ARMv8.7-A
bool has_afp = (hwcap2 & HWCAP2_AFP) != 0; // optional from v8.6
// ARMv9.2-A
bool has_sme = (hwcap2 & HWCAP2_SME) != 0;
// ARMv9.3-A
bool has_sme2 = (hwcap2 & HWCAP2_SME2) != 0; // optional from v9.2
// ARMv8.8-A
bool has_mops = (hwcap2 & HWCAP2_MOPS) != 0; // optional from v8.7
// ARMv8.9-A
bool has_cssc = (hwcap2 & HWCAP2_CSSC) != 0; // optional from v8.7
// ARMv9.4-A
bool has_sme2p1 = (hwcap2 & HWCAP2_SME2P1) != 0; // optional from v9.2
// ARMv9.5-A
bool has_f8e4m3 = (hwcap2 & HWCAP2_F8E4M3) != 0; // optional from v9.2
bool has_f8e5m2 = (hwcap2 & HWCAP2_F8E5M2) != 0; // optional from v9.2
// ARMv9.6-A
bool has_cmpbr = (hwcap & HWCAP_CMPBR) != 0; // optional from v9.5
bool has_fprcvt = (hwcap & HWCAP_FPRCVT) != 0; // optional from v9.5
if (has_sve2 || has_sme) {
// ARMv9
if (has_cmpbr && has_fprcvt) {
cpu->march = "ARMv9.6-A";
} else if (has_f8e5m2 && has_f8e4m3) {
cpu->march = "ARMv9.5-A";
} else if (has_sme2p1) {
cpu->march = "ARMv9.4-A";
} else if (has_sme2) {
cpu->march = "ARMv9.3-A";
} else if (has_sme) {
cpu->march = "ARMv9.2-A";
} else if (has_i8mm && has_bf16) {
cpu->march = "ARMv9.1-A";
} else {
cpu->march = "ARMv9.0-A";
}
} else {
// ARMv8
if (has_cssc) {
cpu->march = "ARMv8.9-A";
} else if (has_mops) {
cpu->march = "ARMv8.8-A";
} else if (has_afp) {
cpu->march = "ARMv8.7-A";
} else if (has_i8mm && has_bf16) {
cpu->march = "ARMv8.6-A";
} else if (has_bti && has_sb && has_dcpodp && has_flagm2 && has_frint) {
cpu->march = "ARMv8.5-A";
} else if (has_dit && has_flagm && has_ilrcpc) {
cpu->march = "ARMv8.4-A";
} else if (has_paca && has_lrcpc && has_fcma && has_jscvt) {
cpu->march = "ARMv8.3-A";
} else if (has_fphp && has_dcpop) {
cpu->march = "ARMv8.2-A";
} else if (has_atomics && has_crc32 && has_asimdrdm) {
cpu->march = "ARMv8.1-A";
} else if (has_asimd && has_fp) {
cpu->march = "ARMv8-A";
}
}
}
#elif __APPLE__
#include <sys/sysctl.h>
// #include <arm/cpu_capabilities_public.h> // Not available in macOS 14-
void ffCPUDetectByCpuid(FFCPUResult* cpu)
{
uint64_t caps[2] = {0}; // 80-bit capability mask, split into two 64-bit values
size_t size = sizeof(caps);
if (sysctlbyname("hw.optional.arm.caps", caps, &size, NULL, 0) != 0) return;
// Helper macro to test bit in 80-bit capability mask
#define FF_HAS_CAP(bit) \
(((bit) < 64) ? ((caps[0] >> (bit)) & 1ULL) : ((caps[1] >> ((bit) - 64U)) & 1ULL))
cpu->march = "unknown";
// ARMv8-A
bool has_fp = FF_HAS_CAP(50); /* CAP_BIT_AdvSIMD_HPFPCvt */ // Full FP16 support (implies FP/ASIMD)
bool has_asimd = FF_HAS_CAP(49); /* CAP_BIT_AdvSIMD */ // Advanced SIMD (NEON)
// ARMv8.1-A
bool has_lse = FF_HAS_CAP(6); /* CAP_BIT_FEAT_LSE */ // Large System Extensions, optional in v8.0
bool has_crc32 = FF_HAS_CAP(51); /* CAP_BIT_FEAT_CRC32 */ // CRC32 instructions, optional in v8.0
bool has_rdm = FF_HAS_CAP(5); /* CAP_BIT_FEAT_RDM */ // AdvSIMD rounding double multiply accumulate, optional in v8.0
// ARMv8.2-A
bool has_fp16 = FF_HAS_CAP(34); /* CAP_BIT_FEAT_FP16 */ // Half-precision FP support, optional
bool has_dpb = FF_HAS_CAP(22); /* CAP_BIT_FEAT_DPB */ // DC CVAP, optional from v8.1
// ARMv8.3-A
bool has_pauth = FF_HAS_CAP(19); /* CAP_BIT_FEAT_PAuth */ // Pointer Authentication (PAC), optional from v8.2
bool has_lrcpc = FF_HAS_CAP(15); /* CAP_BIT_FEAT_LRCPC */ // LDAPR/LR with RCPC semantics, optional from v8.2
bool has_fcma = FF_HAS_CAP(17); /* CAP_BIT_FEAT_FCMA */ // Complex number multiply-add, optional from v8.2
bool has_jscvt = FF_HAS_CAP(18); /* CAP_BIT_FEAT_JSCVT */ // JavaScript-style conversion (FJCVTZS), optional from v8.2
// ARMv8.4-A
bool has_lse2 = FF_HAS_CAP(30); /* CAP_BIT_FEAT_LSE2 */ // Large System Extensions version 2, optional from v8.2
bool has_dit = FF_HAS_CAP(33); /* CAP_BIT_FEAT_DIT */ // Data Independent Timing, optional from v8.3
bool has_flagm = FF_HAS_CAP(0); /* CAP_BIT_FEAT_FlagM */ // Flag manipulation (FMOV/FCVT), optional from v8.1
bool has_lrcpc2 = FF_HAS_CAP(16); /* CAP_BIT_FEAT_LRCPC2 */ // Enhanced RCPC (LDAPUR/LDAPST), optional from v8.2
// ARMv8.5-A
bool has_bti = FF_HAS_CAP(36); /* CAP_BIT_FEAT_BTI */ // Branch Target Identification, optional from v8.4
bool has_sb = FF_HAS_CAP(13); /* CAP_BIT_FEAT_SB */ // Speculative Barrier, optional from v8.0
bool has_dpb2 = FF_HAS_CAP(23); /* CAP_BIT_FEAT_DPB2 */ // DC CVADP (DPB2), optional from v8.1
bool has_flagm2 = FF_HAS_CAP(1); /* CAP_BIT_FEAT_FlagM2 */ // Enhanced FlagM, optional from v8.4
bool has_frintts = FF_HAS_CAP(14); /* CAP_BIT_FEAT_FRINTTS */ // Floating-point to integer instructions, optional from v8.4
// ARMv9.0-A
bool has_sve2 = false; // Not exposed and not supported by Apple M4
// ARMv9.1-A
// ARMv8.6-A
bool has_bf16 = FF_HAS_CAP(24); /* CAP_BIT_FEAT_BF16 */ // Brain float16, optional from v8.2
bool has_i8mm = FF_HAS_CAP(25); /* CAP_BIT_FEAT_I8MM */ // Int8 Matrix Multiply, optional from v8.1
// ARMv8.7-A
bool has_afp = FF_HAS_CAP(29); /* CAP_BIT_FEAT_AFP */ // Alternate FP16 (FEXPA), optional from v8.6
// ARMv9.2-A
bool has_sme = FF_HAS_CAP(40); /* CAP_BIT_FEAT_SME */ // Scalable Matrix Extension, optional from v9.2
// ARMv9.3-A
bool has_sme2 = FF_HAS_CAP(41); /* CAP_BIT_FEAT_SME2 */ // SME2, optional from v9.2
// ARMv8.8-A
bool has_hbc = FF_HAS_CAP(64); /* CAP_BIT_FEAT_HBC */ // Hinted conditional branches, optional from v8.7
// ARMv8.9-A
bool has_cssc = FF_HAS_CAP(67); /* CAP_BIT_FEAT_CSSC */ // Common Short String Compare, optional from v8.7
// ARMv9.4-A+ are not exposed yet
if (has_sve2 || has_sme) {
// ARMv9 family
if (has_sme2) {
cpu->march = "ARMv9.3-A";
} else if (has_sme) {
cpu->march = "ARMv9.2-A";
} else if (has_i8mm && has_bf16) {
cpu->march = "ARMv9.1-A";
} else {
cpu->march = "ARMv9.0-A";
}
} else {
// ARMv8 family
if (has_cssc) {
cpu->march = "ARMv8.9-A";
} else if (has_hbc) {
cpu->march = "ARMv8.8-A";
} else if (has_afp) {
cpu->march = "ARMv8.7-A";
} else if (has_i8mm && has_bf16) {
cpu->march = "ARMv8.6-A";
} else if (has_bti && has_sb && has_dpb2 && has_flagm2 && has_frintts) {
cpu->march = "ARMv8.5-A";
} else if (has_lse2 && has_dit && has_flagm && has_lrcpc2) {
cpu->march = "ARMv8.4-A";
} else if (has_pauth && has_lrcpc && has_fcma && has_jscvt) {
cpu->march = "ARMv8.3-A";
} else if (has_fp16 && has_dpb) {
cpu->march = "ARMv8.2-A";
} else if (has_lse && has_crc32 && has_rdm) {
cpu->march = "ARMv8.1-A";
} else if (has_asimd && has_fp) {
cpu->march = "ARMv8-A";
}
}
#undef HAS_CAP
}
#elif _WIN32
#include <processthreadsapi.h>
// Missing from winnt.h of MinGW-w64
#define PF_ARM_LSE2_AVAILABLE 62
#define PF_RESERVED_FEATURE 63
#define PF_ARM_SHA3_INSTRUCTIONS_AVAILABLE 64
#define PF_ARM_SHA512_INSTRUCTIONS_AVAILABLE 65
#define PF_ARM_V82_I8MM_INSTRUCTIONS_AVAILABLE 66
#define PF_ARM_V82_FP16_INSTRUCTIONS_AVAILABLE 67
#define PF_ARM_V86_BF16_INSTRUCTIONS_AVAILABLE 68
#define PF_ARM_V86_EBF16_INSTRUCTIONS_AVAILABLE 69
#define PF_ARM_SME_INSTRUCTIONS_AVAILABLE 70
#define PF_ARM_SME2_INSTRUCTIONS_AVAILABLE 71
#define PF_ARM_SME2_1_INSTRUCTIONS_AVAILABLE 72
#define PF_ARM_SME2_2_INSTRUCTIONS_AVAILABLE 73
#define PF_ARM_SME_AES_INSTRUCTIONS_AVAILABLE 74
#define PF_ARM_SME_SBITPERM_INSTRUCTIONS_AVAILABLE 75
#define PF_ARM_SME_SF8MM4_INSTRUCTIONS_AVAILABLE 76
#define PF_ARM_SME_SF8MM8_INSTRUCTIONS_AVAILABLE 77
#define PF_ARM_SME_SF8DP2_INSTRUCTIONS_AVAILABLE 78
#define PF_ARM_SME_SF8DP4_INSTRUCTIONS_AVAILABLE 79
#define PF_ARM_SME_SF8FMA_INSTRUCTIONS_AVAILABLE 80
#define PF_ARM_SME_F8F32_INSTRUCTIONS_AVAILABLE 81
#define PF_ARM_SME_F8F16_INSTRUCTIONS_AVAILABLE 82
#define PF_ARM_SME_F16F16_INSTRUCTIONS_AVAILABLE 83
#define PF_ARM_SME_B16B16_INSTRUCTIONS_AVAILABLE 84
#define PF_ARM_SME_F64F64_INSTRUCTIONS_AVAILABLE 85
#define PF_ARM_SME_I16I64_INSTRUCTIONS_AVAILABLE 86
#define PF_ARM_SME_LUTv2_INSTRUCTIONS_AVAILABLE 87
#define PF_ARM_SME_FA64_INSTRUCTIONS_AVAILABLE 88
void ffCPUDetectByCpuid(FFCPUResult* cpu)
{
// ARMv8-A
bool has_vfp = IsProcessorFeaturePresent(PF_ARM_VFP_32_REGISTERS_AVAILABLE); // Implies basic FP support
bool has_neon = IsProcessorFeaturePresent(PF_ARM_NEON_INSTRUCTIONS_AVAILABLE); // NEON (ASIMD)
// ARMv8.1-A
bool has_atomics = IsProcessorFeaturePresent(PF_ARM_V81_ATOMIC_INSTRUCTIONS_AVAILABLE); // LSE atomics
bool has_crc32 = IsProcessorFeaturePresent(PF_ARM_V8_CRC32_INSTRUCTIONS_AVAILABLE); // CRC32
// ARMv8.2-A
bool has_fp16 = IsProcessorFeaturePresent(PF_ARM_V82_FP16_INSTRUCTIONS_AVAILABLE); // Half-precision FP
// ARMv8.3-A
bool has_lrcpc = IsProcessorFeaturePresent(PF_ARM_V83_LRCPC_INSTRUCTIONS_AVAILABLE); // LDAPR/LR with RCPC semantics
bool has_jscvt = IsProcessorFeaturePresent(PF_ARM_V83_JSCVT_INSTRUCTIONS_AVAILABLE); // FJCVTZS
// ARMv8.4-A
// My CPU (Apple M1 Pro in VM) does support LSE2, but Windows doesn't detect it for some reason
// bool has_lse2 = IsProcessorFeaturePresent(PF_ARM_LSE2_AVAILABLE); // Large System Extensions version 2, optional from v8.2
bool has_dp = IsProcessorFeaturePresent(PF_ARM_V82_DP_INSTRUCTIONS_AVAILABLE); // DotProd, optional from v8.1 (*)
// ARMv9.0-A
bool has_sve2 = IsProcessorFeaturePresent(PF_ARM_SVE2_INSTRUCTIONS_AVAILABLE); // SVE2
// ARMv9.1-A
// ARMv8.6-A
bool has_bf16 = IsProcessorFeaturePresent(PF_ARM_V86_BF16_INSTRUCTIONS_AVAILABLE); // BF16, optional from v8.2
bool has_i8mm = IsProcessorFeaturePresent(PF_ARM_V82_I8MM_INSTRUCTIONS_AVAILABLE); // Int8 matrix multiply, optional from v8.2
// ARMv8.7-A
bool has_ebf16 = IsProcessorFeaturePresent(PF_ARM_V86_EBF16_INSTRUCTIONS_AVAILABLE); // Extended BFloat16 behaviors, optional from v8.2
// ARMv9.2-A
bool has_sme = IsProcessorFeaturePresent(PF_ARM_SME_INSTRUCTIONS_AVAILABLE); // SME
// ARMv9.3-A
bool has_sme2 = IsProcessorFeaturePresent(PF_ARM_SME2_INSTRUCTIONS_AVAILABLE); // SME2
// ARMv9.4-A
bool has_sme2p1 = IsProcessorFeaturePresent(PF_ARM_SME2_1_INSTRUCTIONS_AVAILABLE); // SME2.1
if (has_sve2 || has_sme)
{
// ARMv9 family
if (has_sme2p1) {
cpu->march = "ARMv9.4-A";
} else if (has_sme2) {
cpu->march = "ARMv9.3-A";
} else if (has_sme) {
cpu->march = "ARMv9.2-A";
} else if (has_i8mm && has_bf16) {
cpu->march = "ARMv9.1-A";
} else {
cpu->march = "ARMv9.0-A";
}
}
else
{
// ARMv8 family
if (has_ebf16) {
cpu->march = "ARMv8.7-A";
} else if (has_i8mm && has_bf16) {
cpu->march = "ARMv8.6-A";
} else if (has_dp) {
cpu->march = "ARMv8.4-A";
} else if (has_lrcpc && has_jscvt) {
cpu->march = "ARMv8.3-A";
} else if (has_fp16) {
cpu->march = "ARMv8.2-A";
} else if (has_atomics && has_crc32) {
cpu->march = "ARMv8.1-A";
} else if (has_neon && has_vfp) {
cpu->march = "ARMv8-A";
}
}
}
#else
void ffCPUDetectByCpuid(FF_MAYBE_UNUSED FFCPUResult* cpu)
{
// Unsupported system
}
#endif
#else
void ffCPUDetectByCpuid(FF_MAYBE_UNUSED FFCPUResult* cpu)
{
// Unsupported architecture
}
#endif
+2 -26
View File
@@ -15,6 +15,7 @@ typedef struct FFCPUResult
{
FFstrbuf name;
FFstrbuf vendor;
const char* march; // Microarchitecture
uint16_t packages;
uint16_t coresPhysical;
@@ -32,29 +33,4 @@ typedef struct FFCPUResult
const char* ffDetectCPU(const FFCPUOptions* options, FFCPUResult* cpu);
const char* ffCPUAppleCodeToName(uint32_t code);
const char* ffCPUQualcommCodeToName(uint32_t code);
#if defined(__x86_64__) || defined(__i386__)
#include <cpuid.h>
// WARNING: CPUID may report frequencies of efficient cores
inline static const char* ffCPUDetectSpeedByCpuid(FFCPUResult* cpu)
{
uint32_t base = 0, max = 0, bus = 0, unused = 0;
if (!__get_cpuid(0x16, &base, &max, &bus, &unused))
return "Unsupported instruction";
// cpuid returns 0 MHz when hyper-v is enabled
if (base) cpu->frequencyBase = base;
if (max) cpu->frequencyMax = max;
return NULL;
}
#else
inline static const char* ffCPUDetectSpeedByCpuid(FF_MAYBE_UNUSED FFCPUResult* cpu)
{
return "Unsupported platform";
}
#endif
void ffCPUDetectByCpuid(FFCPUResult* cpu);
+1
View File
@@ -126,6 +126,7 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu)
if(cpu->coresOnline == 1)
cpu->coresOnline = (uint16_t) ffSysctlGetInt("hw.activecpu", 1);
ffCPUDetectByCpuid(cpu);
detectFrequency(cpu);
if (options->showPeCoreCount) detectCoreCount(cpu);
+1 -1
View File
@@ -70,7 +70,7 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu)
cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, sizeof(cpuset_t), &currentCPU);
#endif
ffCPUDetectSpeedByCpuid(cpu);
ffCPUDetectByCpuid(cpu);
uint32_t clockrate = (uint32_t) ffSysctlGetInt("hw.clockrate", 0);
if (clockrate > cpu->frequencyBase) cpu->frequencyBase = clockrate;
+1 -1
View File
@@ -55,7 +55,7 @@ const char* ffDetectCPUImpl(FF_MAYBE_UNUSED const FFCPUOptions* options, FFCPURe
ffStrbufSetF(&cpu->name, "(Unknown %" B_PRIx32 ")", cpuModel);
ffStrbufSetS(&cpu->vendor, get_cpu_vendor_string(cpuVendor));
ffCPUDetectSpeedByCpuid(cpu);
ffCPUDetectByCpuid(cpu);
if (cpu->frequencyBase < frequency) cpu->frequencyBase = frequency;
cpu->packages = packages;
cpu->coresPhysical = cores;
+110 -62
View File
@@ -13,87 +13,129 @@
#define FF_CPUINFO_PATH "/proc/cpuinfo"
static double parseHwmonDir(FFstrbuf* dir, FFstrbuf* buffer)
static double parseTZDir(int dfd, FFstrbuf* buffer)
{
//https://www.kernel.org/doc/Documentation/hwmon/sysfs-interface
uint32_t dirLength = dir->length;
ffStrbufAppendS(dir, "temp1_input");
if(!ffReadFileBuffer(dir->chars, buffer))
{
// Some badly implemented system put temp file in /hwmonN/device
ffStrbufSubstrBefore(dir, dirLength);
ffStrbufAppendS(dir, "device/");
dirLength = dir->length;
ffStrbufAppendS(dir, "temp1_input");
if(!ffReadFileBuffer(dir->chars, buffer))
return FF_CPU_TEMP_UNSET;
}
ffStrbufSubstrBefore(dir, dirLength);
double value = ffStrbufToDouble(buffer, FF_CPU_TEMP_UNSET);// millidegree Celsius
if(value == FF_CPU_TEMP_UNSET)
if (!ffReadFileBufferRelative(dfd, "type", buffer))
return FF_CPU_TEMP_UNSET;
ffStrbufAppendS(dir, "name");
if (!ffReadFileBuffer(dir->chars, buffer))
if (!ffStrbufStartsWithS(buffer, "cpu") &&
!ffStrbufStartsWithS(buffer, "soc") &&
#if __x86_64__ || __i386__
!ffStrbufEqualS(buffer, "x86_pkg_temp") &&
#endif
true
) return FF_CPU_TEMP_UNSET;
if (!ffReadFileBufferRelative(dfd, "temp", buffer))
return FF_CPU_TEMP_UNSET;
double value = ffStrbufToDouble(buffer, FF_CPU_TEMP_UNSET);// millidegree Celsius
if (value == FF_CPU_TEMP_UNSET)
return FF_CPU_TEMP_UNSET;
return value / 1000.;
}
static double parseHwmonDir(int dfd, FFstrbuf* buffer)
{
if (!ffReadFileBufferRelative(dfd, "name", buffer))
return FF_CPU_TEMP_UNSET;
ffStrbufTrimRightSpace(buffer);
if(
ffStrbufContainS(buffer, "cpu") ||
ffStrbufEqualS(buffer, "k10temp") || // AMD
ffStrbufEqualS(buffer, "fam15h_power") || // AMD
ffStrbufEqualS(buffer, "coretemp") // Intel
) return value / 1000.;
if (
!ffStrbufContainS(buffer, "cpu") &&
#if __x86_64__ || __i386__
!ffStrbufEqualS(buffer, "k10temp") && // AMD
!ffStrbufEqualS(buffer, "fam15h_power") && // AMD
!ffStrbufEqualS(buffer, "coretemp") && // Intel
#endif
true
) return FF_CPU_TEMP_UNSET;
return FF_CPU_TEMP_UNSET;
}
//https://www.kernel.org/doc/Documentation/hwmon/sysfs-interface
if (!ffReadFileBufferRelative(dfd, "temp1_input", buffer))
return FF_CPU_TEMP_UNSET;
static double detectTZTemp(FFstrbuf* buffer)
{
if (ffReadFileBuffer("/sys/class/thermal/thermal_zone0/temp", buffer))
{
double value = ffStrbufToDouble(buffer, FF_CPU_TEMP_UNSET);// millidegree Celsius
return value != FF_CPU_TEMP_UNSET ? value / 1000. : FF_CPU_TEMP_UNSET;
}
return FF_CPU_TEMP_UNSET;
double value = ffStrbufToDouble(buffer, FF_CPU_TEMP_UNSET);// millidegree Celsius
if (value == FF_CPU_TEMP_UNSET)
return FF_CPU_TEMP_UNSET;
return value / 1000.;
}
static double detectCPUTemp(void)
{
FF_STRBUF_AUTO_DESTROY baseDir = ffStrbufCreateA(64);
ffStrbufAppendS(&baseDir, "/sys/class/hwmon/");
FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate();
uint32_t baseDirLength = baseDir.length;
FF_AUTO_CLOSE_DIR DIR* dirp = opendir(baseDir.chars);
if(dirp == NULL)
return FF_CPU_TEMP_UNSET;
struct dirent* entry;
while((entry = readdir(dirp)) != NULL)
{
if(entry->d_name[0] == '.')
continue;
FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/hwmon/");
if(dirp)
{
int dfd = dirfd(dirp);
struct dirent* entry;
while((entry = readdir(dirp)) != NULL)
{
if(entry->d_name[0] == '.')
continue;
ffStrbufAppendS(&baseDir, entry->d_name);
ffStrbufAppendC(&baseDir, '/');
FF_AUTO_CLOSE_FD int subfd = openat(dfd, entry->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if(subfd < 0)
continue;
double result = parseHwmonDir(&baseDir, &buffer);
if (result != FF_CPU_TEMP_UNSET)
return result;
double result = parseHwmonDir(subfd, &buffer);
if (result != FF_CPU_TEMP_UNSET)
return result;
}
}
}
{
FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/thermal/");
if(dirp)
{
int dfd = dirfd(dirp);
struct dirent* entry;
while((entry = readdir(dirp)) != NULL)
{
if(entry->d_name[0] == '.')
continue;
if(!ffStrStartsWith(entry->d_name, "thermal_zone"))
continue;
ffStrbufSubstrBefore(&baseDir, baseDirLength);
FF_AUTO_CLOSE_FD int subfd = openat(dfd, entry->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if(subfd < 0)
continue;
double result = parseTZDir(subfd, &buffer);
if (result != FF_CPU_TEMP_UNSET)
return result;
}
}
}
{
FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/devices/platform/");
if(dirp)
{
int dfd = dirfd(dirp);
struct dirent* entry;
while((entry = readdir(dirp)) != NULL)
{
if(entry->d_name[0] == '.')
continue;
if(!ffStrStartsWith(entry->d_name, "cputemp."))
continue;
FF_AUTO_CLOSE_FD int subfd = openat(dfd, entry->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if(subfd < 0)
continue;
double result = parseHwmonDir(subfd, &buffer);
if (result != FF_CPU_TEMP_UNSET)
return result;
}
}
}
return detectTZTemp(&buffer);
return FF_CPU_TEMP_UNSET;
}
#ifdef __ANDROID__
@@ -311,6 +353,10 @@ static const char* parseCpuInfo(
(cpu->name.length == 0 && ffParsePropLine(line, "processor 0:", &cpu->name)) ||
(cpu->vendor.length == 0 && ffParsePropLine(line, "vendor_id :", &cpu->vendor)) ||
(cpuMHz->length == 0 && ffParsePropLine(line, "cpu MHz static :", cpuMHz)) || // This one cannot be detected because of early return
#elif __ia64__
(cpu->name.length == 0 && ffParsePropLine(line, "model name :", &cpu->name)) ||
(cpu->vendor.length == 0 && ffParsePropLine(line, "vendor :", &cpu->vendor)) ||
(cpuMHz->length == 0 && ffParsePropLine(line, "cpu MHz :", cpuMHz)) ||
#else
(cpu->name.length == 0 && ffParsePropLine(line, "model name :", &cpu->name)) ||
(cpu->name.length == 0 && ffParsePropLine(line, "model :", &cpu->name)) ||
@@ -456,7 +502,7 @@ FF_MAYBE_UNUSED static const char* detectCPUX86(const FFCPUOptions* options, FFC
cpu->coresPhysical *= cpu->packages;
// Ref https://github.com/fastfetch-cli/fastfetch/issues/1194#issuecomment-2295058252
ffCPUDetectSpeedByCpuid(cpu);
ffCPUDetectByCpuid(cpu);
if (!detectFrequency(cpu, options) || cpu->frequencyBase == 0)
cpu->frequencyBase = (uint32_t) ffStrbufToUInt(&cpuMHz, 0);
@@ -734,6 +780,8 @@ FF_MAYBE_UNUSED static const char* detectCPUOthers(const FFCPUOptions* options,
if (cpu->coresPhysical == 0)
detectPhysicalCores(cpu);
ffCPUDetectByCpuid(cpu);
return NULL;
}
#endif
+1 -1
View File
@@ -64,7 +64,7 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu)
cpu->coresLogical = cpu->coresPhysical;
cpu->coresOnline = (uint16_t) ffSysctlGetInt("hw.ncpuonline", cpu->coresLogical);
ffCPUDetectSpeedByCpuid(cpu);
ffCPUDetectByCpuid(cpu);
uint32_t freq = (uint32_t) ffSysctlGetInt("machdep.cpu.frequency.target", 0);
if (freq == 0) freq = (uint32_t) (ffSysctlGetInt64("hw.cpu0.clock_frequency", 0) / 1000000);
+1 -1
View File
@@ -56,7 +56,7 @@ const char *ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu)
cpu->coresLogical = cpu->coresPhysical;
cpu->coresOnline = (uint16_t) ffSysctlGetInt(CTL_HW, HW_NCPUONLINE, cpu->coresLogical);
ffCPUDetectSpeedByCpuid(cpu);
ffCPUDetectByCpuid(cpu);
uint32_t cpuspeed = (uint32_t) ffSysctlGetInt(CTL_HW, HW_CPUSPEED, 0);
if (cpuspeed > cpu->frequencyBase) cpu->frequencyBase = cpuspeed;
+1 -1
View File
@@ -122,7 +122,7 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu)
kstat_named_t* kn = kstat_data_lookup(ks, "vendor_id");
if (kn) ffStrbufSetNS(&cpu->vendor, KSTAT_NAMED_STR_BUFLEN(kn) - 1, KSTAT_NAMED_STR_PTR(kn));
}
ffCPUDetectSpeedByCpuid(cpu);
ffCPUDetectByCpuid(cpu);
{
kstat_named_t* kn = kstat_data_lookup(ks, "clock_MHz");
if (kn && kn->value.ui32 > cpu->frequencyBase)
+1 -1
View File
@@ -287,7 +287,7 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu)
if (error)
return error;
ffCPUDetectSpeedByCpuid(cpu);
ffCPUDetectByCpuid(cpu);
if (options->showPeCoreCount) detectCoreTypes(cpu);
if (cpu->frequencyMax == 0)
+1
View File
@@ -54,6 +54,7 @@ retry:
ffTimeSleep(options->waitTime);
goto retry;
}
return "CPU time did not increase. Try increasing wait time.";
}
}
+43 -1
View File
@@ -6,8 +6,9 @@
#include "common/parsing.h"
#include "common/properties.h"
#include "common/processing.h"
#include "util/binary.h"
#include "util/path.h"
#include "detection/displayserver/displayserver.h"
#include "util/stringUtils.h"
#include <ctype.h>
#ifdef __FreeBSD__
@@ -195,6 +196,45 @@ static void getUnity(FFstrbuf* result, FF_MAYBE_UNUSED FFDEOptions* options)
ffStrbufSubstrBeforeFirstC(result, '"');
}
static bool extractTdeVersion(const char* line, uint32_t len, void *userdata)
{
int count = 0;
sscanf(line, "R%*d.%*d.%*d%n", &count);
if (count == 0) return true;
ffStrbufSetNS((FFstrbuf*) userdata, len, line);
return false;
}
static const char* getTrinity(FFstrbuf* result, FFDEOptions* options)
{
FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate();
const char* error = ffFindExecutableInPath("tde-config", &path);
if (error) return "Failed to find tde-config path";
ffStrbufSubstrBeforeLastC(&path, '/');
ffStrbufAppendS(&path, "/../lib/libtdecore.so");
if (ffBinaryExtractStrings(path.chars, extractTdeVersion, result, strlen("R0.0.0")) == NULL)
return NULL;
if (options->slowVersionDetection)
{
ffStrbufClear(&path);
ffProcessAppendStdOut(&path, (char* const[]){
"tde-config",
"--version",
NULL
});
ffParsePropLines(path.chars , "TDE: ", result);
return NULL;
}
return "All methods failed";
}
const char* ffDetectDEVersion(const FFstrbuf* deName, FFstrbuf* result, FFDEOptions* options)
{
if (!instance.config.general.detectVersion) return "Disabled by config";
@@ -215,6 +255,8 @@ const char* ffDetectDEVersion(const FFstrbuf* deName, FFstrbuf* result, FFDEOpti
getBudgie(result, options);
else if (ffStrbufEqualS(deName, FF_DE_PRETTY_UNITY))
getUnity(result, options);
else if (ffStrbufEqualS(deName, "trinity"))
getTrinity(result, options);
else
return "Unsupported DE";
return NULL;
-1
View File
@@ -9,7 +9,6 @@
#include <mntent.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/mount.h>
#ifdef __USE_LARGEFILE64
#define stat stat64
+2 -2
View File
@@ -23,8 +23,8 @@ static const char* parseDiskIOCounters(int dfd, const char* devName, FFlist* res
ffStrbufAppendC(&name, ' ');
}
if (ffAppendFileBufferRelative(devfd, "model", &name))
ffStrbufTrimRightSpace(&name);
ffAppendFileBufferRelative(devfd, "model", &name);
ffStrbufTrimRightSpace(&name);
if (name.length == 0)
ffStrbufSetS(&name, devName);
@@ -44,6 +44,7 @@
#define FF_WM_PROTOCOL_TTY "TTY"
#define FF_WM_PROTOCOL_X11 "X11"
#define FF_WM_PROTOCOL_WAYLAND "Wayland"
#define FF_WM_PROTOCOL_SURFACEFLINGER "SurfaceFlinger"
typedef enum __attribute__((__packed__)) FFDisplayType {
FF_DISPLAY_TYPE_UNKNOWN,
@@ -1,6 +1,7 @@
#include "displayserver.h"
#include "common/settings.h"
#include "common/processing.h"
#include "linux/displayserver_linux.h"
#include <math.h>
@@ -82,13 +83,10 @@ static void detectWithDumpsys(FFDisplayServerResult* ds)
ffStrbufRecalculateLength(&name);
FFDisplayResult* display = ffdsAppendDisplay(ds,
(uint32_t)width,
(uint32_t)height,
(uint32_t)width, (uint32_t)height,
refreshRate,
0,
0,
0,
0,
0, 0,
0, 0,
0,
0,
&name,
@@ -121,13 +119,10 @@ static bool detectWithGetprop(FFDisplayServerResult* ds)
ffStrbufSubstrAfterFirstC(&buffer, ',');
double scaleFactor = (double) ffStrbufToUInt(&buffer, 0) / 160.;
FFDisplayResult* display = ffdsAppendDisplay(ds,
width,
height,
0,
(uint32_t) (width / scaleFactor + .5),
(uint32_t) (height / scaleFactor + .5),
0,
width, height,
0,
(uint32_t) (width / scaleFactor + .5), (uint32_t) (height / scaleFactor + .5),
0, 0,
0,
0,
NULL,
@@ -147,8 +142,19 @@ static bool detectWithGetprop(FFDisplayServerResult* ds)
void ffConnectDisplayServerImpl(FFDisplayServerResult* ds)
{
ffStrbufSetStatic(&ds->wmProcessName, "WindowManager");
ffStrbufSetStatic(&ds->wmPrettyName, "Window Manager");
const char* error = ffdsConnectXcbRandr(ds);
if (error)
error = ffdsConnectXrandr(ds);
if (!error)
{
ffdsDetectWMDE(ds);
return;
}
// https://source.android.com/docs/core/graphics/surfaceflinger-windowmanager
ffStrbufSetStatic(&ds->wmProcessName, "system_server");
ffStrbufSetStatic(&ds->wmPrettyName, "WindowManager"); // A system service managed by system_server
ffStrbufSetStatic(&ds->wmProtocolName, FF_WM_PROTOCOL_SURFACEFLINGER);
if (!detectWithGetprop(ds))
detectWithDumpsys(ds);
@@ -0,0 +1,16 @@
#include "displayserver_linux.h"
#include "util/stringUtils.h"
FFDisplayType ffdsGetDisplayType(const char* name)
{
if(ffStrStartsWith(name, "eDP-") || ffStrStartsWith(name, "LVDS-"))
return FF_DISPLAY_TYPE_BUILTIN;
else if(ffStrStartsWith(name, "HDMI-") ||
ffStrStartsWith(name, "DP-") ||
ffStrStartsWith(name, "DisplayPort-") ||
ffStrStartsWith(name, "DVI-") ||
ffStrStartsWith(name, "VGA-"))
return FF_DISPLAY_TYPE_EXTERNAL;
return FF_DISPLAY_TYPE_UNKNOWN;
}
@@ -95,17 +95,3 @@ void ffConnectDisplayServerImpl(FFDisplayServerResult* ds)
ffdsDetectWMDE(ds);
}
}
FFDisplayType ffdsGetDisplayType(const char* name)
{
if(ffStrStartsWith(name, "eDP-") || ffStrStartsWith(name, "LVDS-"))
return FF_DISPLAY_TYPE_BUILTIN;
else if(ffStrStartsWith(name, "HDMI-") ||
ffStrStartsWith(name, "DP-") ||
ffStrStartsWith(name, "DisplayPort-") ||
ffStrStartsWith(name, "DVI-") ||
ffStrStartsWith(name, "VGA-"))
return FF_DISPLAY_TYPE_EXTERNAL;
return FF_DISPLAY_TYPE_UNKNOWN;
}
+3 -6
View File
@@ -396,13 +396,10 @@ static const char* drmConnectLibdrm(FFDisplayServerResult* result)
}
FFDisplayResult* item = ffdsAppendDisplay(result,
width,
height,
width, height,
refreshRate,
0,
0,
preferredWidth,
preferredHeight,
0, 0,
preferredWidth, preferredHeight,
preferredRefreshRate,
0,
&name,
@@ -128,8 +128,8 @@ const char* ffWaylandHandleGlobalOutput(WaylandData* wldata, struct wl_registry*
(uint32_t) display.width,
(uint32_t) display.height,
display.refreshRate / 1000.0,
(uint32_t) (display.width / display.scale),
(uint32_t) (display.height / display.scale),
(uint32_t) (display.width / display.scale + .5),
(uint32_t) (display.height / display.scale + .5),
(uint32_t) display.preferredWidth,
(uint32_t) display.preferredHeight,
display.preferredRefreshRate / 1000.0,
@@ -1,4 +1,4 @@
/* Generated by wayland-scanner 1.23.1 */
/* Generated by wayland-scanner 1.24.0 */
#ifndef KDE_OUTPUT_DEVICE_V2_CLIENT_PROTOCOL_H
#define KDE_OUTPUT_DEVICE_V2_CLIENT_PROTOCOL_H
@@ -234,6 +234,11 @@ enum kde_output_device_v2_capability {
* @since 16
*/
KDE_OUTPUT_DEVICE_V2_CAPABILITY_EDR = 0x800,
/**
* if this outputdevice supports the sharpness setting
* @since 17
*/
KDE_OUTPUT_DEVICE_V2_CAPABILITY_SHARPNESS = 0x1000,
};
/**
* @ingroup iface_kde_output_device_v2
@@ -271,6 +276,10 @@ enum kde_output_device_v2_capability {
* @ingroup iface_kde_output_device_v2
*/
#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_EDR_SINCE_VERSION 16
/**
* @ingroup iface_kde_output_device_v2
*/
#define KDE_OUTPUT_DEVICE_V2_CAPABILITY_SHARPNESS_SINCE_VERSION 17
#endif /* KDE_OUTPUT_DEVICE_V2_CAPABILITY_ENUM */
#ifndef KDE_OUTPUT_DEVICE_V2_VRR_POLICY_ENUM
@@ -774,6 +783,17 @@ struct kde_output_device_v2_listener {
void (*edr_policy)(void *data,
struct kde_output_device_v2 *kde_output_device_v2,
uint32_t policy);
/**
* sharpness strength
*
* This is the sharpness modifier of the output. 0 is sharpness
* disabled and 10000 is the maximum sharpness
* @param sharpness sharpness in 0-10000
* @since 17
*/
void (*sharpness)(void *data,
struct kde_output_device_v2 *kde_output_device_v2,
uint32_t sharpness);
};
/**
@@ -919,6 +939,10 @@ kde_output_device_v2_add_listener(struct kde_output_device_v2 *kde_output_device
* @ingroup iface_kde_output_device_v2
*/
#define KDE_OUTPUT_DEVICE_V2_EDR_POLICY_SINCE_VERSION 16
/**
* @ingroup iface_kde_output_device_v2
*/
#define KDE_OUTPUT_DEVICE_V2_SHARPNESS_SINCE_VERSION 17
/** @ingroup iface_kde_output_device_v2 */
@@ -1,6 +1,6 @@
#ifdef FF_HAVE_WAYLAND
/* Generated by wayland-scanner 1.23.1 */
/* Generated by wayland-scanner 1.24.0 */
/*
* SPDX-FileCopyrightText: 2008-2011 Kristian Høgsberg
@@ -66,12 +66,13 @@ static const struct wl_message kde_output_device_v2_events[] = {
{ "max_bits_per_color_range", "15uu", kde_output_device_v2_types + 0 },
{ "automatic_max_bits_per_color_limit", "15u", kde_output_device_v2_types + 0 },
{ "edr_policy", "16u", kde_output_device_v2_types + 0 },
{ "sharpness", "17u", kde_output_device_v2_types + 0 },
};
WL_EXPORT const struct wl_interface kde_output_device_v2_interface = {
"kde_output_device_v2", 16,
"kde_output_device_v2", 17,
0, NULL,
33, kde_output_device_v2_events,
34, kde_output_device_v2_events,
};
static const struct wl_message kde_output_device_mode_v2_events[] = {
@@ -177,6 +177,7 @@ static struct kde_output_device_v2_listener outputListener = {
.max_bits_per_color_range = (void*) stubListener,
.automatic_max_bits_per_color_limit = (void*) stubListener,
.edr_policy = (void*) stubListener,
.sharpness = (void*) stubListener,
};
const char* ffWaylandHandleKdeOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version)
@@ -219,8 +220,8 @@ const char* ffWaylandHandleKdeOutput(WaylandData* wldata, struct wl_registry* re
(uint32_t) display.width,
(uint32_t) display.height,
display.refreshRate / 1000.0,
(uint32_t) (display.width / display.scale),
(uint32_t) (display.height / display.scale),
(uint32_t) (display.width / display.scale + .5),
(uint32_t) (display.height / display.scale + .5),
(uint32_t) display.preferredWidth,
(uint32_t) display.preferredHeight,
display.preferredRefreshRate / 1000.0,
@@ -26,9 +26,9 @@
static bool waylandDetectWM(int fd, FFDisplayServerResult* result)
{
#if __linux__ || (__FreeBSD__ && !__DragonFly__)
#if __linux__ || __GNU__ || (__FreeBSD__ && !__DragonFly__)
#if __linux
#if __linux__ || __GNU__
struct ucred ucred = {};
socklen_t len = sizeof(ucred);
if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == -1 || ucred.pid <= 0)
+7 -2
View File
@@ -65,7 +65,7 @@ static const char* parseEnv(void)
if(getenv("SWAYSOCK") != NULL)
return "Sway";
#ifdef __linux__
#if __linux__ && !__ANDROID__
if(
getenv("WAYLAND_DISPLAY") != NULL &&
ffPathExists("/mnt/wslg/", FF_PATHTYPE_DIRECTORY)
@@ -351,7 +351,7 @@ static const char* getFromProcesses(FFDisplayServerResult* result)
break;
}
}
#elif __linux__
#elif __linux__ || __GNU__
FF_AUTO_CLOSE_DIR DIR* procdir = opendir("/proc");
if(procdir == NULL)
return "opendir(\"/proc\") failed";
@@ -433,6 +433,11 @@ static const char* getFromProcesses(FFDisplayServerResult* result)
void ffdsDetectWMDE(FFDisplayServerResult* result)
{
#if __ANDROID__
if(ffStrbufIgnCaseEqualS(&result->wmProtocolName, FF_WM_PROTOCOL_SURFACEFLINGER))
return; // Only supported when connected to X11
#endif
const char* env = parseEnv();
if(result->wmProcessName.length > 0)
+104 -104
View File
@@ -3,7 +3,7 @@
#ifdef FF_HAVE_XCB_RANDR
#include "common/library.h"
#include "common/time.h"
#include "common/properties.h"
#include "util/edidHelper.h"
#include "util/mallocHelper.h"
#include "util/stringUtils.h"
@@ -56,7 +56,7 @@ static void* xcbGetProperty(XcbPropertyData* data, xcb_connection_t* connection,
if(requestAtomReply == NULL)
return NULL;
xcb_get_property_cookie_t propertyCookie = data->ffxcb_get_property(connection, false, window, requestAtomReply->atom, XCB_ATOM_ANY, 0, 64);
xcb_get_property_cookie_t propertyCookie = data->ffxcb_get_property(connection, false, window, requestAtomReply->atom, XCB_ATOM_ANY, 0, 8 * 1024);
FF_AUTO_FREE xcb_get_property_reply_t* propertyReply = data->ffxcb_get_property_reply(connection, propertyCookie, NULL);
if(propertyReply == NULL)
@@ -83,11 +83,11 @@ static void xcbDetectWMfromEWMH(XcbPropertyData* data, xcb_connection_t* connect
if(wmWindow == NULL)
return;
FF_AUTO_FREE char* wmName = (char*) xcbGetProperty(data, connection, *wmWindow, "_NET_WM_NAME");
if(wmName == NULL)
wmName = (char*) xcbGetProperty(data, connection, *wmWindow, "WM_NAME");
FF_AUTO_FREE char* wmName = (char*) xcbGetProperty(data, connection, *wmWindow, "WM_NAME");
if(!ffStrSet(wmName))
wmName = (char*) xcbGetProperty(data, connection, *wmWindow, "_NET_WM_NAME");
if(wmName == NULL || *wmName == '\0')
if(!ffStrSet(wmName))
return;
ffStrbufSetS(&result->wmProcessName, wmName);
@@ -138,86 +138,9 @@ typedef struct XcbRandrData
xcb_connection_t* connection;
FFDisplayServerResult* result;
XcbPropertyData propData;
//init per screen
xcb_randr_get_screen_resources_current_reply_t* screenResources;
} XcbRandrData;
static bool xcbRandrHandleCrtc(XcbRandrData* data, xcb_randr_crtc_t crtc, FFstrbuf* name, bool primary, xcb_randr_get_output_info_reply_t* output, FFDisplayType displayType, uint8_t* edidData, uint32_t edidLength)
{
xcb_randr_get_crtc_info_cookie_t crtcInfoCookie = data->ffxcb_randr_get_crtc_info(data->connection, crtc, XCB_CURRENT_TIME);
FF_AUTO_FREE xcb_randr_get_crtc_info_reply_t* crtcInfoReply = data->ffxcb_randr_get_crtc_info_reply(data->connection, crtcInfoCookie, NULL);
if(crtcInfoReply == NULL)
return false;
uint32_t rotation;
switch (crtcInfoReply->rotation)
{
case XCB_RANDR_ROTATION_ROTATE_90:
rotation = 90;
break;
case XCB_RANDR_ROTATION_ROTATE_180:
rotation = 180;
break;
case XCB_RANDR_ROTATION_ROTATE_270:
rotation = 270;
break;
default:
rotation = 0;
break;
}
xcb_randr_mode_info_t* currentMode = NULL;
xcb_randr_mode_info_t* preferredMode = NULL;
if(data->screenResources)
{
xcb_randr_mode_info_iterator_t modesIterator = data->ffxcb_randr_get_screen_resources_current_modes_iterator(data->screenResources);
if (output->num_preferred > 0)
preferredMode = modesIterator.data;
while (modesIterator.rem > 0)
{
if (modesIterator.data->id == crtcInfoReply->mode)
{
currentMode = modesIterator.data;
break;
}
data->ffxcb_randr_mode_info_next(&modesIterator);
}
}
FFDisplayResult* item = ffdsAppendDisplay(
data->result,
(uint32_t) crtcInfoReply->width,
(uint32_t) crtcInfoReply->height,
currentMode ? (double) currentMode->dot_clock / (double) ((uint32_t) currentMode->htotal * currentMode->vtotal) : 0,
(uint32_t) crtcInfoReply->width,
(uint32_t) crtcInfoReply->height,
preferredMode ? (uint32_t) preferredMode->width : 0,
preferredMode ? (uint32_t) preferredMode->height : 0,
preferredMode ? (double) preferredMode->dot_clock / (double) ((uint32_t) preferredMode->htotal * preferredMode->vtotal) : 0,
rotation,
name,
displayType,
primary,
0,
(uint32_t) output->mm_width,
(uint32_t) output->mm_height,
"xcb-randr-crtc"
);
if (item && edidLength)
{
item->hdrStatus = ffEdidGetHdrCompatible(edidData, (uint32_t) edidLength) ? FF_DISPLAY_HDR_STATUS_SUPPORTED : FF_DISPLAY_HDR_STATUS_UNSUPPORTED;
ffEdidGetSerialAndManufactureDate(edidData, &item->serial, &item->manufactureYear, &item->manufactureWeek);
}
return !!item;
}
static bool xcbRandrHandleOutput(XcbRandrData* data, xcb_randr_output_t output, FFstrbuf* name, bool primary, FFDisplayType displayType)
static bool xcbRandrHandleOutput(XcbRandrData* data, xcb_randr_output_t output, FFstrbuf* name, bool primary, FFDisplayType displayType, struct xcb_randr_get_screen_resources_current_reply_t* screenResources, uint8_t bitDepth, double scaleFactor)
{
xcb_randr_get_output_info_cookie_t outputInfoCookie = data->ffxcb_randr_get_output_info(data->connection, output, XCB_CURRENT_TIME);
FF_AUTO_FREE xcb_randr_get_output_info_reply_t* outputInfoReply = data->ffxcb_randr_get_output_info_reply(data->connection, outputInfoCookie, NULL);
@@ -246,12 +169,80 @@ static bool xcbRandrHandleOutput(XcbRandrData* data, xcb_randr_output_t output,
}
}
bool res = xcbRandrHandleCrtc(data, outputInfoReply->crtc, name, primary, outputInfoReply, displayType, edidData, edidLength);
xcb_randr_get_crtc_info_cookie_t crtcInfoCookie = data->ffxcb_randr_get_crtc_info(data->connection, outputInfoReply->crtc, XCB_CURRENT_TIME);
FF_AUTO_FREE xcb_randr_get_crtc_info_reply_t* crtcInfoReply = data->ffxcb_randr_get_crtc_info_reply(data->connection, crtcInfoCookie, NULL);
if(crtcInfoReply == NULL)
return false;
return res;
uint32_t rotation;
switch (crtcInfoReply->rotation)
{
case XCB_RANDR_ROTATION_ROTATE_90:
rotation = 90;
break;
case XCB_RANDR_ROTATION_ROTATE_180:
rotation = 180;
break;
case XCB_RANDR_ROTATION_ROTATE_270:
rotation = 270;
break;
default:
rotation = 0;
break;
}
xcb_randr_mode_info_t* currentMode = NULL;
xcb_randr_mode_info_t* preferredMode = NULL;
if(screenResources)
{
xcb_randr_mode_info_iterator_t modesIterator = data->ffxcb_randr_get_screen_resources_current_modes_iterator(screenResources);
if (outputInfoReply->num_preferred > 0)
preferredMode = modesIterator.data;
while (modesIterator.rem > 0)
{
if (modesIterator.data->id == crtcInfoReply->mode)
{
currentMode = modesIterator.data;
break;
}
data->ffxcb_randr_mode_info_next(&modesIterator);
}
}
FFDisplayResult* item = ffdsAppendDisplay(
data->result,
(uint32_t) crtcInfoReply->width,
(uint32_t) crtcInfoReply->height,
currentMode ? (double) currentMode->dot_clock / (double) ((uint32_t) currentMode->htotal * currentMode->vtotal) : 0,
(uint32_t) (crtcInfoReply->width / scaleFactor + .5),
(uint32_t) (crtcInfoReply->height / scaleFactor + .5),
preferredMode ? (uint32_t) preferredMode->width : 0,
preferredMode ? (uint32_t) preferredMode->height : 0,
preferredMode ? (double) preferredMode->dot_clock / (double) ((uint32_t) preferredMode->htotal * preferredMode->vtotal) : 0,
rotation,
name,
displayType,
primary,
0,
(uint32_t) outputInfoReply->mm_width,
(uint32_t) outputInfoReply->mm_height,
"xcb-randr-crtc"
);
if (item && edidLength)
{
item->hdrStatus = ffEdidGetHdrCompatible(edidData, (uint32_t) edidLength) ? FF_DISPLAY_HDR_STATUS_SUPPORTED : FF_DISPLAY_HDR_STATUS_UNSUPPORTED;
ffEdidGetSerialAndManufactureDate(edidData, &item->serial, &item->manufactureYear, &item->manufactureWeek);
item->bitDepth = bitDepth;
}
return !!item;
}
static bool xcbRandrHandleMonitor(XcbRandrData* data, xcb_randr_monitor_info_t* monitor)
static bool xcbRandrHandleMonitor(XcbRandrData* data, xcb_randr_monitor_info_t* monitor, struct xcb_randr_get_screen_resources_current_reply_t* screenResources, uint8_t bitDepth, double scaleFactor)
{
//for some reasons, we have to construct this our self
xcb_randr_output_iterator_t outputIterator = {
@@ -275,18 +266,20 @@ static bool xcbRandrHandleMonitor(XcbRandrData* data, xcb_randr_monitor_info_t*
while(outputIterator.rem > 0)
{
if(xcbRandrHandleOutput(data, *outputIterator.data, &name, monitor->primary, displayType))
if(xcbRandrHandleOutput(data, *outputIterator.data, &name, monitor->primary, displayType, screenResources, bitDepth, scaleFactor))
foundOutput = true;
data->ffxcb_randr_output_next(&outputIterator);
};
}
return foundOutput ? true : !!ffdsAppendDisplay(
if (foundOutput) return true;
FFDisplayResult* display = ffdsAppendDisplay(
data->result,
(uint32_t) monitor->width,
(uint32_t) monitor->height,
0,
(uint32_t) monitor->width,
(uint32_t) monitor->height,
(uint32_t) (monitor->width / scaleFactor + .5),
(uint32_t) (monitor->height / scaleFactor + .5),
0, 0, 0,
0,
&name,
@@ -297,6 +290,8 @@ static bool xcbRandrHandleMonitor(XcbRandrData* data, xcb_randr_monitor_info_t*
(uint32_t) monitor->height_in_millimeters,
"xcb-randr-monitor"
);
if (display) display->bitDepth = bitDepth;
return !!display;
}
static bool xcbRandrHandleMonitors(XcbRandrData* data, xcb_screen_t* screen)
@@ -306,13 +301,27 @@ static bool xcbRandrHandleMonitors(XcbRandrData* data, xcb_screen_t* screen)
if(monitorsReply == NULL)
return false;
//Init screen resources. They are used to iterate over all modes. xcbRandrHandleMode checks for " == NULL", to fail as late as possible.
xcb_randr_get_screen_resources_current_cookie_t screenResourcesCookie = data->ffxcb_randr_get_screen_resources_current(data->connection, screen->root);
FF_AUTO_FREE struct xcb_randr_get_screen_resources_current_reply_t* screenResources = data->ffxcb_randr_get_screen_resources_current_reply(data->connection, screenResourcesCookie, NULL);
double scaleFactor = 1;
FF_AUTO_FREE const char* resourceManager = xcbGetProperty(&data->propData, data->connection, screen->root, "RESOURCE_MANAGER");
if (resourceManager)
{
FF_STRBUF_AUTO_DESTROY dpi = ffStrbufCreate();
if (ffParsePropLines(resourceManager, "Xft.dpi:", &dpi))
scaleFactor = ffStrbufToDouble(&dpi, 96) / 96;
}
uint8_t bitDepth = (uint8_t) (screen->root_depth / 3);
xcb_randr_monitor_info_iterator_t monitorInfoIterator = data->ffxcb_randr_get_monitors_monitors_iterator(monitorsReply);
bool foundMonitor = false;
while(monitorInfoIterator.rem > 0)
{
if(xcbRandrHandleMonitor(data, monitorInfoIterator.data))
if(xcbRandrHandleMonitor(data, monitorInfoIterator.data, screenResources, bitDepth, scaleFactor))
foundMonitor = true;
data->ffxcb_randr_monitor_info_next(&monitorInfoIterator);
}
@@ -322,17 +331,8 @@ static bool xcbRandrHandleMonitors(XcbRandrData* data, xcb_screen_t* screen)
static void xcbRandrHandleScreen(XcbRandrData* data, xcb_screen_t* screen)
{
//Init screen resources. They are used to iterate over all modes. xcbRandrHandleMode checks for " == NULL", to fail as late as possible.
xcb_randr_get_screen_resources_current_cookie_t screenResourcesCookie = data->ffxcb_randr_get_screen_resources_current(data->connection, screen->root);
data->screenResources = data->ffxcb_randr_get_screen_resources_current_reply(data->connection, screenResourcesCookie, NULL);
//With all the initialisation done, start the detection
bool ret = xcbRandrHandleMonitors(data, screen);
free(data->screenResources);
if(ret)
if(xcbRandrHandleMonitors(data, screen))
return;
//If detetction failed, fallback to screen = monitor, like in the libxcb.so implementation
@@ -348,7 +348,7 @@ static void xcbRandrHandleScreen(XcbRandrData* data, xcb_screen_t* screen)
NULL,
FF_DISPLAY_TYPE_UNKNOWN,
false,
0,
(uint64_t) screen->root,
(uint32_t) screen->width_in_millimeters,
(uint32_t) screen->height_in_millimeters,
"xcb-randr-screen"
+52 -43
View File
@@ -3,7 +3,7 @@
#ifdef FF_HAVE_XRANDR
#include "common/library.h"
#include "common/parsing.h"
#include "common/properties.h"
#include "util/edidHelper.h"
#include "util/stringUtils.h"
@@ -53,9 +53,9 @@ static void x11DetectWMFromEWMH(X11PropertyData* data, Display* display, FFDispl
if(wmWindow == NULL)
return;
char* wmName = (char*) x11GetProperty(data, display, *wmWindow, "_NET_WM_NAME");
if(wmName == NULL)
wmName = (char*) x11GetProperty(data, display, *wmWindow, "WM_NAME");
char* wmName = (char*) x11GetProperty(data, display, *wmWindow, "WM_NAME");
if(!ffStrSet(wmName))
wmName = (char*) x11GetProperty(data, display, *wmWindow, "_NET_WM_NAME");
if(ffStrSet(wmName))
ffStrbufSetS(&result->wmProcessName, wmName);
@@ -70,8 +70,6 @@ static void x11FetchServerVendor(X11PropertyData* data, Display* display, FFDisp
if (serverVendor && !ffStrEquals(serverVendor, "The X.Org Foundation")) {
ffStrbufSetS(&result->wmProtocolName, serverVendor);
}
}
typedef struct XrandrData
@@ -92,18 +90,16 @@ typedef struct XrandrData
//Init once
Display* display;
FFDisplayServerResult* result;
//Init per screen
XRRScreenResources* screenResources;
X11PropertyData* propData;
} XrandrData;
static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf* name, bool primary, FFDisplayType displayType, uint8_t* edidData, uint32_t edidLength)
static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf* name, bool primary, FFDisplayType displayType, uint8_t* edidData, uint32_t edidLength, XRRScreenResources* screenResources, uint8_t bitDepth, double scaleFactor)
{
//We do the check here, because we want the best fallback display if this call failed
if(data->screenResources == NULL)
if(screenResources == NULL)
return false;
XRRCrtcInfo* crtcInfo = data->ffXRRGetCrtcInfo(data->display, data->screenResources, output->crtc);
XRRCrtcInfo* crtcInfo = data->ffXRRGetCrtcInfo(data->display, screenResources, output->crtc);
if(crtcInfo == NULL)
return false;
@@ -125,27 +121,24 @@ static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf*
}
XRRModeInfo* currentMode = NULL;
if (data->screenResources)
for(int i = 0; i < screenResources->nmode; i++)
{
for(int i = 0; i < data->screenResources->nmode; i++)
if(screenResources->modes[i].id == crtcInfo->mode)
{
if(data->screenResources->modes[i].id == crtcInfo->mode)
{
currentMode = &data->screenResources->modes[i];
break;
}
currentMode = &screenResources->modes[i];
break;
}
}
XRRModeInfo* preferredMode = data->screenResources && output->npreferred > 0 ? &data->screenResources->modes[0] : NULL;
XRRModeInfo* preferredMode = output->npreferred > 0 ? &screenResources->modes[0] : NULL;
FFDisplayResult* item = ffdsAppendDisplay(
data->result,
(uint32_t) crtcInfo->width,
(uint32_t) crtcInfo->height,
currentMode ? (double) currentMode->dotClock / (double) ((uint32_t) currentMode->hTotal * currentMode->vTotal) : 0,
(uint32_t) crtcInfo->width,
(uint32_t) crtcInfo->height,
(uint32_t) (crtcInfo->width / scaleFactor + .5),
(uint32_t) (crtcInfo->height / scaleFactor + .5),
preferredMode ? (uint32_t) preferredMode->width : 0,
preferredMode ? (uint32_t) preferredMode->height : 0,
preferredMode ? (double) preferredMode->dotClock / (double) ((uint32_t) preferredMode->hTotal * preferredMode->vTotal) : 0,
@@ -159,19 +152,23 @@ static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf*
"xlib-randr-crtc"
);
if (item && edidLength)
if (item)
{
item->hdrStatus = ffEdidGetHdrCompatible(edidData, edidLength) ? FF_DISPLAY_HDR_STATUS_SUPPORTED : FF_DISPLAY_HDR_STATUS_UNSUPPORTED;
ffEdidGetSerialAndManufactureDate(edidData, &item->serial, &item->manufactureYear, &item->manufactureWeek);
if (edidLength)
{
item->hdrStatus = ffEdidGetHdrCompatible(edidData, edidLength) ? FF_DISPLAY_HDR_STATUS_SUPPORTED : FF_DISPLAY_HDR_STATUS_UNSUPPORTED;
ffEdidGetSerialAndManufactureDate(edidData, &item->serial, &item->manufactureYear, &item->manufactureWeek);
}
item->bitDepth = bitDepth;
}
data->ffXRRFreeCrtcInfo(crtcInfo);
return !!item;
}
static bool xrandrHandleOutput(XrandrData* data, RROutput output, FFstrbuf* name, bool primary, FFDisplayType displayType)
static bool xrandrHandleOutput(XrandrData* data, RROutput output, FFstrbuf* name, bool primary, FFDisplayType displayType, XRRScreenResources* screenResources, uint8_t bitDepth, double scaleFactor)
{
XRROutputInfo* outputInfo = data->ffXRRGetOutputInfo(data->display, data->screenResources, output);
XRROutputInfo* outputInfo = data->ffXRRGetOutputInfo(data->display, screenResources, output);
if(outputInfo == NULL)
return false;
@@ -195,7 +192,7 @@ static bool xrandrHandleOutput(XrandrData* data, RROutput output, FFstrbuf* name
}
}
bool res = xrandrHandleCrtc(data, outputInfo, name, primary, displayType, edidData, (uint32_t) edidLength);
bool res = xrandrHandleCrtc(data, outputInfo, name, primary, displayType, edidData, (uint32_t) edidLength, screenResources, bitDepth, scaleFactor);
if (edidData)
data->ffXFree(edidData);
@@ -204,7 +201,7 @@ static bool xrandrHandleOutput(XrandrData* data, RROutput output, FFstrbuf* name
return res;
}
static bool xrandrHandleMonitor(XrandrData* data, XRRMonitorInfo* monitorInfo)
static bool xrandrHandleMonitor(XrandrData* data, XRRMonitorInfo* monitorInfo, XRRScreenResources* screenResources, uint8_t bitDepth, double scaleFactor)
{
bool foundOutput = false;
char* xname = data->ffXGetAtomName(data->display, monitorInfo->name);
@@ -213,17 +210,19 @@ static bool xrandrHandleMonitor(XrandrData* data, XRRMonitorInfo* monitorInfo)
FFDisplayType displayType = ffdsGetDisplayType(name.chars);
for(int i = 0; i < monitorInfo->noutput; i++)
{
if(xrandrHandleOutput(data, monitorInfo->outputs[i], &name, monitorInfo->primary, displayType))
if(xrandrHandleOutput(data, monitorInfo->outputs[i], &name, monitorInfo->primary, displayType, screenResources, bitDepth, scaleFactor))
foundOutput = true;
}
return foundOutput ? true : !!ffdsAppendDisplay(
if (foundOutput) return true;
FFDisplayResult* display = ffdsAppendDisplay(
data->result,
(uint32_t) monitorInfo->width,
(uint32_t) monitorInfo->height,
0,
(uint32_t) monitorInfo->width,
(uint32_t) monitorInfo->height,
(uint32_t) (monitorInfo->width / scaleFactor + .5),
(uint32_t) (monitorInfo->height / scaleFactor + .5),
0, 0, 0,
0,
&name,
@@ -234,6 +233,8 @@ static bool xrandrHandleMonitor(XrandrData* data, XRRMonitorInfo* monitorInfo)
(uint32_t) monitorInfo->mheight,
"xlib-randr-monitor"
);
if (display) display->bitDepth = bitDepth;
return !!display;
}
static bool xrandrHandleMonitors(XrandrData* data, Screen* screen)
@@ -243,29 +244,36 @@ static bool xrandrHandleMonitors(XrandrData* data, Screen* screen)
if(monitorInfos == NULL)
return false;
XRRScreenResources* screenResources = data->ffXRRGetScreenResourcesCurrent(data->display, RootWindowOfScreen(screen));
double scaleFactor = 1;
char* resourceManager = (char*) x11GetProperty(data->propData, data->display, screen->root, "RESOURCE_MANAGER");
if (resourceManager)
{
FF_STRBUF_AUTO_DESTROY dpi = ffStrbufCreate();
if (ffParsePropLines(resourceManager, "Xft.dpi:", &dpi))
scaleFactor = ffStrbufToDouble(&dpi, 96) / 96;
data->ffXFree(resourceManager);
}
uint8_t bitDepth = (uint8_t) (screen->root_depth / 3);
bool foundAMonitor = false;
for(int i = 0; i < numberOfMonitors; i++)
{
if(xrandrHandleMonitor(data, &monitorInfos[i]))
if(xrandrHandleMonitor(data, &monitorInfos[i], screenResources, bitDepth, scaleFactor))
foundAMonitor = true;
}
data->ffXRRFreeMonitors(monitorInfos);
data->ffXRRFreeScreenResources(screenResources);
return foundAMonitor;
}
static void xrandrHandleScreen(XrandrData* data, Screen* screen)
{
//Init screen resources
data->screenResources = data->ffXRRGetScreenResourcesCurrent(data->display, RootWindowOfScreen(screen));
bool ret = xrandrHandleMonitors(data, screen);
data->ffXRRFreeScreenResources(data->screenResources);
if(ret)
if(xrandrHandleMonitors(data, screen))
return;
//Fallback to screen
@@ -281,7 +289,7 @@ static void xrandrHandleScreen(XrandrData* data, Screen* screen)
NULL,
FF_DISPLAY_TYPE_UNKNOWN,
false,
0,
RootWindowOfScreen(screen),
(uint32_t) WidthMMOfScreen(screen),
(uint32_t) HeightMMOfScreen(screen),
"xlib-randr-screen"
@@ -312,6 +320,7 @@ const char* ffdsConnectXrandr(FFDisplayServerResult* result)
X11PropertyData propertyData;
bool propertyDataInitialized = x11InitPropertyData(xrandr, &propertyData);
data.propData = &propertyData;
data.display = ffXOpenDisplay(NULL);
if(data.display == NULL)
+1 -1
View File
@@ -28,7 +28,7 @@ const char* ffDetectFontImpl(FFFontResult* result)
{
const FFDisplayServerResult* wmde = ffConnectDisplayServer();
if(ffStrbufIgnCaseCompS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY) == 0)
if(ffStrbufIgnCaseEqualS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY))
return "Font isn't supported in TTY";
FFfont qt;
+7
View File
@@ -116,6 +116,13 @@ const char* ffDetectGPU(const FFGPUOptions* options, FFlist* result)
{
ffListDestroy(result);
ffListInitMove(result, &vulkan->gpus);
#ifdef __ANDROID__
double ffGPUDetectTempFromTZ(void);
if (options->temp && result->length == 1)
FF_LIST_GET(FFGPUResult, *result, 0)->temperature = ffGPUDetectTempFromTZ();
#endif
return NULL;
}
}
+53
View File
@@ -0,0 +1,53 @@
#include "gpu.h"
#include "common/io/io.h"
#include "util/stringUtils.h"
#include <fcntl.h>
static double parseTZDir(int dfd, FFstrbuf* buffer)
{
if (!ffReadFileBufferRelative(dfd, "type", buffer) || !ffStrbufStartsWithS(buffer, "gpu"))
return FF_GPU_TEMP_UNSET;
if (!ffReadFileBufferRelative(dfd, "temp", buffer))
return FF_GPU_TEMP_UNSET;
double value = ffStrbufToDouble(buffer, FF_GPU_TEMP_UNSET);// millidegree Celsius
if (value == FF_GPU_TEMP_UNSET)
return FF_GPU_TEMP_UNSET;
return value / 1000.;
}
double ffGPUDetectTempFromTZ(void)
{
FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/thermal/");
if(dirp)
{
FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate();
int dfd = dirfd(dirp);
struct dirent* entry;
while((entry = readdir(dirp)) != NULL)
{
if(entry->d_name[0] == '.')
continue;
if(!ffStrStartsWith(entry->d_name, "thermal_zone"))
continue;
FF_AUTO_CLOSE_FD int subfd = openat(dfd, entry->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if(subfd < 0)
continue;
double result = parseTZDir(subfd, &buffer);
if (result != FF_GPU_TEMP_UNSET)
return result;
}
}
return FF_GPU_TEMP_UNSET;
}
const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus)
{
FF_UNUSED(options, gpus);
return "No permission. Fallbacks to Vulkan, OpenCL or OpenGL instead";
}
+3 -3
View File
@@ -45,10 +45,10 @@ static const FFstrbuf* loadPciIds()
if (pciids.length == 0)
ffReadFileBuffer(FASTFETCH_TARGET_DIR_USR "/local/share/hwdata/pci.ids", &pciids);
}
#elif __FreeBSD__ || __NetBSD__
ffReadFileBuffer(_PATH_LOCALBASE "/share/pciids/pci.ids", &pciids);
#elif __OpenBSD__
#elif __OpenBSD__ || __FreeBSD__ || __NetBSD__
ffReadFileBuffer(_PATH_LOCALBASE "/share/hwdata/pci.ids", &pciids);
if (pciids.length == 0)
ffReadFileBuffer(_PATH_LOCALBASE "/share/pciids/pci.ids", &pciids);
#elif __sun
ffReadFileBuffer(FASTFETCH_TARGET_DIR_ROOT "/usr/share/hwdata/pci.ids", &pciids);
#elif __HAIKU__
+26 -24
View File
@@ -40,17 +40,11 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
return "CM_Get_Device_ID_ListW failed";
}
int deviceCount = 0;
FF_MAYBE_UNUSED int deviceCount = 0;
for (wchar_t* devId = devIdList; *devId; devId += wcslen(devId) + 1)
{
FF_DEBUG("Processing device ID: %ls", devId);
if (wcsncmp(devId, L"SWD\\", 4) == 0)
{
FF_DEBUG("Skipping SWD device interface to avoid duplicates");
continue;
}
DEVINST devInst = 0;
{
@@ -121,6 +115,25 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
wchar_t buffer[256];
ULONG bufferLen = 0;
FF_DEBUG("Get device description as device name");
bufferLen = sizeof(buffer);
if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_DEVICEDESC, NULL, buffer, &bufferLen, 0) == CR_SUCCESS)
{
ffStrbufSetWS(&gpu->name, buffer);
FF_DEBUG("Found device description: %s", gpu->name.chars);
}
else
{
FF_DEBUG("Failed to get device description");
}
if (wcsncmp(devId, L"SWD\\", 4) == 0 || wcsncmp(devId, L"ROOT\\DISPLAY\\", 13) == 0)
{
FF_DEBUG("Skipping virtual devices to avoid duplicates");
continue;
}
if (CM_Open_DevNode_Key(devInst, KEY_QUERY_VALUE, 0, RegDisposition_OpenExisting, &hVideoIdKey, CM_REGISTRY_HARDWARE) == CR_SUCCESS)
{
FF_DEBUG("Opened device node registry key");
@@ -145,8 +158,12 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
}
}
if (ffRegReadStrbuf(hDirectxKey, L"Description", &gpu->name, NULL))
FF_DEBUG("Found GPU description: %s", gpu->name.chars);
if (gpu->name.length == 0)
{
FF_DEBUG("Trying to get GPU name from DirectX registry");
if (ffRegReadStrbuf(hDirectxKey, L"Description", &gpu->name, NULL))
FF_DEBUG("Found GPU description: %s", gpu->name.chars);
}
if (ffRegReadUint64(hDirectxKey, L"DedicatedVideoMemory", &gpu->dedicated.total, NULL))
FF_DEBUG("Found dedicated video memory: %llu bytes", gpu->dedicated.total);
@@ -309,21 +326,6 @@ const char* ffDetectGPUImpl(FF_MAYBE_UNUSED const FFGPUOptions* options, FFlist*
FF_DEBUG("No driver-specific detection function found for vendor: %s", gpu->vendor.chars);
}
if (!gpu->name.length)
{
FF_DEBUG("Trying to get device description as fallback");
bufferLen = sizeof(buffer);
if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_DEVICEDESC, NULL, buffer, &bufferLen, 0) == CR_SUCCESS)
{
ffStrbufSetWS(&gpu->name, buffer);
FF_DEBUG("Found device description: %s", gpu->name.chars);
}
else
{
FF_DEBUG("Failed to get device description");
}
}
if (gpu->type == FF_GPU_TYPE_UNKNOWN && adapterLuid > 0)
{
FF_DEBUG("Trying to determine GPU type using D3DKMT APIs");
+33 -28
View File
@@ -34,6 +34,13 @@ static inline void applyGTKSettings(FFGTKResult* result, const char* themeName,
ffStrbufAppendS(&result->wallpaper, wallpaper);
}
static bool testXfconfWallpaperPropKey(FF_MAYBE_UNUSED void* data, const char* key)
{
int count = 0;
sscanf(key, "/backdrop/screen0/monitor%*[^/]/workspace0/last-image%n", &count);
return count == 0;
}
static void detectGTKFromSettings(FFGTKResult* result)
{
static const char* themeName = NULL;
@@ -55,47 +62,45 @@ static void detectGTKFromSettings(FFGTKResult* result)
const FFDisplayServerResult* wmde = ffConnectDisplayServer();
if(ffStrbufIgnCaseCompS(&wmde->dePrettyName, FF_DE_PRETTY_XFCE4) == 0)
if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_XFCE4))
{
themeName = ffSettingsGetXFConf("xsettings", "/Net/ThemeName", FF_VARIANT_TYPE_STRING).strValue;
iconsName = ffSettingsGetXFConf("xsettings", "/Net/IconThemeName", FF_VARIANT_TYPE_STRING).strValue;
fontName = ffSettingsGetXFConf("xsettings", "/Gtk/FontName", FF_VARIANT_TYPE_STRING).strValue;
cursorTheme = ffSettingsGetXFConf("xsettings", "/Gtk/CursorThemeName", FF_VARIANT_TYPE_STRING).strValue;
cursorSize = ffSettingsGetXFConf("xsettings", "/Gtk/CursorThemeSize", FF_VARIANT_TYPE_INT).intValue;
wallpaper = ffSettingsGetXFConf("xfce4-desktop", "/backdrop/screen0/monitor0/workspace0/last-image", FF_VARIANT_TYPE_STRING).strValue;
if (!wallpaper) // FIXME: find a way to enumerate possible properties
wallpaper = ffSettingsGetXFConf("xfce4-desktop", "/backdrop/screen0/monitoreDP-1/workspace0/last-image", FF_VARIANT_TYPE_STRING).strValue;
wallpaper = ffSettingsGetXFConfFirstMatch("xfce4-desktop", "/backdrop/screen0", FF_VARIANT_TYPE_STRING, NULL, testXfconfWallpaperPropKey).strValue;
}
else if(ffStrbufIgnCaseCompS(&wmde->dePrettyName, FF_DE_PRETTY_CINNAMON) == 0)
else if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_CINNAMON))
{
themeName = ffSettingsGet("/org/cinnamon/desktop/interface/gtk-theme", "org.cinnamon.desktop.interface", NULL, "gtk-theme", FF_VARIANT_TYPE_STRING).strValue;
iconsName = ffSettingsGet("/org/cinnamon/desktop/interface/icon-theme", "org.cinnamon.desktop.interface", NULL, "icon-theme", FF_VARIANT_TYPE_STRING).strValue;
fontName = ffSettingsGet("/org/cinnamon/desktop/interface/font-name", "org.cinnamon.desktop.interface", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue;
cursorTheme = ffSettingsGet("/org/cinnamon/desktop/interface/cursor-theme", "org.cinnamon.desktop.interface", NULL, "cursor-theme", FF_VARIANT_TYPE_STRING).strValue;
cursorSize = ffSettingsGet("/org/cinnamon/desktop/interface/cursor-size", "org.cinnamon.desktop.interface", NULL, "cursor-size", FF_VARIANT_TYPE_INT).intValue;
wallpaper = ffSettingsGet("/org/cinnamon/desktop/background/picture-uri", "org.cinnamon.desktop.background", NULL, "picture-uri", FF_VARIANT_TYPE_STRING).strValue;
themeName = ffSettingsGetGnome("/org/cinnamon/desktop/interface/gtk-theme", "org.cinnamon.desktop.interface", NULL, "gtk-theme", FF_VARIANT_TYPE_STRING).strValue;
iconsName = ffSettingsGetGnome("/org/cinnamon/desktop/interface/icon-theme", "org.cinnamon.desktop.interface", NULL, "icon-theme", FF_VARIANT_TYPE_STRING).strValue;
fontName = ffSettingsGetGnome("/org/cinnamon/desktop/interface/font-name", "org.cinnamon.desktop.interface", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue;
cursorTheme = ffSettingsGetGnome("/org/cinnamon/desktop/interface/cursor-theme", "org.cinnamon.desktop.interface", NULL, "cursor-theme", FF_VARIANT_TYPE_STRING).strValue;
cursorSize = ffSettingsGetGnome("/org/cinnamon/desktop/interface/cursor-size", "org.cinnamon.desktop.interface", NULL, "cursor-size", FF_VARIANT_TYPE_INT).intValue;
wallpaper = ffSettingsGetGnome("/org/cinnamon/desktop/background/picture-uri", "org.cinnamon.desktop.background", NULL, "picture-uri", FF_VARIANT_TYPE_STRING).strValue;
}
else if(ffStrbufIgnCaseCompS(&wmde->dePrettyName, FF_DE_PRETTY_MATE) == 0)
else if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_MATE))
{
themeName = ffSettingsGet("/org/mate/interface/gtk-theme", "org.mate.interface", NULL, "gtk-theme", FF_VARIANT_TYPE_STRING).strValue;
iconsName = ffSettingsGet("/org/mate/interface/icon-theme", "org.mate.interface", NULL, "icon-theme", FF_VARIANT_TYPE_STRING).strValue;
fontName = ffSettingsGet("/org/mate/interface/font-name", "org.mate.interface", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue;
cursorTheme = ffSettingsGet("/org/mate/peripherals-mouse/cursor-theme", "org.mate.peripherals-mouse", NULL, "cursor-theme", FF_VARIANT_TYPE_STRING).strValue;
cursorSize = ffSettingsGet("/org/mate/peripherals-mouse/cursor-size", "org.mate.peripherals-mouse", NULL, "cursor-size", FF_VARIANT_TYPE_INT).intValue;
wallpaper = ffSettingsGet("/org/mate/desktop/background", "org.mate.background", NULL, "picture-filename", FF_VARIANT_TYPE_STRING).strValue;
themeName = ffSettingsGetGnome("/org/mate/interface/gtk-theme", "org.mate.interface", NULL, "gtk-theme", FF_VARIANT_TYPE_STRING).strValue;
iconsName = ffSettingsGetGnome("/org/mate/interface/icon-theme", "org.mate.interface", NULL, "icon-theme", FF_VARIANT_TYPE_STRING).strValue;
fontName = ffSettingsGetGnome("/org/mate/interface/font-name", "org.mate.interface", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue;
cursorTheme = ffSettingsGetGnome("/org/mate/peripherals-mouse/cursor-theme", "org.mate.peripherals-mouse", NULL, "cursor-theme", FF_VARIANT_TYPE_STRING).strValue;
cursorSize = ffSettingsGetGnome("/org/mate/peripherals-mouse/cursor-size", "org.mate.peripherals-mouse", NULL, "cursor-size", FF_VARIANT_TYPE_INT).intValue;
wallpaper = ffSettingsGetGnome("/org/mate/desktop/background", "org.mate.background", NULL, "picture-filename", FF_VARIANT_TYPE_STRING).strValue;
}
else if(
ffStrbufIgnCaseCompS(&wmde->dePrettyName, FF_DE_PRETTY_GNOME) == 0 ||
ffStrbufIgnCaseCompS(&wmde->dePrettyName, FF_DE_PRETTY_GNOME_CLASSIC) == 0 ||
ffStrbufIgnCaseCompS(&wmde->dePrettyName, FF_DE_PRETTY_UNITY) == 0 ||
ffStrbufIgnCaseCompS(&wmde->dePrettyName, FF_DE_PRETTY_BUDGIE) == 0
ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_GNOME) ||
ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_GNOME_CLASSIC) ||
ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_UNITY) ||
ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_BUDGIE)
) {
themeName = ffSettingsGet("/org/gnome/desktop/interface/gtk-theme", "org.gnome.desktop.interface", NULL, "gtk-theme", FF_VARIANT_TYPE_STRING).strValue;
iconsName = ffSettingsGet("/org/gnome/desktop/interface/icon-theme", "org.gnome.desktop.interface", NULL, "icon-theme", FF_VARIANT_TYPE_STRING).strValue;
fontName = ffSettingsGet("/org/gnome/desktop/interface/font-name", "org.gnome.desktop.interface", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue;
cursorTheme = ffSettingsGet("/org/gnome/desktop/interface/cursor-theme", "org.gnome.desktop.interface", NULL, "cursor-theme", FF_VARIANT_TYPE_STRING).strValue;
cursorSize = ffSettingsGet("/org/gnome/desktop/interface/cursor-size", "org.gnome.desktop.interface", NULL, "cursor-size", FF_VARIANT_TYPE_INT).intValue;
wallpaper = ffSettingsGet("/org/gnome/desktop/background/picture-uri", "org.gnome.desktop.background", NULL, "picture-uri", FF_VARIANT_TYPE_STRING).strValue;
themeName = ffSettingsGetGnome("/org/gnome/desktop/interface/gtk-theme", "org.gnome.desktop.interface", NULL, "gtk-theme", FF_VARIANT_TYPE_STRING).strValue;
iconsName = ffSettingsGetGnome("/org/gnome/desktop/interface/icon-theme", "org.gnome.desktop.interface", NULL, "icon-theme", FF_VARIANT_TYPE_STRING).strValue;
fontName = ffSettingsGetGnome("/org/gnome/desktop/interface/font-name", "org.gnome.desktop.interface", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue;
cursorTheme = ffSettingsGetGnome("/org/gnome/desktop/interface/cursor-theme", "org.gnome.desktop.interface", NULL, "cursor-theme", FF_VARIANT_TYPE_STRING).strValue;
cursorSize = ffSettingsGetGnome("/org/gnome/desktop/interface/cursor-size", "org.gnome.desktop.interface", NULL, "cursor-size", FF_VARIANT_TYPE_INT).intValue;
wallpaper = ffSettingsGetGnome("/org/gnome/desktop/background/picture-uri", "org.gnome.desktop.background", NULL, "picture-uri", FF_VARIANT_TYPE_STRING).strValue;
}
applyGTKSettings(result, themeName, iconsName, fontName, cursorTheme, cursorSize, wallpaper);
+1 -1
View File
@@ -140,7 +140,7 @@ const char* ffHostGetMacProductNameWithHwModel(const FFstrbuf* hwModel)
if(ffStrEquals(version, "14,5") ||
ffStrEquals(version, "14,9")) return "MacBook Pro (14-inch, 2023)";
if(ffStrEquals(version, "14,3")) return "Mac mini (M2, 2023, Two Thunderbolt 4 ports)";
if(ffStrEquals(version, "14,12")) return "Mac mini (M2, 2023, Four Thunderbolt 4 ports)";
if(ffStrEquals(version, "14,12")) return "Mac mini (M2 Pro, 2023, Four Thunderbolt 4 ports)";
if(ffStrEquals(version, "14,7")) return "MacBook Pro (13-inch, M2, 2022)";
if(ffStrEquals(version, "14,2")) return "MacBook Air (M2, 2022)";
if(ffStrEquals(version, "13,1")) return "Mac Studio (M1 Max, 2022, Two USB-C front ports)";
+1 -1
View File
@@ -7,7 +7,7 @@ const char* ffDetectIcons(FFIconsResult* result)
{
const FFDisplayServerResult* wmde = ffConnectDisplayServer();
if(ffStrbufIgnCaseCompS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY) == 0)
if(ffStrbufIgnCaseEqualS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY))
return "Icons aren't supported in TTY";
const FFstrbuf* plasma = &ffDetectQt()->icons;
+18 -1
View File
@@ -48,7 +48,7 @@ const char* ffDetectInitSystem(FFInitSystemResult* result)
if (instance.config.general.detectVersion)
{
#if __linux__ && !__ANDROID__
#if (defined(__linux__) && !defined(__ANDROID__)) || defined(__GNU__)
if (ffStrbufEqualS(&result->name, "systemd"))
{
ffBinaryExtractStrings(result->exe.chars, extractSystemdVersion, &result->version, (uint32_t) strlen("systemd 0.0 running in x"));
@@ -84,6 +84,23 @@ const char* ffDetectInitSystem(FFInitSystemResult* result)
ffStrbufSubstrAfterLastC(&result->version, ' ');
}
}
else if (ffStrbufEqualS(&result->name, "shepherd"))
{
if (ffProcessAppendStdOut(&result->version, (char* const[]) {
ffStrbufEndsWithS(&result->exe, "/shepherd") ? result->exe.chars : "shepherd",
"--version",
NULL,
}) == NULL && result->version.length)
{
// shepherd (GNU Shepherd) 1.0.6
// The first line in the output might not contain the version
if (!ffStrbufStartsWithS(&result->version, "shepherd"))
ffStrbufSubstrAfterFirstC(&result->version, '\n');
ffStrbufSubstrBeforeFirstC(&result->version, '\n');
ffStrbufSubstrAfterLastC(&result->version, ' ');
}
}
#elif __APPLE__
if (ffStrbufEqualS(&result->name, "launchd"))
{
+2 -1
View File
@@ -19,7 +19,7 @@ const char* ffDetectLoadavg(double result[3])
}
#endif
#ifndef __GNU__
// getloadavg requires higher ANDROID_API version
struct sysinfo si;
if (sysinfo(&si) < 0)
@@ -27,5 +27,6 @@ const char* ffDetectLoadavg(double result[3])
for (int i = 0; i < 3; i++)
result[i] = (double) si.loads[i] / (1 << SI_LOAD_SHIFT);
#endif
return NULL;
}
+1 -1
View File
@@ -12,7 +12,7 @@ typedef struct FFLocalIpResult
FFstrbuf flags;
int32_t mtu;
int32_t speed; // in Mbps
bool defaultRoute;
FFLocalIpType defaultRoute;
} FFLocalIpResult;
typedef struct FFLocalIpNIFlag
+404 -150
View File
@@ -2,6 +2,7 @@
#include "common/io/io.h"
#include "common/netif/netif.h"
#include "util/stringUtils.h"
#include "util/debug.h"
#include <string.h>
#include <ctype.h>
@@ -28,7 +29,7 @@
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__) || defined(__NetBSD__) || defined(__HAIKU__)
#include <net/if_media.h>
#include <net/if_dl.h>
#else
#elif !defined(__GNU__)
#include <netpacket/packet.h>
#endif
#if defined(__sun) || defined(__HAIKU__)
@@ -68,12 +69,14 @@ static const FFLocalIpNIFlag niFlagOptions[] = {
#ifdef IFF_NOTRAILERS
FF_LOCALIP_NIFLAG(NOTRAILERS),
#endif
#ifdef __linux__
#if defined( __linux__) || defined (__GNU__)
FF_LOCALIP_NIFLAG(MASTER),
FF_LOCALIP_NIFLAG(SLAVE),
FF_LOCALIP_NIFLAG(PORTSEL),
FF_LOCALIP_NIFLAG(AUTOMEDIA),
FF_LOCALIP_NIFLAG(DYNAMIC),
#endif
#ifdef __linux__
FF_LOCALIP_NIFLAG(LOWER_UP),
FF_LOCALIP_NIFLAG(DORMANT),
FF_LOCALIP_NIFLAG(ECHO),
@@ -108,58 +111,24 @@ static const FFLocalIpNIFlag niFlagOptions[] = {
{},
};
static void addNewIp(FFlist* list, const char* name, const char* addr, int type, bool defaultRoute, uint64_t flags, bool firstOnly)
typedef enum __attribute__((__packed__)) FFIPv6Type
{
FFLocalIpResult* ip = NULL;
FF_IPV6_Other,
FF_IPV6_GUA = 0b0001,
FF_IPV6_GUA_SECONDARY = 0b0101,
FF_IPV6_ULA = 0b0010,
FF_IPV6_ULA_SECONDARY = 0b0110,
FF_IPV6_TYPE_MASK = 0b0011,
FF_IPV6_SECONDARY_FLAG = 0b1100,
FF_IPV6_PREFERRED = UINT8_MAX,
} FFIPv6Type;
FF_LIST_FOR_EACH(FFLocalIpResult, temp, *list)
{
if (!ffStrbufEqualS(&temp->name, name)) continue;
ip = temp;
if (defaultRoute) ip->defaultRoute = true;
break;
}
if (!ip)
{
ip = (FFLocalIpResult*) ffListAdd(list);
ffStrbufInitS(&ip->name, name);
ffStrbufInit(&ip->ipv4);
ffStrbufInit(&ip->ipv6);
ffStrbufInit(&ip->mac);
ffStrbufInit(&ip->flags);
ip->defaultRoute = defaultRoute;
ip->mtu = -1;
ip->speed = -1;
ffLocalIpFillNIFlags(&ip->flags, flags, niFlagOptions);
}
switch (type)
{
case AF_INET:
if (ip->ipv4.length)
{
if (firstOnly) return;
ffStrbufAppendC(&ip->ipv4, ',');
}
ffStrbufAppendS(&ip->ipv4, addr);
break;
case AF_INET6:
if (ip->ipv6.length)
{
if (firstOnly) return;
ffStrbufAppendC(&ip->ipv6, ',');
}
ffStrbufAppendS(&ip->ipv6, addr);
break;
case -1:
ffStrbufSetS(&ip->mac, addr);
break;
}
}
static bool isIPv6AddressPreferred(struct ifaddrs* ifa, struct sockaddr_in6* addr)
static FFIPv6Type getIpType(struct ifaddrs* ifa)
{
struct sockaddr_in6* addr = (struct sockaddr_in6*) ifa->ifa_addr;
FF_DEBUG("Checking IPv6 type for interface %s", ifa->ifa_name);
#ifndef IN6_IS_ADDR_GLOBAL
#define IN6_IS_ADDR_GLOBAL(a) \
((((const uint32_t *) (a))[0] & htonl(0x70000000)) == htonl(0x20000000))
@@ -168,8 +137,22 @@ static bool isIPv6AddressPreferred(struct ifaddrs* ifa, struct sockaddr_in6* add
#define IN6_IS_ADDR_UNIQUE_LOCAL(a) \
((((const uint32_t *) (a))[0] & htonl(0xfe000000)) == htonl(0xfc000000))
#endif
if (!IN6_IS_ADDR_GLOBAL(&addr->sin6_addr) && !IN6_IS_ADDR_UNIQUE_LOCAL(&addr->sin6_addr))
return false;
FFIPv6Type result = FF_IPV6_Other;
if (IN6_IS_ADDR_GLOBAL(&addr->sin6_addr))
{
result = FF_IPV6_GUA;
FF_DEBUG("Interface %s has Global Unicast Address", ifa->ifa_name);
}
else if (IN6_IS_ADDR_UNIQUE_LOCAL(&addr->sin6_addr))
{
result = FF_IPV6_ULA;
FF_DEBUG("Interface %s has Unique Local Address", ifa->ifa_name);
}
else
{
FF_DEBUG("Interface %s has other IPv6 address type", ifa->ifa_name);
return FF_IPV6_Other;
}
#ifdef SIOCGIFAFLAG_IN6
static int sockfd = 0;
@@ -184,33 +167,33 @@ static bool isIPv6AddressPreferred(struct ifaddrs* ifa, struct sockaddr_in6* add
if (sockfd > 0) fcntl(sockfd, F_SETFD, FD_CLOEXEC);
#endif
}
if (sockfd < 0) return true; // Give up
if (sockfd < 0) return result;
struct in6_ifreq ifr6 = {};
ffStrCopy(ifr6.ifr_name, ifa->ifa_name, IFNAMSIZ);
ifr6.ifr_addr = *addr;
if (ioctl(sockfd, SIOCGIFAFLAG_IN6, &ifr6) != 0)
return true;
return result;
#ifdef IN6_IFF_PREFER_SOURCE
if (ifr6.ifr_ifru.ifru_flags6 & IN6_IFF_PREFER_SOURCE)
return true;
return FF_IPV6_PREFERRED;
#endif
return !(ifr6.ifr_ifru.ifru_flags6 & (IN6_IFF_DEPRECATED | IN6_IFF_TEMPORARY | IN6_IFF_TENTATIVE | IN6_IFF_DUPLICATED
if (ifr6.ifr_ifru.ifru_flags6 & (IN6_IFF_DEPRECATED | IN6_IFF_TEMPORARY | IN6_IFF_TENTATIVE | IN6_IFF_DUPLICATED
#ifdef IN6_IFF_OPTIMISTIC
| IN6_IFF_OPTIMISTIC
#endif
));
)) result |= FF_IPV6_SECONDARY_FLAG;
return result;
#elif __linux__
FF_UNUSED(ifa);
static FFlist addresses = {};
if (addresses.elementSize == 0)
{
ffListInit(&addresses, sizeof(struct in6_addr));
FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate();
if (!ffReadFileBuffer("/proc/net/if_inet6", &buffer))
return true;
return result;
char* line = NULL;
size_t len = 0;
@@ -230,146 +213,381 @@ static bool isIPv6AddressPreferred(struct ifaddrs* ifa, struct sockaddr_in6* add
--addresses.length;
}
}
if (addresses.capacity == 0) return true; // Give up
if (addresses.capacity == 0) return result;
FF_LIST_FOR_EACH(struct in6_addr, entry, addresses)
{
if (memcmp(&addr->sin6_addr, entry, sizeof(struct in6_addr)) == 0)
return true;
return result;
}
return false;
result |= FF_IPV6_SECONDARY_FLAG;
return result;
#elif __sun
if (ifa->ifa_flags & IFF_PREFERRED)
return true;
return !(ifa->ifa_flags & (IFF_DEPRECATED | IFF_TEMPORARY | IFF_DUPLICATE));
return FF_IPV6_PREFERRED;
if (ifa->ifa_flags & (IFF_DEPRECATED | IFF_TEMPORARY | IFF_DUPLICATE))
result |= FF_IPV6_SECONDARY_FLAG;
return result;
#else
return true;
return result;
#endif
}
typedef struct {
struct ifaddrs* mac;
FFlist /*<struct ifaddrs*>*/ ipv4;
FFlist /*<struct ifaddrs*>*/ ipv6;
} FFAdapter;
static void appendIpv4(const FFLocalIpOptions* options, FFstrbuf* buffer, const struct ifaddrs* ifa)
{
struct sockaddr_in* ipv4 = (struct sockaddr_in*) ifa->ifa_addr;
char addressBuffer[INET_ADDRSTRLEN + 16];
inet_ntop(AF_INET, &ipv4->sin_addr, addressBuffer, INET_ADDRSTRLEN);
FF_DEBUG("Adding IPv4 address %s for interface %s", addressBuffer, ifa->ifa_name);
if (options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT)
{
struct sockaddr_in* netmask = (struct sockaddr_in*) ifa->ifa_netmask;
int cidr = __builtin_popcount(netmask->sin_addr.s_addr);
if (cidr != 0)
{
size_t len = strlen(addressBuffer);
snprintf(addressBuffer + len, 16, "/%d", cidr);
}
}
if (buffer->length) ffStrbufAppendC(buffer, ',');
ffStrbufAppendS(buffer, addressBuffer);
}
static void appendIpv6(const FFLocalIpOptions* options, FFstrbuf* buffer, const struct ifaddrs* ifa)
{
struct sockaddr_in6* ipv6 = (struct sockaddr_in6*) ifa->ifa_addr;
char addressBuffer[INET6_ADDRSTRLEN + 16];
inet_ntop(AF_INET6, &ipv6->sin6_addr, addressBuffer, INET6_ADDRSTRLEN);
FF_DEBUG("Adding IPv6 address %s for interface %s", addressBuffer, ifa->ifa_name);
if (options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT)
{
struct sockaddr_in6* netmask = (struct sockaddr_in6*) ifa->ifa_netmask;
int cidr = 0;
static_assert(sizeof(netmask->sin6_addr) % sizeof(uint64_t) == 0, "");
for (uint32_t i = 0; i < sizeof(netmask->sin6_addr) / sizeof(uint64_t); ++i)
cidr += __builtin_popcountll(((uint64_t*) &netmask->sin6_addr)[i]);
if (cidr != 0)
{
size_t len = strlen(addressBuffer);
snprintf(addressBuffer + len, 16, "/%d", cidr);
}
}
if (buffer->length) ffStrbufAppendC(buffer, ',');
ffStrbufAppendS(buffer, addressBuffer);
}
const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
{
FF_DEBUG("Starting local IP detection with showType=0x%x, namePrefix='%s'",
options->showType, options->namePrefix.chars);
struct ifaddrs* ifAddrStruct = NULL;
if(getifaddrs(&ifAddrStruct) < 0)
{
FF_DEBUG("getifaddrs() failed");
return "getifaddrs(&ifAddrStruct) failed";
}
FF_DEBUG("Successfully retrieved interface addresses");
FF_LIST_AUTO_DESTROY adapters = ffListCreate(sizeof(FFAdapter));
for (struct ifaddrs* ifa = ifAddrStruct; ifa; ifa = ifa->ifa_next)
{
if (!ifa->ifa_addr)
{
FF_DEBUG("Skipping interface %s (no address)", ifa->ifa_name);
continue;
}
#ifdef IFF_RUNNING
#ifdef IFF_RUNNING
if (!(ifa->ifa_flags & IFF_RUNNING))
{
FF_DEBUG("Skipping interface %s (not running)", ifa->ifa_name);
continue;
#endif
}
#endif
if ((ifa->ifa_flags & IFF_LOOPBACK) && !(options->showType & FF_LOCALIP_TYPE_LOOP_BIT))
{
FF_DEBUG("Skipping loopback interface %s", ifa->ifa_name);
continue;
}
if (options->namePrefix.length && strncmp(ifa->ifa_name, options->namePrefix.chars, options->namePrefix.length) != 0)
continue;
uint64_t flags = options->showType & FF_LOCALIP_TYPE_FLAGS_BIT ? ifa->ifa_flags : 0;
if (ifa->ifa_addr->sa_family == AF_INET)
{
if (!(options->showType & FF_LOCALIP_TYPE_IPV4_BIT))
continue;
FF_DEBUG("Skipping interface %s (doesn't match prefix '%s')",
ifa->ifa_name, options->namePrefix.chars);
continue;
}
struct sockaddr_in* ipv4 = (struct sockaddr_in*) ifa->ifa_addr;
if (!(options->showType & FF_LOCALIP_TYPE_MAC_BIT) &&
ifa->ifa_addr->sa_family != AF_INET && ifa->ifa_addr->sa_family != AF_INET6)
{
FF_DEBUG("Skipping interface %s (unsupported address family %d)",
ifa->ifa_name, ifa->ifa_addr->sa_family);
continue;
}
if (options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT)
{
// If the interface is not the default route for either IPv4 or IPv6, skip it
if (!((options->showType & FF_LOCALIP_TYPE_IPV4_BIT) && ffStrEquals(ffNetifGetDefaultRouteV4()->ifName, ifa->ifa_name)) &&
!((options->showType & FF_LOCALIP_TYPE_IPV6_BIT) && ffStrEquals(ffNetifGetDefaultRouteV6()->ifName, ifa->ifa_name)))
{
FF_DEBUG("Skipping interface %s (not default route interface)", ifa->ifa_name);
continue;
}
}
FF_DEBUG("Processing interface %s (family=%d, flags=0x%x)",
ifa->ifa_name, ifa->ifa_addr->sa_family, ifa->ifa_flags);
FFAdapter* adapter = NULL;
FF_LIST_FOR_EACH(FFAdapter, x, adapters)
{
if (ffStrEquals(x->mac->ifa_name, ifa->ifa_name))
{
adapter = x;
break;
}
}
if (!adapter)
{
adapter = ffListAdd(&adapters);
*adapter = (FFAdapter) {
.mac = ifa,
.ipv4 = ffListCreate(sizeof(struct ifaddrs*)),
.ipv6 = ffListCreate(sizeof(struct ifaddrs*)),
};
FF_DEBUG("Created new adapter entry for interface %s", ifa->ifa_name);
}
switch (ifa->ifa_addr->sa_family)
{
case AF_INET:
if (options->showType & FF_LOCALIP_TYPE_IPV4_BIT)
{
*FF_LIST_ADD(struct ifaddrs*, adapter->ipv4) = ifa;
FF_DEBUG("Added IPv4 entry for interface %s", ifa->ifa_name);
}
break;
case AF_INET6:
if (options->showType & FF_LOCALIP_TYPE_IPV6_BIT)
{
*FF_LIST_ADD(struct ifaddrs*, adapter->ipv6) = ifa;
FF_DEBUG("Added IPv6 entry for interface %s", ifa->ifa_name);
}
break;
#if __FreeBSD__ || __OpenBSD__ || __APPLE__ || __NetBSD__ || __HAIKU__
case AF_LINK:
adapter->mac = ifa;
FF_DEBUG("Updated MAC entry for interface %s", ifa->ifa_name);
break;
#elif !__sun && !__GNU__
case AF_PACKET:
adapter->mac = ifa;
FF_DEBUG("Updated MAC entry for interface %s", ifa->ifa_name);
break;
#endif
}
}
FF_DEBUG("Found %u network adapters", adapters.length);
FF_LIST_FOR_EACH(FFAdapter, adapter, adapters)
{
FF_DEBUG("Processing adapter %s (IPv4 entries: %u, IPv6 entries: %u)",
adapter->mac->ifa_name, adapter->ipv4.length, adapter->ipv6.length);
if (adapter->ipv4.length == 0 && adapter->ipv6.length == 0 &&
!(options->showType & FF_LOCALIP_TYPE_MAC_BIT) )
{
FF_DEBUG("Skipping interface %s (no IP addresses)", adapter->mac->ifa_name);
continue;
}
FFLocalIpResult* item = FF_LIST_ADD(FFLocalIpResult, *results);
ffStrbufInitS(&item->name, adapter->mac->ifa_name);
ffStrbufInit(&item->ipv4);
ffStrbufInit(&item->ipv6);
ffStrbufInit(&item->mac);
ffStrbufInit(&item->flags);
item->defaultRoute = FF_LOCALIP_TYPE_NONE;
item->mtu = -1;
item->speed = -1;
if (options->showType & FF_LOCALIP_TYPE_FLAGS_BIT)
{
ffLocalIpFillNIFlags(&item->flags, adapter->mac->ifa_flags, niFlagOptions);
FF_DEBUG("Added flags for interface %s: %s", adapter->mac->ifa_name, item->flags.chars);
}
if ((options->showType & FF_LOCALIP_TYPE_IPV4_BIT))
{
const FFNetifDefaultRouteResult* defaultRouteV4 = ffNetifGetDefaultRouteV4();
bool isDefaultRouteIf = ffStrEquals(defaultRouteV4->ifName, adapter->mac->ifa_name);
if (isDefaultRouteIf)
{
item->defaultRoute |= FF_LOCALIP_TYPE_IPV4_BIT;
FF_DEBUG("Interface %s is IPv4 default route", adapter->mac->ifa_name);
}
const FFNetifDefaultRouteResult* defaultRoute = ffNetifGetDefaultRouteV4();
bool isDefaultRouteIf = ffStrEquals(defaultRoute->ifName, ifa->ifa_name);
if (options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT)
{
if (!isDefaultRouteIf)
continue;
if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT))
{
bool isPreferredSourceAddr = defaultRoute->preferredSourceAddrV4 == 0 || ipv4->sin_addr.s_addr == defaultRoute->preferredSourceAddrV4;
if (!isPreferredSourceAddr)
continue;
FF_DEBUG("Skipping IPv4 for interface %s (not default route)", adapter->mac->ifa_name);
goto v6;
}
}
char addressBuffer[INET_ADDRSTRLEN + 16];
inet_ntop(AF_INET, &ipv4->sin_addr, addressBuffer, INET_ADDRSTRLEN);
if (options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT)
if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT))
{
struct sockaddr_in* netmask = (struct sockaddr_in*) ifa->ifa_netmask;
int cidr = __builtin_popcount(netmask->sin_addr.s_addr);
if (cidr != 0)
struct ifaddrs* ifa = NULL;
if (isDefaultRouteIf && defaultRouteV4->preferredSourceAddrV4 != 0)
{
size_t len = strlen(addressBuffer);
snprintf(addressBuffer + len, 16, "/%d", cidr);
FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv4)
{
struct sockaddr_in* ipv4 = (struct sockaddr_in*) (*pifa)->ifa_addr;
if (ipv4->sin_addr.s_addr == defaultRouteV4->preferredSourceAddrV4)
{
ifa = *pifa;
FF_DEBUG("Found preferred IPv4 source address for interface %s", adapter->mac->ifa_name);
break;
}
}
}
if (ifa)
appendIpv4(options, &item->ipv4, ifa);
else if (adapter->ipv4.length > 0)
{
appendIpv4(options, &item->ipv4, *FF_LIST_GET(struct ifaddrs*, adapter->ipv4, 0));
FF_DEBUG("Using first IPv4 address for interface %s", adapter->mac->ifa_name);
}
}
addNewIp(results, ifa->ifa_name, addressBuffer, AF_INET, isDefaultRouteIf, flags, !(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT));
}
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
if (!(options->showType & FF_LOCALIP_TYPE_IPV6_BIT))
continue;
const FFNetifDefaultRouteResult* defaultRoute = ffNetifGetDefaultRouteV6();
bool isDefaultRouteIf = ffStrEquals(defaultRoute->ifName, ifa->ifa_name);
if ((options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) && !isDefaultRouteIf)
continue;
struct sockaddr_in6* ipv6 = (struct sockaddr_in6 *)ifa->ifa_addr;
if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT) && !isIPv6AddressPreferred(ifa, ipv6))
continue;
char addressBuffer[INET6_ADDRSTRLEN + 16];
inet_ntop(AF_INET6, &ipv6->sin6_addr, addressBuffer, INET6_ADDRSTRLEN);
if (options->showType & FF_LOCALIP_TYPE_PREFIX_LEN_BIT)
else
{
struct sockaddr_in6* netmask = (struct sockaddr_in6*) ifa->ifa_netmask;
int cidr = 0;
static_assert(sizeof(netmask->sin6_addr) % sizeof(uint64_t) == 0, "");
for (uint32_t i = 0; i < sizeof(netmask->sin6_addr) / sizeof(uint64_t); ++i)
cidr += __builtin_popcountll(((uint64_t*) &netmask->sin6_addr)[i]);
if (cidr != 0)
FF_DEBUG("Adding all IPv4 addresses for interface %s", adapter->mac->ifa_name);
FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv4)
appendIpv4(options, &item->ipv4, *pifa);
}
}
v6:
if ((options->showType & FF_LOCALIP_TYPE_IPV6_BIT))
{
const FFNetifDefaultRouteResult* defaultRouteV6 = ffNetifGetDefaultRouteV6();
bool isDefaultRouteIf = ffStrEquals(defaultRouteV6->ifName, adapter->mac->ifa_name);
if (isDefaultRouteIf)
{
item->defaultRoute |= FF_LOCALIP_TYPE_IPV6_BIT;
FF_DEBUG("Interface %s is IPv6 default route", adapter->mac->ifa_name);
}
if (options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT)
{
if (!isDefaultRouteIf)
{
size_t len = strlen(addressBuffer);
snprintf(addressBuffer + len, 16, "/%d", cidr);
FF_DEBUG("Skipping IPv6 for interface %s (not default route)", adapter->mac->ifa_name);
goto mac;
}
}
addNewIp(results, ifa->ifa_name, addressBuffer, AF_INET6, isDefaultRouteIf, flags, !(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT));
}
#if __FreeBSD__ || __OpenBSD__ || __APPLE__ || __NetBSD__ || __HAIKU__
else if (ifa->ifa_addr->sa_family == AF_LINK)
{
if (!(options->showType & FF_LOCALIP_TYPE_MAC_BIT))
continue;
if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT))
{
struct ifaddrs* selected = NULL;
struct ifaddrs* secondary = NULL;
char addressBuffer[32];
uint8_t* ptr = (uint8_t*) LLADDR((struct sockaddr_dl *)ifa->ifa_addr);
snprintf(addressBuffer, ARRAY_SIZE(addressBuffer), "%02x:%02x:%02x:%02x:%02x:%02x",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
addNewIp(results, ifa->ifa_name, addressBuffer, -1, false, flags, false);
FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv6)
{
FFIPv6Type type = getIpType(*pifa);
if (type == FF_IPV6_PREFERRED)
{
selected = *pifa;
FF_DEBUG("Found preferred IPv6 address for interface %s", adapter->mac->ifa_name);
break;
}
else if (type == FF_IPV6_GUA && !selected)
{
selected = *pifa;
FF_DEBUG("Found GUA IPv6 address for interface %s", adapter->mac->ifa_name);
}
else if (type == FF_IPV6_ULA && !secondary)
{
secondary = *pifa;
FF_DEBUG("Found ULA IPv6 address for interface %s", adapter->mac->ifa_name);
}
}
if (!selected) selected = secondary;
if (selected)
appendIpv6(options, &item->ipv6, selected);
else if (adapter->ipv6.length > 0)
{
appendIpv6(options, &item->ipv6, *FF_LIST_GET(struct ifaddrs*, adapter->ipv6, 0));
FF_DEBUG("Using first IPv6 address for interface %s", adapter->mac->ifa_name);
}
}
else
{
FF_DEBUG("Adding all IPv6 addresses for interface %s", adapter->mac->ifa_name);
FF_LIST_FOR_EACH(struct ifaddrs*, pifa, adapter->ipv6)
appendIpv6(options, &item->ipv6, *pifa);
}
}
mac:
#if !defined( __sun) && !defined(__GNU__)
if (options->showType & FF_LOCALIP_TYPE_MAC_BIT)
{
if (adapter->mac->ifa_addr)
{
#if __FreeBSD__ || __OpenBSD__ || __APPLE__ || __NetBSD__ || __HAIKU__
uint8_t* ptr = (uint8_t*) LLADDR((struct sockaddr_dl *)adapter->mac->ifa_addr);
#else
uint8_t* ptr = ((struct sockaddr_ll *)adapter->mac->ifa_addr)->sll_addr;
#endif
ffStrbufSetF(&item->mac, "%02x:%02x:%02x:%02x:%02x:%02x",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
FF_DEBUG("Added MAC address %s for interface %s", item->mac.chars, adapter->mac->ifa_name);
}
else
{
FF_DEBUG("No MAC address available for interface %s", adapter->mac->ifa_name);
}
}
#else
else if (ifa->ifa_addr->sa_family == AF_PACKET)
{
if (!(options->showType & FF_LOCALIP_TYPE_MAC_BIT))
continue;
char addressBuffer[32];
uint8_t* ptr = ((struct sockaddr_ll *)ifa->ifa_addr)->sll_addr;
snprintf(addressBuffer, ARRAY_SIZE(addressBuffer), "%02x:%02x:%02x:%02x:%02x:%02x",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
addNewIp(results, ifa->ifa_name, addressBuffer, -1, false, flags, false);
}
(void) adapter;
#endif
}
if (ifAddrStruct) freeifaddrs(ifAddrStruct);
FF_LIST_FOR_EACH(FFAdapter, adapter, adapters)
{
ffListDestroy(&adapter->ipv4);
ffListDestroy(&adapter->ipv6);
}
if (ifAddrStruct)
{
freeifaddrs(ifAddrStruct);
ifAddrStruct = NULL;
FF_DEBUG("Cleaned up interface address structures");
}
if ((options->showType & FF_LOCALIP_TYPE_MTU_BIT) || (options->showType & FF_LOCALIP_TYPE_SPEED_BIT)
#ifdef __sun
@@ -377,18 +595,26 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
#endif
)
{
FF_DEBUG("Retrieving additional interface properties (MTU/Speed/MAC)");
FF_AUTO_CLOSE_FD int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd > 0)
{
FF_LIST_FOR_EACH(FFLocalIpResult, iface, *results)
{
struct ifreq ifr;
struct ifreq ifr = {};
ffStrCopy(ifr.ifr_name, iface->name.chars, IFNAMSIZ);
if (options->showType & FF_LOCALIP_TYPE_MTU_BIT)
{
if (ioctl(sockfd, SIOCGIFMTU, &ifr) == 0)
{
iface->mtu = (int32_t) ifr.ifr_mtu;
FF_DEBUG("Interface %s MTU: %d", iface->name.chars, iface->mtu);
}
else
{
FF_DEBUG("Failed to get MTU for interface %s", iface->name.chars);
}
}
if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT)
@@ -397,12 +623,21 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
struct ethtool_cmd edata = { .cmd = ETHTOOL_GSET };
ifr.ifr_data = (void*) &edata;
if (ioctl(sockfd, SIOCETHTOOL, &ifr) == 0)
iface->speed = (edata.speed_hi << 16) | edata.speed; // ethtool_cmd_speed is not available on Android
{
iface->speed = (edata.speed_hi << 16) | edata.speed;
FF_DEBUG("Interface %s speed: %d Mbps", iface->name.chars, iface->speed);
}
else
{
// ethtool_cmd_speed is not available on Android
FF_DEBUG("Failed to get speed for interface %s via ethtool", iface->name.chars);
}
#elif __FreeBSD__ || __APPLE__ || __OpenBSD__ || __NetBSD__
struct ifmediareq ifmr = {};
ffStrCopy(ifmr.ifm_name, iface->name.chars, IFNAMSIZ);
if (ioctl(sockfd, SIOCGIFMEDIA, &ifmr) == 0 && (IFM_TYPE(ifmr.ifm_active) & IFM_ETHER))
{
FF_DEBUG("Interface %s media type: 0x%x", iface->name.chars, IFM_SUBTYPE(ifmr.ifm_active));
switch (IFM_SUBTYPE(ifmr.ifm_active))
{
#ifdef IFM_HPNA_1
@@ -767,18 +1002,29 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
iface->speed = 56000; break;
default:
iface->speed = -1;
FF_DEBUG("Unknown media subtype for interface %s", iface->name.chars);
break;
}
if (iface->speed > 0)
FF_DEBUG("Interface %s speed: %d Mbps", iface->name.chars, iface->speed);
}
else
{
FF_DEBUG("Failed to get media info for interface %s", iface->name.chars);
}
#endif
}
#ifdef __sun
#if __sun || __GNU__
if ((options->showType & FF_LOCALIP_TYPE_MAC_BIT) && ioctl(sockfd, SIOCGIFHWADDR, &ifr) == 0)
{
const uint8_t* ptr = (uint8_t*) ifr.ifr_addr.sa_data; // NOT ifr_enaddr
ffStrbufSetF(&iface->mac, "%02x:%02x:%02x:%02x:%02x:%02x",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
FF_DEBUG("Added MAC address %s for interface %s (Solaris/GNU)", iface->mac.chars, iface->name.chars);
}
#endif
#if __sun
if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT)
{
__attribute__((__cleanup__(kstatFreeWrap))) kstat_ctl_t* kc = kstat_open();
@@ -791,7 +1037,10 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
{
kstat_named_t* ifspeed = (kstat_named_t*) kstat_data_lookup(ks, "ifspeed");
if (ifspeed)
{
iface->speed = (int32_t) (ifspeed->value.ui64 / 1000 / 1000);
FF_DEBUG("Interface %s speed: %d Mbps (kstat)", iface->name.chars, iface->speed);
}
}
break;
}
@@ -800,7 +1049,12 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
#endif
}
}
else
{
FF_DEBUG("Failed to create socket for interface property retrieval");
}
}
FF_DEBUG("Local IP detection completed, found %u interfaces", results->length);
return NULL;
}
+134 -71
View File
@@ -4,6 +4,7 @@
#include "common/netif/netif.h"
#include "util/mallocHelper.h"
#include "util/windows/unicode.h"
#include "util/debug.h"
#include "localip.h"
#define FF_LOCALIP_NIFLAG(name) { IP_ADAPTER_##name, #name }
@@ -23,45 +24,11 @@ static const FFLocalIpNIFlag niFlagOptions[] = {
{},
};
static void addNewIp(FFlist* list, const char* name, const char* addr, int type, bool newIp, bool defaultRoute)
{
FFLocalIpResult* ip = NULL;
if (newIp)
{
ip = (FFLocalIpResult*) ffListAdd(list);
ffStrbufInitS(&ip->name, name);
ffStrbufInit(&ip->ipv4);
ffStrbufInit(&ip->ipv6);
ffStrbufInit(&ip->mac);
ffStrbufInit(&ip->flags);
ip->defaultRoute = defaultRoute;
ip->speed = -1;
ip->mtu = -1;
}
else
{
ip = FF_LIST_GET(FFLocalIpResult, *list, list->length - 1);
}
switch (type)
{
case AF_INET:
if (ip->ipv4.length) ffStrbufAppendC(&ip->ipv4, ',');
ffStrbufAppendS(&ip->ipv4, addr);
break;
case AF_INET6:
if (ip->ipv6.length) ffStrbufAppendC(&ip->ipv6, ',');
ffStrbufAppendS(&ip->ipv6, addr);
break;
case -1:
ffStrbufSetS(&ip->mac, addr);
break;
}
}
const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
{
FF_DEBUG("Starting local IP detection with showType=0x%X, namePrefix='%.*s'",
options->showType, (int)options->namePrefix.length, options->namePrefix.chars);
IP_ADAPTER_ADDRESSES* FF_AUTO_FREE adapter_addresses = NULL;
// Multiple attempts in case interfaces change while
@@ -69,72 +36,133 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
DWORD adapter_addresses_buffer_size = 0;
for (int attempts = 0;; ++attempts)
{
FF_DEBUG("Attempt %d to get adapter addresses, buffer size: %lu", attempts + 1, adapter_addresses_buffer_size);
if (adapter_addresses_buffer_size)
{
adapter_addresses = (IP_ADAPTER_ADDRESSES*)realloc(adapter_addresses, adapter_addresses_buffer_size);
assert(adapter_addresses);
}
DWORD family = options->showType & FF_LOCALIP_TYPE_IPV4_BIT
? options->showType & FF_LOCALIP_TYPE_IPV6_BIT ? AF_UNSPEC : AF_INET
: AF_INET6;
FF_DEBUG("Calling GetAdaptersAddresses with family=%u, flags=0x%X", (unsigned)family,
GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER);
DWORD error = GetAdaptersAddresses(
options->showType & FF_LOCALIP_TYPE_IPV4_BIT
? options->showType & FF_LOCALIP_TYPE_IPV6_BIT ? AF_UNSPEC : AF_INET
: AF_INET6,
family,
GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER,
NULL,
adapter_addresses,
&adapter_addresses_buffer_size);
if (error == ERROR_SUCCESS)
{
FF_DEBUG("GetAdaptersAddresses succeeded on attempt %d", attempts + 1);
break;
}
else if (ERROR_BUFFER_OVERFLOW == error && attempts < 4)
{
FF_DEBUG("Buffer overflow, need %lu bytes, retrying", adapter_addresses_buffer_size);
continue;
}
else
{
FF_DEBUG("GetAdaptersAddresses failed with error %lu after %d attempts", error, attempts + 1);
return "GetAdaptersAddresses() failed";
}
}
uint32_t defaultRouteIfIndex = ffNetifGetDefaultRouteV4()->ifIndex;
FF_MAYBE_UNUSED int adapterCount = 0, processedCount = 0;
// Iterate through all of the adapters
for (IP_ADAPTER_ADDRESSES* adapter = adapter_addresses; adapter; adapter = adapter->Next)
{
if (adapter->OperStatus != IfOperStatusUp)
continue;
adapterCount++;
bool isDefaultRoute = adapter->IfIndex == defaultRouteIfIndex;
if ((options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) && !isDefaultRoute)
FF_DEBUG("Processing adapter %d: IfIndex=%u, IfType=%u, OperStatus=%u",
adapterCount, (unsigned)adapter->IfIndex, (unsigned)adapter->IfType, (unsigned)adapter->OperStatus);
if (adapter->OperStatus != IfOperStatusUp)
{
FF_DEBUG("Skipping adapter %u (not operational, status=%d)", (unsigned)adapter->IfIndex, adapter->OperStatus);
continue;
}
bool isLoop = adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK;
if (isLoop && !(options->showType & FF_LOCALIP_TYPE_LOOP_BIT))
continue;
FF_DEBUG("Adapter %u: isLoopback=%s", (unsigned)adapter->IfIndex, isLoop ? "true" : "false");
bool newIp = true;
if (isLoop && !(options->showType & FF_LOCALIP_TYPE_LOOP_BIT))
{
FF_DEBUG("Skipping loopback adapter %u (loopback not requested)", (unsigned)adapter->IfIndex);
continue;
}
char name[128];
WideCharToMultiByte(CP_UTF8, 0, adapter->FriendlyName, -1, name, ARRAY_SIZE(name), NULL, NULL);
if (options->namePrefix.length && strncmp(name, options->namePrefix.chars, options->namePrefix.length) != 0)
continue;
FF_DEBUG("Adapter %u name: '%s'", (unsigned)adapter->IfIndex, name);
if (options->showType & FF_LOCALIP_TYPE_MAC_BIT && adapter->PhysicalAddressLength == 6)
if (options->namePrefix.length && strncmp(name, options->namePrefix.chars, options->namePrefix.length) != 0)
{
char addressBuffer[32];
uint8_t* ptr = adapter->PhysicalAddress;
snprintf(addressBuffer, ARRAY_SIZE(addressBuffer), "%02x:%02x:%02x:%02x:%02x:%02x",
ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
addNewIp(results, name, addressBuffer, -1, newIp, isDefaultRoute);
newIp = false;
FF_DEBUG("Skipping adapter %u (name doesn't match prefix '%.*s')",
(unsigned)adapter->IfIndex, (int)options->namePrefix.length, options->namePrefix.chars);
continue;
}
if (options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT)
{
if (!((options->showType & FF_LOCALIP_TYPE_IPV4_BIT) && ffNetifGetDefaultRouteV4()->ifIndex == adapter->IfIndex) &&
!((options->showType & FF_LOCALIP_TYPE_IPV6_BIT) && ffNetifGetDefaultRouteV6()->ifIndex == adapter->IfIndex))
{
FF_DEBUG("Skipping interface %u (not default route interface)", (unsigned)adapter->IfIndex);
continue;
}
}
processedCount++;
FF_DEBUG("Creating result item for adapter %u ('%s')", (unsigned)adapter->IfIndex, name);
FFLocalIpResult* item = (FFLocalIpResult*) ffListAdd(results);
ffStrbufInitS(&item->name, name);
ffStrbufInit(&item->ipv4);
ffStrbufInit(&item->ipv6);
ffStrbufInit(&item->mac);
ffStrbufInit(&item->flags);
item->defaultRoute = FF_LOCALIP_TYPE_NONE;
item->speed = -1;
item->mtu = -1;
uint32_t typesToAdd = options->showType & (FF_LOCALIP_TYPE_IPV4_BIT | FF_LOCALIP_TYPE_IPV6_BIT | FF_LOCALIP_TYPE_ALL_IPS_BIT);
FF_DEBUG("Types to add for adapter %u: 0x%X", (unsigned)adapter->IfIndex, typesToAdd);
FF_MAYBE_UNUSED int ipv4Count = 0, ipv6Count = 0;
for (IP_ADAPTER_UNICAST_ADDRESS* ifa = adapter->FirstUnicastAddress; ifa; ifa = ifa->Next)
{
FF_DEBUG("Processing unicast address: family=%d, DadState=%d",
ifa->Address.lpSockaddr->sa_family, ifa->DadState);
if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT) && ifa->DadState != IpDadStatePreferred)
{
FF_DEBUG("Skipping address (DadState=%d, not preferred)", ifa->DadState);
continue;
}
if (ifa->Address.lpSockaddr->sa_family == AF_INET)
{
if (!(typesToAdd & (FF_LOCALIP_TYPE_IPV4_BIT | FF_LOCALIP_TYPE_ALL_IPS_BIT))) continue;
if (!(typesToAdd & (FF_LOCALIP_TYPE_IPV4_BIT | FF_LOCALIP_TYPE_ALL_IPS_BIT)))
{
FF_DEBUG("Skipping IPv4 address (not requested in typesToAdd=0x%X)", typesToAdd);
continue;
}
bool isDefaultRoute = ((options->showType & FF_LOCALIP_TYPE_IPV4_BIT) && ffNetifGetDefaultRouteV4()->ifIndex == adapter->IfIndex);
if ((options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) && !isDefaultRoute)
{
FF_DEBUG("Skipping IPv4 address (not on default route interface)");
continue;
}
SOCKADDR_IN* ipv4 = (SOCKADDR_IN*) ifa->Address.lpSockaddr;
char addressBuffer[INET_ADDRSTRLEN + 6];
@@ -146,15 +174,30 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
snprintf(addressBuffer + len, 6, "/%u", (unsigned) ifa->OnLinkPrefixLength);
}
addNewIp(results, name, addressBuffer, AF_INET, newIp, isDefaultRoute);
newIp = false;
FF_DEBUG("Adding IPv4 address: %s (isDefaultRoute=%s)", addressBuffer, isDefaultRoute ? "true" : "false");
if (item->ipv4.length) ffStrbufAppendC(&item->ipv4, ',');
ffStrbufAppendS(&item->ipv4, addressBuffer);
if (isDefaultRoute) item->defaultRoute |= FF_LOCALIP_TYPE_IPV4_BIT;
ipv4Count++;
typesToAdd &= ~(unsigned) FF_LOCALIP_TYPE_IPV4_BIT;
if (typesToAdd == 0) break;
}
else if (ifa->Address.lpSockaddr->sa_family == AF_INET6)
{
if (!(typesToAdd & (FF_LOCALIP_TYPE_IPV6_BIT | FF_LOCALIP_TYPE_ALL_IPS_BIT))) continue;
if (!(typesToAdd & (FF_LOCALIP_TYPE_IPV6_BIT | FF_LOCALIP_TYPE_ALL_IPS_BIT)))
{
FF_DEBUG("Skipping IPv6 address (not requested in typesToAdd=0x%X)", typesToAdd);
continue;
}
bool isDefaultRoute = ((options->showType & FF_LOCALIP_TYPE_IPV6_BIT) && ffNetifGetDefaultRouteV6()->ifIndex == adapter->IfIndex);
if ((options->showType & FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT) && !isDefaultRoute)
{
FF_DEBUG("Skipping IPv6 address (not on default route interface)");
continue;
}
SOCKADDR_IN6* ipv6 = (SOCKADDR_IN6*) ifa->Address.lpSockaddr;
char addressBuffer[INET6_ADDRSTRLEN + 6];
@@ -166,25 +209,45 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results)
snprintf(addressBuffer + len, 6, "/%u", (unsigned) ifa->OnLinkPrefixLength);
}
addNewIp(results, name, addressBuffer, AF_INET6, newIp, isDefaultRoute);
newIp = false;
FF_DEBUG("Adding IPv6 address: %s (isDefaultRoute=%s)", addressBuffer, isDefaultRoute ? "true" : "false");
if (item->ipv6.length) ffStrbufAppendC(&item->ipv6, ',');
ffStrbufAppendS(&item->ipv6, addressBuffer);
if (isDefaultRoute) item->defaultRoute |= FF_LOCALIP_TYPE_IPV6_BIT;
ipv6Count++;
typesToAdd &= ~(unsigned) FF_LOCALIP_TYPE_IPV6_BIT;
if (typesToAdd == 0) break;
}
}
if (!newIp)
FF_DEBUG("Adapter %u: collected %d IPv4 and %d IPv6 addresses", (unsigned)adapter->IfIndex, ipv4Count, ipv6Count);
if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT)
{
FFLocalIpResult* result = FF_LIST_GET(FFLocalIpResult, *results, results->length - 1);
if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT)
result->speed = (int32_t) (adapter->ReceiveLinkSpeed / 1000000);
if (options->showType & FF_LOCALIP_TYPE_MTU_BIT)
result->mtu = (int32_t) adapter->Mtu;
if (options->showType & FF_LOCALIP_TYPE_FLAGS_BIT)
ffLocalIpFillNIFlags(&result->flags, adapter->Flags, niFlagOptions);
item->speed = (int32_t) (adapter->ReceiveLinkSpeed / 1000000);
FF_DEBUG("Adapter %u speed: %d Mbps (raw: %llu)", (unsigned)adapter->IfIndex, item->speed, adapter->ReceiveLinkSpeed);
}
if (options->showType & FF_LOCALIP_TYPE_MTU_BIT)
{
item->mtu = (int32_t) adapter->Mtu;
FF_DEBUG("Adapter %u MTU: %d", (unsigned)adapter->IfIndex, item->mtu);
}
if (options->showType & FF_LOCALIP_TYPE_FLAGS_BIT)
{
ffLocalIpFillNIFlags(&item->flags, adapter->Flags, niFlagOptions);
FF_DEBUG("Adapter %u flags: 0x%lX -> '%s'", (unsigned)adapter->IfIndex, adapter->Flags, item->flags.chars);
}
if (options->showType & FF_LOCALIP_TYPE_MAC_BIT && adapter->PhysicalAddressLength == 6)
{
uint8_t* ptr = adapter->PhysicalAddress;
ffStrbufSetF(&item->mac, "%02x:%02x:%02x:%02x:%02x:%02x", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]);
FF_DEBUG("Adapter %u MAC: %s", (unsigned)adapter->IfIndex, item->mac.chars);
}
}
FF_DEBUG("Local IP detection completed: scanned %d adapters, processed %d, results count: %u",
adapterCount, processedCount, results->length);
return NULL;
}
+1 -1
View File
@@ -191,7 +191,7 @@ static void getBestBus(FFDBusData* data, FFMediaResult* result)
getBusProperties(data, FF_DBUS_MPRIS_PREFIX "plasma-browser-integration", result)
) return;
DBusMessage* reply = ffDBusGetMethodReply(data, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListNames", NULL);
DBusMessage* reply = ffDBusGetMethodReply(data, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListNames", NULL, NULL);
if(reply == NULL)
return;
+1 -1
View File
@@ -370,7 +370,7 @@ void ffDetectOSImpl(FFOSResult* os)
{
detectOS(os);
#ifdef __linux__
#if __linux__ || __GNU__
if(ffStrbufEqualS(&os->id, "ubuntu"))
getUbuntuFlavour(os);
else if(ffStrbufEqualS(&os->id, "debian"))
+1 -1
View File
@@ -55,7 +55,7 @@ const char* ffDetectPackages(FFPackagesResult* result, FFPackagesOptions* option
bool ffPackagesReadCache(FFstrbuf* cacheDir, FFstrbuf* cacheContent, const char* filePath, const char* packageId, uint32_t* result);
bool ffPackagesWriteCache(FFstrbuf* cacheDir, FFstrbuf* cacheContent, uint32_t num_elements);
#if defined(__linux__) || defined(__APPLE__)
#if defined(__linux__) || defined(__APPLE__) || defined(__GNU__)
uint32_t ffPackagesGetNix(FFstrbuf* baseDir, const char* dirname);
#endif
#ifndef _WIN32
+3 -2
View File
@@ -258,6 +258,8 @@ static uint32_t getAMSystem(FFstrbuf* baseDir)
static uint32_t getAMUser(void)
{
if (instance.state.platform.configDirs.length == 0) return 0;
// check if $XDG_CONFIG_HOME/appman/appman-config exists
FFstrbuf* baseDir = FF_LIST_GET(FFstrbuf, instance.state.platform.configDirs, 0);
uint32_t baseLen = baseDir->length;
@@ -446,7 +448,7 @@ static void getPackageCounts(FFstrbuf* baseDir, FFPackagesResult* packageCounts,
{
packageCounts->guixSystem += getGuixPackages(baseDir, "/run/current-system/profile");
}
if (!(options->disabled & FF_PACKAGES_FLAG_LINGLONG_BIT)) packageCounts->linglong += getNumElements(baseDir, "/var/lib/linglong/repo/refs/heads/main", true);
if (!(options->disabled & FF_PACKAGES_FLAG_LINGLONG_BIT)) packageCounts->linglong += getNumElements(baseDir, "/var/lib/linglong/layers", true);
if (!(options->disabled & FF_PACKAGES_FLAG_PACSTALL_BIT)) packageCounts->pacstall += getNumElements(baseDir, "/var/lib/pacstall/metadata", false);
if (!(options->disabled & FF_PACKAGES_FLAG_PISI_BIT)) packageCounts->pisi += getNumElements(baseDir, "/var/lib/pisi/package", true);
if (!(options->disabled & FF_PACKAGES_FLAG_PKGSRC_BIT)) packageCounts->pkgsrc += getNumElements(baseDir, "/usr/pkg/pkgdb", DT_DIR);
@@ -517,7 +519,6 @@ void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options)
#endif
ffStrbufSet(&baseDir, &instance.state.platform.homeDir);
if (!(options->disabled & FF_PACKAGES_FLAG_NIX_BIT))
{
// Count packages from $HOME/.nix-profile
+1 -1
View File
@@ -16,7 +16,7 @@ const char* ffDetectProcesses(uint32_t* result)
{
if (
#ifdef _DIRENT_HAVE_D_TYPE
entry->d_type == DT_DIR &&
(entry->d_type == DT_DIR || entry->d_type == DT_UNKNOWN) &&
#endif
ffCharIsDigit(entry->d_name[0]))
++num;
+1 -1
View File
@@ -16,7 +16,7 @@ const char* ffDetectSwap(FFlist* result)
if (kvms)
{
const char* swapAuto = get_driver_parameter(kvms, "swap_auto", NULL, NULL);
if (swapAuto)
if (swapAuto)
ffStrbufSetStatic(&swap->name, swapAuto[0] == 'y' ? "Auto" : "Manual");
unload_driver_settings(kvms);
}
+1 -1
View File
@@ -266,7 +266,7 @@ static bool detectRio(FFTerminalFontResult* terminalFont)
return true;
}
void ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont);
bool ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont);
static bool detectTerminalFontCommon(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont)
{
@@ -13,6 +13,12 @@
const char* detectTermux(FFTerminalFontResult* terminalFont)
{
if(!ffPathExists(FF_TERMUX_FONT_PATH, FF_PATHTYPE_FILE))
{
ffFontInitCopy(&terminalFont->font, "monospace");
return NULL;
}
#ifdef FF_HAVE_FREETYPE
FF_LIBRARY_LOAD(freetype, "dlopen libfreetype"FF_LIBRARY_EXTENSION " failed", "libfreetype"FF_LIBRARY_EXTENSION, 2)
@@ -53,19 +59,15 @@ exit:
#endif
}
void ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont)
bool ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont)
{
if(ffStrbufCompS(&terminal->processName, "com.termux") != 0)
if(ffStrbufEqualS(&terminal->processName, "com.termux"))
ffStrbufSetS(&terminalFont->error, detectTermux(terminalFont));
else
{
ffStrbufSetS(&terminalFont->error, "Unsupported terminal");
return;
bool ffDetectTerminalFontPlatformLinux(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont);
return ffDetectTerminalFontPlatformLinux(terminal, terminalFont);
}
if(!ffPathExists(FF_TERMUX_FONT_PATH, FF_PATHTYPE_FILE))
{
ffFontInitCopy(&terminalFont->font, "monospace");
return;
}
ffStrbufSetS(&terminalFont->error, detectTermux(terminalFont));
return true;
}
@@ -91,7 +91,7 @@ static void detectWarpTerminal(FFTerminalFontResult* terminalFont)
ffFontInitValues(&terminalFont->font, fontName.UTF8String, fontSize.UTF8String);
}
void ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont)
bool ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont)
{
if(ffStrbufIgnCaseEqualS(&terminal->processName, "iterm.app") ||
ffStrbufStartsWithIgnCaseS(&terminal->processName, "iTermServer-"))
@@ -100,4 +100,7 @@ void ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFo
detectAppleTerminal(terminalFont);
else if(ffStrbufIgnCaseEqualS(&terminal->processName, "WarpTerminal"))
detectWarpTerminal(terminalFont);
else
return false;
return true;
}
@@ -16,26 +16,26 @@ static const char* getSystemMonospaceFont(void)
if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, "Cinnamon"))
{
const char* systemMonospaceFont = ffSettingsGet("/org/cinnamon/desktop/interface/monospace-font-name", "org.cinnamon.desktop.interface", NULL, "monospace-font-name", FF_VARIANT_TYPE_STRING).strValue;
const char* systemMonospaceFont = ffSettingsGetGnome("/org/cinnamon/desktop/interface/monospace-font-name", "org.cinnamon.desktop.interface", NULL, "monospace-font-name", FF_VARIANT_TYPE_STRING).strValue;
if(ffStrSet(systemMonospaceFont))
return systemMonospaceFont;
}
else if(ffStrbufIgnCaseEqualS(&wmde->dePrettyName, "Mate"))
{
const char* systemMonospaceFont = ffSettingsGet("/org/mate/interface/monospace-font-name", "org.mate.interface", NULL, "monospace-font-name", FF_VARIANT_TYPE_STRING).strValue;
const char* systemMonospaceFont = ffSettingsGetGnome("/org/mate/interface/monospace-font-name", "org.mate.interface", NULL, "monospace-font-name", FF_VARIANT_TYPE_STRING).strValue;
if(ffStrSet(systemMonospaceFont))
return systemMonospaceFont;
}
return ffSettingsGet("/org/gnome/desktop/interface/monospace-font-name", "org.gnome.desktop.interface", NULL, "monospace-font-name", FF_VARIANT_TYPE_STRING).strValue;
return ffSettingsGetGnome("/org/gnome/desktop/interface/monospace-font-name", "org.gnome.desktop.interface", NULL, "monospace-font-name", FF_VARIANT_TYPE_STRING).strValue;
}
static void detectKgx(FFTerminalFontResult* terminalFont)
{
// kgx (gnome console) doesn't support profiles
if(!ffSettingsGet("/org/gnome/Console/use-system-font", "org.gnome.Console", NULL, "use-system-font", FF_VARIANT_TYPE_BOOL).boolValue)
if(!ffSettingsGetGnome("/org/gnome/Console/use-system-font", "org.gnome.Console", NULL, "use-system-font", FF_VARIANT_TYPE_BOOL).boolValue)
{
FF_AUTO_FREE const char* fontName = ffSettingsGet("/org/gnome/Console/custom-font", "org.gnome.Console", NULL, "custom-font", FF_VARIANT_TYPE_STRING).strValue;
FF_AUTO_FREE const char* fontName = ffSettingsGetGnome("/org/gnome/Console/custom-font", "org.gnome.Console", NULL, "custom-font", FF_VARIANT_TYPE_STRING).strValue;
if(ffStrSet(fontName))
ffFontInitPango(&terminalFont->font, fontName);
else
@@ -53,9 +53,9 @@ static void detectKgx(FFTerminalFontResult* terminalFont)
static void detectPtyxis(FFTerminalFontResult* terminalFont)
{
if(!ffSettingsGet("/org/gnome/Ptyxis/use-system-font", "org.gnome.Ptyxis", NULL, "use-system-font", FF_VARIANT_TYPE_BOOL).boolValue)
if(!ffSettingsGetGnome("/org/gnome/Ptyxis/use-system-font", "org.gnome.Ptyxis", NULL, "use-system-font", FF_VARIANT_TYPE_BOOL).boolValue)
{
FF_AUTO_FREE const char* fontName = ffSettingsGet("/org/gnome/Ptyxis/font-name", "org.gnome.Ptyxis", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue;
FF_AUTO_FREE const char* fontName = ffSettingsGetGnome("/org/gnome/Ptyxis/font-name", "org.gnome.Ptyxis", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue;
if(ffStrSet(fontName))
ffFontInitPango(&terminalFont->font, fontName);
else
@@ -167,7 +167,7 @@ static void detectXFCETerminal(FFTerminalFontResult* terminalFont)
});
}
if(configFound && (useSysFont.length == 0 || ffStrbufIgnCaseCompS(&useSysFont, "false") == 0))
if(configFound && (useSysFont.length == 0 || ffStrbufIgnCaseEqualS(&useSysFont, "false")))
{
if(fontName.length == 0)
ffStrbufAppendF(&terminalFont->error, "Couldn't find FontName in %s", path);
@@ -433,7 +433,13 @@ static void detectHaikuTerminal(FFTerminalFontResult* terminalFont)
}
#endif
void ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont)
bool
#ifdef __ANDROID__
ffDetectTerminalFontPlatformLinux
#else
ffDetectTerminalFontPlatform
#endif
(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont)
{
if(ffStrbufIgnCaseEqualS(&terminal->processName, "konsole"))
detectKonsole(terminalFont, "konsolerc");
@@ -477,4 +483,7 @@ void ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFo
#endif
else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "termite"))
detectFromConfigFile("termite/config", "font =", terminalFont);
else
return false;
return true;
}
@@ -274,7 +274,7 @@ static void detectWarp(FFTerminalFontResult* terminalFont)
ffFontInitValues(&terminalFont->font, fontName.chars, fontSize.chars);
}
void ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont)
bool ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFontResult* terminalFont)
{
if(ffStrbufIgnCaseEqualS(&terminal->processName, "Windows Terminal") ||
ffStrbufIgnCaseEqualS(&terminal->processName, "WindowsTerminal.exe"))
@@ -287,4 +287,7 @@ void ffDetectTerminalFontPlatform(const FFTerminalResult* terminal, FFTerminalFo
detectConEmu(terminalFont);
else if(ffStrbufStartsWithIgnCaseS(&terminal->processName, "warp"))
detectWarp(terminalFont);
else
return false;
return true;
}
+6 -5
View File
@@ -85,8 +85,9 @@ static bool getShellVersionFish(FFstrbuf* exe, FFstrbuf* version)
if(!getExeVersionRaw(exe, version))
return false;
//fish, version 3.6.0
ffStrbufSubstrAfterLastC(version, ' ');
//fish, version 4.0.2-1 (Built by MSYS2 project)
ffStrbufSubstrAfterFirstS(version, "version ");
ffStrbufSubstrBeforeFirstC(version, ' ');
return true;
}
@@ -579,10 +580,10 @@ static bool getTerminalVersionZed(FFstrbuf* exe, FFstrbuf* version)
#ifndef _WIN32
static bool getTerminalVersionKitty(FFstrbuf* exe, FFstrbuf* version)
{
#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__GNU__)
char buffer[1024] = {};
if (
#ifdef __linux__
#if __linux__ || __GNU__
ffReadFileData(FASTFETCH_TARGET_DIR_USR "/lib64/kitty/kitty/constants.py", ARRAY_SIZE(buffer) - 1, buffer) ||
ffReadFileData(FASTFETCH_TARGET_DIR_USR "/lib/kitty/kitty/constants.py", ARRAY_SIZE(buffer) - 1, buffer)
#else
@@ -767,7 +768,7 @@ bool fftsGetTerminalVersion(FFstrbuf* processName, FF_MAYBE_UNUSED FFstrbuf* exe
#endif
#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__sun) || defined(__NetBSD__) || defined(__HAIKU__)
#if defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__sun) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__GNU__)
if(ffStrbufStartsWithIgnCaseS(processName, "gnome-terminal"))
return getTerminalVersionGnome(exe, version);
@@ -31,13 +31,14 @@ static pid_t getShellInfo(FFShellResult* result, pid_t pid)
userShellName = instance.state.platform.userShell.chars + index + 1;
}
while (ffProcessGetBasicInfoLinux(pid, &result->processName, &ppid, &tty) == NULL)
while (pid > 1 && ffProcessGetBasicInfoLinux(pid, &result->processName, &ppid, &tty) == NULL)
{
if (!ffStrbufEqualS(&result->processName, userShellName))
{
//Common programs that are between terminal and own process, but are not the shell
if(
// tty < 0 || //A shell should connect to a tty
pid == 1 || // init/systemd
ffStrbufEqualS(&result->processName, "sh") || //This prevents us from detecting things like pipes and redirects, i hope nobody uses plain `sh` as shell
ffStrbufEqualS(&result->processName, "sudo") ||
ffStrbufEqualS(&result->processName, "su") ||
@@ -50,7 +51,6 @@ static pid_t getShellInfo(FFShellResult* result, pid_t pid)
ffStrbufEqualS(&result->processName, "perf") ||
ffStrbufEqualS(&result->processName, "guake-wrapped") ||
ffStrbufEqualS(&result->processName, "time") ||
ffStrbufContainS(&result->processName, "hyfetch") || //when hyfetch uses fastfetch as backend
ffStrbufEqualS(&result->processName, "clifm") || //https://github.com/leo-arch/clifm/issues/289
ffStrbufEqualS(&result->processName, "valgrind") ||
ffStrbufEqualS(&result->processName, "fastfetch") || //#994
@@ -74,17 +74,18 @@ static pid_t getShellInfo(FFShellResult* result, pid_t pid)
ffProcessGetInfoLinux(pid, &result->processName, &result->exe, &result->exeName, &result->exePath);
break;
}
return ppid;
return pid > 1 ? ppid : 0;
}
static pid_t getTerminalInfo(FFTerminalResult* result, pid_t pid)
{
pid_t ppid = 0;
while (ffProcessGetBasicInfoLinux(pid, &result->processName, &ppid, NULL) == NULL)
while (pid > 1 && ffProcessGetBasicInfoLinux(pid, &result->processName, &ppid, NULL) == NULL)
{
//Known shells
if (
pid == 1 || // init/systemd
ffStrbufEqualS(&result->processName, "sudo") ||
ffStrbufEqualS(&result->processName, "su") ||
ffStrbufEqualS(&result->processName, "sh") ||
@@ -109,9 +110,8 @@ static pid_t getTerminalInfo(FFTerminalResult* result, pid_t pid)
ffStrbufEqualS(&result->processName, "chezmoi") || // #762
ffStrbufEqualS(&result->processName, "proot") ||
ffStrbufEqualS(&result->processName, "script") ||
ffStrbufEqualS(&result->processName, "init") ||
ffStrbufEqualS(&result->processName, "systemd") ||
#ifdef __linux__
ffStrbufStartsWithS(&result->processName, "Relay(") || // Unknown process in WSL2
ffStrbufStartsWithS(&result->processName, "flatpak-") || // #707
#endif
ffStrbufEndsWithS(&result->processName, ".sh")
@@ -145,7 +145,7 @@ static pid_t getTerminalInfo(FFTerminalResult* result, pid_t pid)
ffProcessGetInfoLinux(pid, &result->processName, &result->exe, &result->exeName, &result->exePath);
break;
}
return ppid;
return pid > 1 ? ppid : 0;
}
static bool getTerminalInfoByPidEnv(FFTerminalResult* result, const char* pidEnv)
@@ -241,7 +241,7 @@ static void getTerminalFromEnv(FFTerminalResult* result)
}
#endif
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__GNU__)
//Konsole
else if(
getenv("KONSOLE_VERSION") != NULL
@@ -334,7 +334,7 @@ static void setTerminalInfoDetails(FFTerminalResult* result)
else if(ffStrbufEqualS(&result->processName, "com.termux"))
ffStrbufInitStatic(&result->prettyName, "Termux");
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
#elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__GNU__)
else if(ffStrbufStartsWithS(&result->processName, "gnome-terminal"))
ffStrbufInitStatic(&result->prettyName, "GNOME Terminal");
@@ -33,7 +33,6 @@ static uint32_t getShellInfo(FFShellResult* result, uint32_t pid)
ffStrbufIgnCaseEqualS(&result->prettyName, "python") || // python on windows generates shim executables
ffStrbufIgnCaseEqualS(&result->prettyName, "fastfetch") || // scoop warps the real binaries with a "shim" exe
ffStrbufIgnCaseEqualS(&result->prettyName, "flashfetch") ||
ffStrbufIgnCaseEqualS(&result->prettyName, "hyfetch") || // uses fastfetch as backend
ffStrbufContainIgnCaseS(&result->prettyName, "debug") ||
ffStrbufContainIgnCaseS(&result->prettyName, "time") ||
ffStrbufStartsWithIgnCaseS(&result->prettyName, "ConEmu") // https://github.com/fastfetch-cli/fastfetch/issues/488#issuecomment-1619982014
+1 -1
View File
@@ -7,7 +7,7 @@ const char* ffDetectTheme(FFThemeResult* result)
{
const FFDisplayServerResult* wmde = ffConnectDisplayServer();
if(ffStrbufIgnCaseCompS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY) == 0)
if(ffStrbufIgnCaseEqualS(&wmde->wmProtocolName, FF_WM_PROTOCOL_TTY))
return "Theme isn't supported in TTY";
const FFQtResult* plasma = ffDetectQt();
+4 -2
View File
@@ -26,13 +26,15 @@ const char* ffDetectUptime(FFUptimeResult* result)
}
#endif
#ifndef __GNU__
struct timespec uptime;
if (clock_gettime(CLOCK_BOOTTIME, &uptime) != 0)
return "clock_gettime(CLOCK_BOOTTIME) failed";
result->uptime = (uint64_t) uptime.tv_sec * 1000 + (uint64_t) uptime.tv_nsec / 1000000;
result->bootTime = ffTimeGetNow() - result->uptime;
return NULL;
#else
return "read(/proc/uptime) failed";
#endif
}
+2 -4
View File
@@ -1,13 +1,11 @@
#include "uptime.h"
#include "common/time.h"
#include <realtimeapiset.h>
#include <sysinfoapi.h>
const char* ffDetectUptime(FFUptimeResult* result)
{
// According to MSDN, this function only fails if it's called with NULL
QueryUnbiasedInterruptTime(&result->uptime);
result->uptime /= 10000; // Convert from 100-nanosecond intervals to milliseconds
result->uptime = GetTickCount64();
result->bootTime = ffTimeGetNow() - result->uptime;
return NULL;
}
+2 -2
View File
@@ -10,7 +10,7 @@
#define setutxent setutent
#define getutxent getutent
#endif
#ifdef __linux__
#if __linux__ || __GNU__
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
@@ -40,7 +40,7 @@ next:
ffStrbufInitS(&user->hostName, n->ut_host);
ffStrbufInitS(&user->sessionName, n->ut_line);
ffStrbufInit(&user->clientIp);
#ifdef __linux__
#if __linux__ || __GNU__
bool isIpv6 = false;
for (int i = 1; i < 4; ++i) {
if (n->ut_addr_v6[i] != 0) {
+2
View File
@@ -54,6 +54,8 @@
#define FF_SYSNAME "NetBSD"
#elif defined(__HAIKU__)
#define FF_SYSNAME "Haiku"
#elif defined(__GNU__)
#define FF_SYSNAME "GNU"
#else
#define FF_SYSNAME "Unknown"
#endif
+1 -1
View File
@@ -57,7 +57,7 @@ static const char* detectWifiWithNm(FFWifiResult* item, FFstrbuf* buffer)
{
FF_DEBUG("Getting device by IP interface name");
DBusMessage* device = ffDBusGetMethodReply(&dbus, "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.NetworkManager", "GetDeviceByIpIface", item->inf.description.chars);
DBusMessage* device = ffDBusGetMethodReply(&dbus, "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager", "org.freedesktop.NetworkManager", "GetDeviceByIpIface", item->inf.description.chars, NULL);
if(!device)
{
FF_DEBUG("GetDeviceByIpIface failed for interface %s", item->inf.description.chars);
+64 -53
View File
@@ -13,6 +13,17 @@ const char* ffDetectWMPlugin(FF_MAYBE_UNUSED FFstrbuf* pluginName)
return "Not supported on this platform";
}
static bool extractCommonWmVersion(const char* line, FF_MAYBE_UNUSED uint32_t len, void *userdata)
{
int count = 0;
sscanf(line, "%*d.%*d.%*d%n", &count);
if (count == 0) return true;
ffStrbufSetNS((FFstrbuf*) userdata, len, line);
return false;
}
#if !__ANDROID__
static bool extractHyprlandVersion(const char* line, uint32_t len, void *userdata)
{
if (line[0] != 'v') return true;
@@ -128,6 +139,48 @@ static const char* getSway(FFstrbuf* result)
return "Failed to run command `sway --version`";
}
static const char* getLabwc(FFstrbuf* result)
{
FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate();
const char* error = ffFindExecutableInPath("labwc", &path);
if (error) return "Failed to find labwc executable path";
ffBinaryExtractStrings(path.chars, extractCommonWmVersion, result, (uint32_t) strlen("0.0.0"));
if (result->length > 0) return NULL;
if (ffProcessAppendStdOut(result, (char* const[]){
path.chars,
"--version",
NULL
}) == NULL)
{ // labwc 0.9.0 (+xwayland +nls +rsvg +libsfdo)
ffStrbufSubstrAfterFirstC(result, ' ');
ffStrbufSubstrBeforeFirstC(result, ' ');
return NULL;
}
return "Failed to run command `labwc --version`";
}
#ifdef __linux__
static const char* getWslg(FFstrbuf* result)
{
if (!ffAppendFileBuffer("/mnt/wslg/versions.txt", result))
return "Failed to read /mnt/wslg/versions.txt";
if (!ffStrbufStartsWithS(result, "WSLg "))
return "Failed to find WSLg version";
ffStrbufSubstrBeforeFirstC(result, '\n');
ffStrbufSubstrBeforeFirstC(result, '+');
ffStrbufSubstrAfterFirstC(result, ':');
ffStrbufTrimLeft(result, ' ');
return NULL;
}
#endif
#endif // !__ANDROID__
static bool extractI3Version(const char* line, FF_MAYBE_UNUSED uint32_t len, void *userdata)
{
int count = 0;
@@ -161,31 +214,6 @@ static const char* getI3(FFstrbuf* result)
return "Failed to run command `i3 --version`";
}
static const char* getWslg(FFstrbuf* result)
{
if (!ffAppendFileBuffer("/mnt/wslg/versions.txt", result))
return "Failed to read /mnt/wslg/versions.txt";
if (!ffStrbufStartsWithS(result, "WSLg "))
return "Failed to find WSLg version";
ffStrbufSubstrBeforeFirstC(result, '\n');
ffStrbufSubstrBeforeFirstC(result, '+');
ffStrbufSubstrAfterFirstC(result, ':');
ffStrbufTrimLeft(result, ' ');
return NULL;
}
static bool extractCommonWmVersion(const char* line, FF_MAYBE_UNUSED uint32_t len, void *userdata)
{
int count = 0;
sscanf(line, "%*d.%*d.%*d%n", &count);
if (count == 0) return true;
ffStrbufSetNS((FFstrbuf*) userdata, len, line);
return false;
}
static const char* getCtwm(FFstrbuf* result)
{
FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate();
@@ -255,45 +283,31 @@ static const char* getOpenbox(FFstrbuf* result)
return "Failed to run command `openbox --version`";
}
static const char* getLabwc(FFstrbuf* result)
{
FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate();
const char* error = ffFindExecutableInPath("labwc", &path);
if (error) return "Failed to find labwc executable path";
ffBinaryExtractStrings(path.chars, extractCommonWmVersion, result, (uint32_t) strlen("0.0.0"));
if (result->length > 0) return NULL;
if (ffProcessAppendStdOut(result, (char* const[]){
path.chars,
"--version",
NULL
}) == NULL)
{ // labwc 0.9.0 (+xwayland +nls +rsvg +libsfdo)
ffStrbufSubstrAfterFirstC(result, ' ');
ffStrbufSubstrBeforeFirstC(result, ' ');
return NULL;
}
return "Failed to run command `labwc --version`";
}
const char* ffDetectWMVersion(const FFstrbuf* wmName, FFstrbuf* result, FF_MAYBE_UNUSED FFWMOptions* options)
{
if (!wmName)
return "No WM detected";
#if !__ANDROID__
// Wayland compositors
if (ffStrbufIgnCaseEqualS(wmName, "Hyprland"))
return getHyprland(result);
if (ffStrbufEqualS(wmName, "sway"))
return getSway(result);
if (ffStrbufEqualS(wmName, "i3"))
return getI3(result);
if (ffStrbufEqualS(wmName, "labwc"))
return getLabwc(result);
#if __linux__
if (ffStrbufEqualS(wmName, "WSLg"))
return getWslg(result);
#endif
#endif
// X11 WMs
if (ffStrbufEqualS(wmName, "i3"))
return getI3(result);
if (ffStrbufEqualS(wmName, "ctwm"))
return getCtwm(result);
@@ -304,8 +318,5 @@ const char* ffDetectWMVersion(const FFstrbuf* wmName, FFstrbuf* result, FF_MAYBE
if (ffStrbufEqualS(wmName, "Openbox"))
return getOpenbox(result);
if (ffStrbufEqualS(wmName, "labwc"))
return getLabwc(result);
return "Unsupported WM";
}
+16 -13
View File
@@ -44,7 +44,7 @@ static bool detectWMThemeFromConfigFile(const char* configFile, const char* them
static bool detectWMThemeFromSettings(const char* dconfKey, const char* gsettingsSchemaName, const char* gsettingsPath, const char* gsettingsKey, FFstrbuf* themeOrError)
{
const char* theme = ffSettingsGet(dconfKey, gsettingsSchemaName, gsettingsPath, gsettingsKey, FF_VARIANT_TYPE_STRING).strValue;
const char* theme = ffSettingsGetGnome(dconfKey, gsettingsSchemaName, gsettingsPath, gsettingsKey, FF_VARIANT_TYPE_STRING).strValue;
if(!ffStrSet(theme))
{
@@ -80,7 +80,7 @@ ok:
static bool detectMutter(FFstrbuf* themeOrError)
{
const char* theme = ffSettingsGet("/org/gnome/shell/extensions/user-theme/name", "org.gnome.shell.extensions.user-theme", NULL, "name", FF_VARIANT_TYPE_STRING).strValue;
const char* theme = ffSettingsGetGnome("/org/gnome/shell/extensions/user-theme/name", "org.gnome.shell.extensions.user-theme", NULL, "name", FF_VARIANT_TYPE_STRING).strValue;
if(ffStrSet(theme))
{
ffStrbufAppendS(themeOrError, theme);
@@ -92,8 +92,8 @@ static bool detectMutter(FFstrbuf* themeOrError)
static bool detectMuffin(FFstrbuf* themeOrError)
{
FF_AUTO_FREE const char* name = ffSettingsGet("/org/cinnamon/theme/name", "org.cinnamon.theme", NULL, "name", FF_VARIANT_TYPE_STRING).strValue;
FF_AUTO_FREE const char* theme = ffSettingsGet("/org/cinnamon/desktop/wm/preferences/theme", "org.cinnamon.desktop.wm.preferences", NULL, "theme", FF_VARIANT_TYPE_STRING).strValue;
FF_AUTO_FREE const char* name = ffSettingsGetGnome("/org/cinnamon/theme/name", "org.cinnamon.theme", NULL, "name", FF_VARIANT_TYPE_STRING).strValue;
FF_AUTO_FREE const char* theme = ffSettingsGetGnome("/org/cinnamon/desktop/wm/preferences/theme", "org.cinnamon.desktop.wm.preferences", NULL, "theme", FF_VARIANT_TYPE_STRING).strValue;
if(name == NULL && theme == NULL)
{
@@ -135,9 +135,9 @@ static bool detectOpenbox(const FFstrbuf* dePrettyName, FFstrbuf* themeOrError)
{
FF_STRBUF_AUTO_DESTROY absolutePath = ffStrbufCreateA(64);
const char *configFileSubpath = "openbox/rc.xml";
if (ffStrbufIgnCaseCompS(dePrettyName, "LXQt") == 0)
if (ffStrbufIgnCaseEqualS(dePrettyName, "LXQt"))
configFileSubpath = "openbox/lxqt-rc.xml";
else if (ffStrbufIgnCaseCompS(dePrettyName, "LXDE") == 0)
else if (ffStrbufIgnCaseEqualS(dePrettyName, "LXDE"))
configFileSubpath = "openbox/lxde-rc.xml";
if (!ffSearchUserConfigFile(&instance.state.platform.configDirs, configFileSubpath, &absolutePath))
@@ -197,16 +197,19 @@ bool ffDetectWmTheme(FFstrbuf* themeOrError)
return false;
}
if(ffStrbufIgnCaseCompS(&wm->wmPrettyName, FF_WM_PRETTY_KWIN) == 0)
if(ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_KWIN))
return detectWMThemeFromConfigFile("kwinrc", "theme =", "Breeze", themeOrError);
if(ffStrbufIgnCaseCompS(&wm->wmPrettyName, FF_WM_PRETTY_XFWM4) == 0)
if(
ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_XFWM4) ||
(ffStrbufIgnCaseEqualS(&wm->wmPrettyName, "labwc") && ffStrbufIgnCaseEqualS(&wm->dePrettyName, FF_DE_PRETTY_XFCE4))
)
return detectXFWM4(themeOrError);
if(ffStrbufIgnCaseCompS(&wm->wmPrettyName, FF_WM_PRETTY_MUTTER) == 0)
if(ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_MUTTER))
{
if(
ffStrbufIgnCaseCompS(&wm->dePrettyName, FF_DE_PRETTY_GNOME) == 0 ||
ffStrbufIgnCaseEqualS(&wm->dePrettyName, FF_DE_PRETTY_GNOME) ||
ffStrbufIgnCaseEqualS(&wm->dePrettyName, FF_DE_PRETTY_GNOME_CLASSIC)
)
return detectMutter(themeOrError);
@@ -214,13 +217,13 @@ bool ffDetectWmTheme(FFstrbuf* themeOrError)
return detectGTKThemeAsWMTheme(themeOrError);
}
if(ffStrbufIgnCaseCompS(&wm->wmPrettyName, FF_WM_PRETTY_MUFFIN) == 0)
if(ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_MUFFIN))
return detectMuffin(themeOrError);
if(ffStrbufIgnCaseCompS(&wm->wmPrettyName, FF_WM_PRETTY_MARCO) == 0)
if(ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_MARCO))
return detectWMThemeFromSettings("/org/mate/Marco/general/theme", "org.mate.Marco.general", NULL, "theme", themeOrError);
if(ffStrbufIgnCaseCompS(&wm->wmPrettyName, FF_WM_PRETTY_OPENBOX) == 0)
if(ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_OPENBOX))
return detectOpenbox(&wm->dePrettyName, themeOrError);
ffStrbufAppendS(themeOrError, "Unknown WM: ");

Some files were not shown because too many files have changed in this diff Show More